+ * MIT Licensed.
+ *
+ * BigNumber.prototype methods | BigNumber methods
+ * |
+ * absoluteValue abs | clone
+ * comparedTo | config set
+ * decimalPlaces dp | DECIMAL_PLACES
+ * dividedBy div | ROUNDING_MODE
+ * dividedToIntegerBy idiv | EXPONENTIAL_AT
+ * exponentiatedBy pow | RANGE
+ * integerValue | CRYPTO
+ * isEqualTo eq | MODULO_MODE
+ * isFinite | POW_PRECISION
+ * isGreaterThan gt | FORMAT
+ * isGreaterThanOrEqualTo gte | ALPHABET
+ * isInteger | isBigNumber
+ * isLessThan lt | maximum max
+ * isLessThanOrEqualTo lte | minimum min
+ * isNaN | random
+ * isNegative | sum
+ * isPositive |
+ * isZero |
+ * minus |
+ * modulo mod |
+ * multipliedBy times |
+ * negated |
+ * plus |
+ * precision sd |
+ * shiftedBy |
+ * squareRoot sqrt |
+ * toExponential |
+ * toFixed |
+ * toFormat |
+ * toFraction |
+ * toJSON |
+ * toNumber |
+ * toPrecision |
+ * toString |
+ * valueOf |
+ *
+ */
+
+
+var
+ isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,
+
+ mathceil = Math.ceil,
+ mathfloor = Math.floor,
+
+ bignumberError = '[BigNumber Error] ',
+ tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',
+
+ BASE = 1e14,
+ LOG_BASE = 14,
+ MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
+ // MAX_INT32 = 0x7fffffff, // 2^31 - 1
+ POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
+ SQRT_BASE = 1e7,
+
+ // EDITABLE
+ // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
+ // the arguments to toExponential, toFixed, toFormat, and toPrecision.
+ MAX = 1E9; // 0 to MAX_INT32
+
+
+/*
+ * Create and return a BigNumber constructor.
+ */
+function clone(configObject) {
+ var div, convertBase, parseNumeric,
+ P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },
+ ONE = new BigNumber(1),
+
+
+ //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------
+
+
+ // The default values below must be integers within the inclusive ranges stated.
+ // The values can also be changed at run-time using BigNumber.set.
+
+ // The maximum number of decimal places for operations involving division.
+ DECIMAL_PLACES = 20, // 0 to MAX
+
+ // The rounding mode used when rounding to the above decimal places, and when using
+ // toExponential, toFixed, toFormat and toPrecision, and round (default value).
+ // UP 0 Away from zero.
+ // DOWN 1 Towards zero.
+ // CEIL 2 Towards +Infinity.
+ // FLOOR 3 Towards -Infinity.
+ // HALF_UP 4 Towards nearest neighbour. If equidistant, up.
+ // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
+ // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
+ // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
+ // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
+ ROUNDING_MODE = 4, // 0 to 8
+
+ // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
+
+ // The exponent value at and beneath which toString returns exponential notation.
+ // Number type: -7
+ TO_EXP_NEG = -7, // 0 to -MAX
+
+ // The exponent value at and above which toString returns exponential notation.
+ // Number type: 21
+ TO_EXP_POS = 21, // 0 to MAX
+
+ // RANGE : [MIN_EXP, MAX_EXP]
+
+ // The minimum exponent value, beneath which underflow to zero occurs.
+ // Number type: -324 (5e-324)
+ MIN_EXP = -1e7, // -1 to -MAX
+
+ // The maximum exponent value, above which overflow to Infinity occurs.
+ // Number type: 308 (1.7976931348623157e+308)
+ // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
+ MAX_EXP = 1e7, // 1 to MAX
+
+ // Whether to use cryptographically-secure random number generation, if available.
+ CRYPTO = false, // true or false
+
+ // The modulo mode used when calculating the modulus: a mod n.
+ // The quotient (q = a / n) is calculated according to the corresponding rounding mode.
+ // The remainder (r) is calculated as: r = a - n * q.
+ //
+ // UP 0 The remainder is positive if the dividend is negative, else is negative.
+ // DOWN 1 The remainder has the same sign as the dividend.
+ // This modulo mode is commonly known as 'truncated division' and is
+ // equivalent to (a % n) in JavaScript.
+ // FLOOR 3 The remainder has the same sign as the divisor (Python %).
+ // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
+ // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
+ // The remainder is always positive.
+ //
+ // The truncated division, floored division, Euclidian division and IEEE 754 remainder
+ // modes are commonly used for the modulus operation.
+ // Although the other rounding modes can also be used, they may not give useful results.
+ MODULO_MODE = 1, // 0 to 9
+
+ // The maximum number of significant digits of the result of the exponentiatedBy operation.
+ // If POW_PRECISION is 0, there will be unlimited significant digits.
+ POW_PRECISION = 0, // 0 to MAX
+
+ // The format specification used by the BigNumber.prototype.toFormat method.
+ FORMAT = {
+ prefix: '',
+ groupSize: 3,
+ secondaryGroupSize: 0,
+ groupSeparator: ',',
+ decimalSeparator: '.',
+ fractionGroupSize: 0,
+ fractionGroupSeparator: '\xA0', // non-breaking space
+ suffix: ''
+ },
+
+ // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',
+ // '-', '.', whitespace, or repeated character.
+ // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+ ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
+
+
+ //------------------------------------------------------------------------------------------
+
+
+ // CONSTRUCTOR
+
+
+ /*
+ * The BigNumber constructor and exported function.
+ * Create and return a new instance of a BigNumber object.
+ *
+ * v {number|string|BigNumber} A numeric value.
+ * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.
+ */
+ function BigNumber(v, b) {
+ var alphabet, c, caseChanged, e, i, isNum, len, str,
+ x = this;
+
+ // Enable constructor call without `new`.
+ if (!(x instanceof BigNumber)) return new BigNumber(v, b);
+
+ if (b == null) {
+
+ if (v && v._isBigNumber === true) {
+ x.s = v.s;
+
+ if (!v.c || v.e > MAX_EXP) {
+ x.c = x.e = null;
+ } else if (v.e < MIN_EXP) {
+ x.c = [x.e = 0];
+ } else {
+ x.e = v.e;
+ x.c = v.c.slice();
+ }
+
+ return;
+ }
+
+ if ((isNum = typeof v == 'number') && v * 0 == 0) {
+
+ // Use `1 / n` to handle minus zero also.
+ x.s = 1 / v < 0 ? (v = -v, -1) : 1;
+
+ // Fast path for integers, where n < 2147483648 (2**31).
+ if (v === ~~v) {
+ for (e = 0, i = v; i >= 10; i /= 10, e++);
+
+ if (e > MAX_EXP) {
+ x.c = x.e = null;
+ } else {
+ x.e = e;
+ x.c = [v];
+ }
+
+ return;
+ }
+
+ str = String(v);
+ } else {
+
+ if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
+
+ x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
+ }
+
+ // Decimal point?
+ if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
+
+ // Exponential form?
+ if ((i = str.search(/e/i)) > 0) {
+
+ // Determine exponent.
+ if (e < 0) e = i;
+ e += +str.slice(i + 1);
+ str = str.substring(0, i);
+ } else if (e < 0) {
+
+ // Integer.
+ e = str.length;
+ }
+
+ } else {
+
+ // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
+ intCheck(b, 2, ALPHABET.length, 'Base');
+
+ // Allow exponential notation to be used with base 10 argument, while
+ // also rounding to DECIMAL_PLACES as with other bases.
+ if (b == 10) {
+ x = new BigNumber(v);
+ return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
+ }
+
+ str = String(v);
+
+ if (isNum = typeof v == 'number') {
+
+ // Avoid potential interpretation of Infinity and NaN as base 44+ values.
+ if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
+
+ x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
+
+ // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
+ if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) {
+ throw Error
+ (tooManyDigits + v);
+ }
+ } else {
+ x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
+ }
+
+ alphabet = ALPHABET.slice(0, b);
+ e = i = 0;
+
+ // Check that str is a valid base b number.
+ // Don't use RegExp, so alphabet can contain special characters.
+ for (len = str.length; i < len; i++) {
+ if (alphabet.indexOf(c = str.charAt(i)) < 0) {
+ if (c == '.') {
+
+ // If '.' is not the first character and it has not be found before.
+ if (i > e) {
+ e = len;
+ continue;
+ }
+ } else if (!caseChanged) {
+
+ // Allow e.g. hexadecimal 'FF' as well as 'ff'.
+ if (str == str.toUpperCase() && (str = str.toLowerCase()) ||
+ str == str.toLowerCase() && (str = str.toUpperCase())) {
+ caseChanged = true;
+ i = -1;
+ e = 0;
+ continue;
+ }
+ }
+
+ return parseNumeric(x, String(v), isNum, b);
+ }
+ }
+
+ // Prevent later check for length on converted number.
+ isNum = false;
+ str = convertBase(str, b, 10, x.s);
+
+ // Decimal point?
+ if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
+ else e = str.length;
+ }
+
+ // Determine leading zeros.
+ for (i = 0; str.charCodeAt(i) === 48; i++);
+
+ // Determine trailing zeros.
+ for (len = str.length; str.charCodeAt(--len) === 48;);
+
+ if (str = str.slice(i, ++len)) {
+ len -= i;
+
+ // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'
+ if (isNum && BigNumber.DEBUG &&
+ len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
+ throw Error
+ (tooManyDigits + (x.s * v));
+ }
+
+ // Overflow?
+ if ((e = e - i - 1) > MAX_EXP) {
+
+ // Infinity.
+ x.c = x.e = null;
+
+ // Underflow?
+ } else if (e < MIN_EXP) {
+
+ // Zero.
+ x.c = [x.e = 0];
+ } else {
+ x.e = e;
+ x.c = [];
+
+ // Transform base
+
+ // e is the base 10 exponent.
+ // i is where to slice str to get the first element of the coefficient array.
+ i = (e + 1) % LOG_BASE;
+ if (e < 0) i += LOG_BASE; // i < 1
+
+ if (i < len) {
+ if (i) x.c.push(+str.slice(0, i));
+
+ for (len -= LOG_BASE; i < len;) {
+ x.c.push(+str.slice(i, i += LOG_BASE));
+ }
+
+ i = LOG_BASE - (str = str.slice(i)).length;
+ } else {
+ i -= len;
+ }
+
+ for (; i--; str += '0');
+ x.c.push(+str);
+ }
+ } else {
+
+ // Zero.
+ x.c = [x.e = 0];
+ }
+ }
+
+
+ // CONSTRUCTOR PROPERTIES
+
+
+ BigNumber.clone = clone;
+
+ BigNumber.ROUND_UP = 0;
+ BigNumber.ROUND_DOWN = 1;
+ BigNumber.ROUND_CEIL = 2;
+ BigNumber.ROUND_FLOOR = 3;
+ BigNumber.ROUND_HALF_UP = 4;
+ BigNumber.ROUND_HALF_DOWN = 5;
+ BigNumber.ROUND_HALF_EVEN = 6;
+ BigNumber.ROUND_HALF_CEIL = 7;
+ BigNumber.ROUND_HALF_FLOOR = 8;
+ BigNumber.EUCLID = 9;
+
+
+ /*
+ * Configure infrequently-changing library-wide settings.
+ *
+ * Accept an object with the following optional properties (if the value of a property is
+ * a number, it must be an integer within the inclusive range stated):
+ *
+ * DECIMAL_PLACES {number} 0 to MAX
+ * ROUNDING_MODE {number} 0 to 8
+ * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]
+ * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]
+ * CRYPTO {boolean} true or false
+ * MODULO_MODE {number} 0 to 9
+ * POW_PRECISION {number} 0 to MAX
+ * ALPHABET {string} A string of two or more unique characters which does
+ * not contain '.'.
+ * FORMAT {object} An object with some of the following properties:
+ * prefix {string}
+ * groupSize {number}
+ * secondaryGroupSize {number}
+ * groupSeparator {string}
+ * decimalSeparator {string}
+ * fractionGroupSize {number}
+ * fractionGroupSeparator {string}
+ * suffix {string}
+ *
+ * (The values assigned to the above FORMAT object properties are not checked for validity.)
+ *
+ * E.g.
+ * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
+ *
+ * Ignore properties/parameters set to null or undefined, except for ALPHABET.
+ *
+ * Return an object with the properties current values.
+ */
+ BigNumber.config = BigNumber.set = function (obj) {
+ var p, v;
+
+ if (obj != null) {
+
+ if (typeof obj == 'object') {
+
+ // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
+ // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'
+ if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {
+ v = obj[p];
+ intCheck(v, 0, MAX, p);
+ DECIMAL_PLACES = v;
+ }
+
+ // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
+ // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'
+ if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {
+ v = obj[p];
+ intCheck(v, 0, 8, p);
+ ROUNDING_MODE = v;
+ }
+
+ // EXPONENTIAL_AT {number|number[]}
+ // Integer, -MAX to MAX inclusive or
+ // [integer -MAX to 0 inclusive, 0 to MAX inclusive].
+ // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'
+ if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {
+ v = obj[p];
+ if (v && v.pop) {
+ intCheck(v[0], -MAX, 0, p);
+ intCheck(v[1], 0, MAX, p);
+ TO_EXP_NEG = v[0];
+ TO_EXP_POS = v[1];
+ } else {
+ intCheck(v, -MAX, MAX, p);
+ TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
+ }
+ }
+
+ // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
+ // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
+ // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'
+ if (obj.hasOwnProperty(p = 'RANGE')) {
+ v = obj[p];
+ if (v && v.pop) {
+ intCheck(v[0], -MAX, -1, p);
+ intCheck(v[1], 1, MAX, p);
+ MIN_EXP = v[0];
+ MAX_EXP = v[1];
+ } else {
+ intCheck(v, -MAX, MAX, p);
+ if (v) {
+ MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
+ } else {
+ throw Error
+ (bignumberError + p + ' cannot be zero: ' + v);
+ }
+ }
+ }
+
+ // CRYPTO {boolean} true or false.
+ // '[BigNumber Error] CRYPTO not true or false: {v}'
+ // '[BigNumber Error] crypto unavailable'
+ if (obj.hasOwnProperty(p = 'CRYPTO')) {
+ v = obj[p];
+ if (v === !!v) {
+ if (v) {
+ if (typeof crypto != 'undefined' && crypto &&
+ (crypto.getRandomValues || crypto.randomBytes)) {
+ CRYPTO = v;
+ } else {
+ CRYPTO = !v;
+ throw Error
+ (bignumberError + 'crypto unavailable');
+ }
+ } else {
+ CRYPTO = v;
+ }
+ } else {
+ throw Error
+ (bignumberError + p + ' not true or false: ' + v);
+ }
+ }
+
+ // MODULO_MODE {number} Integer, 0 to 9 inclusive.
+ // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'
+ if (obj.hasOwnProperty(p = 'MODULO_MODE')) {
+ v = obj[p];
+ intCheck(v, 0, 9, p);
+ MODULO_MODE = v;
+ }
+
+ // POW_PRECISION {number} Integer, 0 to MAX inclusive.
+ // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'
+ if (obj.hasOwnProperty(p = 'POW_PRECISION')) {
+ v = obj[p];
+ intCheck(v, 0, MAX, p);
+ POW_PRECISION = v;
+ }
+
+ // FORMAT {object}
+ // '[BigNumber Error] FORMAT not an object: {v}'
+ if (obj.hasOwnProperty(p = 'FORMAT')) {
+ v = obj[p];
+ if (typeof v == 'object') FORMAT = v;
+ else throw Error
+ (bignumberError + p + ' not an object: ' + v);
+ }
+
+ // ALPHABET {string}
+ // '[BigNumber Error] ALPHABET invalid: {v}'
+ if (obj.hasOwnProperty(p = 'ALPHABET')) {
+ v = obj[p];
+
+ // Disallow if only one character,
+ // or if it contains '+', '-', '.', whitespace, or a repeated character.
+ if (typeof v == 'string' && !/^.$|[+-.\s]|(.).*\1/.test(v)) {
+ ALPHABET = v;
+ } else {
+ throw Error
+ (bignumberError + p + ' invalid: ' + v);
+ }
+ }
+
+ } else {
+
+ // '[BigNumber Error] Object expected: {v}'
+ throw Error
+ (bignumberError + 'Object expected: ' + obj);
+ }
+ }
+
+ return {
+ DECIMAL_PLACES: DECIMAL_PLACES,
+ ROUNDING_MODE: ROUNDING_MODE,
+ EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
+ RANGE: [MIN_EXP, MAX_EXP],
+ CRYPTO: CRYPTO,
+ MODULO_MODE: MODULO_MODE,
+ POW_PRECISION: POW_PRECISION,
+ FORMAT: FORMAT,
+ ALPHABET: ALPHABET
+ };
+ };
+
+
+ /*
+ * Return true if v is a BigNumber instance, otherwise return false.
+ *
+ * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.
+ *
+ * v {any}
+ *
+ * '[BigNumber Error] Invalid BigNumber: {v}'
+ */
+ BigNumber.isBigNumber = function (v) {
+ if (!v || v._isBigNumber !== true) return false;
+ if (!BigNumber.DEBUG) return true;
+
+ var i, n,
+ c = v.c,
+ e = v.e,
+ s = v.s;
+
+ out: if ({}.toString.call(c) == '[object Array]') {
+
+ if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
+
+ // If the first element is zero, the BigNumber value must be zero.
+ if (c[0] === 0) {
+ if (e === 0 && c.length === 1) return true;
+ break out;
+ }
+
+ // Calculate number of digits that c[0] should have, based on the exponent.
+ i = (e + 1) % LOG_BASE;
+ if (i < 1) i += LOG_BASE;
+
+ // Calculate number of digits of c[0].
+ //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {
+ if (String(c[0]).length == i) {
+
+ for (i = 0; i < c.length; i++) {
+ n = c[i];
+ if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
+ }
+
+ // Last element cannot be zero, unless it is the only element.
+ if (n !== 0) return true;
+ }
+ }
+
+ // Infinity/NaN
+ } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
+ return true;
+ }
+
+ throw Error
+ (bignumberError + 'Invalid BigNumber: ' + v);
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the maximum of the arguments.
+ *
+ * arguments {number|string|BigNumber}
+ */
+ BigNumber.maximum = BigNumber.max = function () {
+ return maxOrMin(arguments, P.lt);
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the minimum of the arguments.
+ *
+ * arguments {number|string|BigNumber}
+ */
+ BigNumber.minimum = BigNumber.min = function () {
+ return maxOrMin(arguments, P.gt);
+ };
+
+
+ /*
+ * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
+ * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
+ * zeros are produced).
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'
+ * '[BigNumber Error] crypto unavailable'
+ */
+ BigNumber.random = (function () {
+ var pow2_53 = 0x20000000000000;
+
+ // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
+ // Check if Math.random() produces more than 32 bits of randomness.
+ // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
+ // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
+ var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
+ ? function () { return mathfloor(Math.random() * pow2_53); }
+ : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
+ (Math.random() * 0x800000 | 0); };
+
+ return function (dp) {
+ var a, b, e, k, v,
+ i = 0,
+ c = [],
+ rand = new BigNumber(ONE);
+
+ if (dp == null) dp = DECIMAL_PLACES;
+ else intCheck(dp, 0, MAX);
+
+ k = mathceil(dp / LOG_BASE);
+
+ if (CRYPTO) {
+
+ // Browsers supporting crypto.getRandomValues.
+ if (crypto.getRandomValues) {
+
+ a = crypto.getRandomValues(new Uint32Array(k *= 2));
+
+ for (; i < k;) {
+
+ // 53 bits:
+ // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
+ // 11111 11111111 11111111 11111111 11100000 00000000 00000000
+ // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
+ // 11111 11111111 11111111
+ // 0x20000 is 2^21.
+ v = a[i] * 0x20000 + (a[i + 1] >>> 11);
+
+ // Rejection sampling:
+ // 0 <= v < 9007199254740992
+ // Probability that v >= 9e15, is
+ // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
+ if (v >= 9e15) {
+ b = crypto.getRandomValues(new Uint32Array(2));
+ a[i] = b[0];
+ a[i + 1] = b[1];
+ } else {
+
+ // 0 <= v <= 8999999999999999
+ // 0 <= (v % 1e14) <= 99999999999999
+ c.push(v % 1e14);
+ i += 2;
+ }
+ }
+ i = k / 2;
+
+ // Node.js supporting crypto.randomBytes.
+ } else if (crypto.randomBytes) {
+
+ // buffer
+ a = crypto.randomBytes(k *= 7);
+
+ for (; i < k;) {
+
+ // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
+ // 0x100000000 is 2^32, 0x1000000 is 2^24
+ // 11111 11111111 11111111 11111111 11111111 11111111 11111111
+ // 0 <= v < 9007199254740992
+ v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +
+ (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +
+ (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
+
+ if (v >= 9e15) {
+ crypto.randomBytes(7).copy(a, i);
+ } else {
+
+ // 0 <= (v % 1e14) <= 99999999999999
+ c.push(v % 1e14);
+ i += 7;
+ }
+ }
+ i = k / 7;
+ } else {
+ CRYPTO = false;
+ throw Error
+ (bignumberError + 'crypto unavailable');
+ }
+ }
+
+ // Use Math.random.
+ if (!CRYPTO) {
+
+ for (; i < k;) {
+ v = random53bitInt();
+ if (v < 9e15) c[i++] = v % 1e14;
+ }
+ }
+
+ k = c[--i];
+ dp %= LOG_BASE;
+
+ // Convert trailing digits to zeros according to dp.
+ if (k && dp) {
+ v = POWS_TEN[LOG_BASE - dp];
+ c[i] = mathfloor(k / v) * v;
+ }
+
+ // Remove trailing elements which are zero.
+ for (; c[i] === 0; c.pop(), i--);
+
+ // Zero?
+ if (i < 0) {
+ c = [e = 0];
+ } else {
+
+ // Remove leading elements which are zero and adjust exponent accordingly.
+ for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
+
+ // Count the digits of the first element of c to determine leading zeros, and...
+ for (i = 1, v = c[0]; v >= 10; v /= 10, i++);
+
+ // adjust the exponent accordingly.
+ if (i < LOG_BASE) e -= LOG_BASE - i;
+ }
+
+ rand.e = e;
+ rand.c = c;
+ return rand;
+ };
+ })();
+
+
+ /*
+ * Return a BigNumber whose value is the sum of the arguments.
+ *
+ * arguments {number|string|BigNumber}
+ */
+ BigNumber.sum = function () {
+ var i = 1,
+ args = arguments,
+ sum = new BigNumber(args[0]);
+ for (; i < args.length;) sum = sum.plus(args[i++]);
+ return sum;
+ };
+
+
+ // PRIVATE FUNCTIONS
+
+
+ // Called by BigNumber and BigNumber.prototype.toString.
+ convertBase = (function () {
+ var decimal = '0123456789';
+
+ /*
+ * Convert string of baseIn to an array of numbers of baseOut.
+ * Eg. toBaseOut('255', 10, 16) returns [15, 15].
+ * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].
+ */
+ function toBaseOut(str, baseIn, baseOut, alphabet) {
+ var j,
+ arr = [0],
+ arrL,
+ i = 0,
+ len = str.length;
+
+ for (; i < len;) {
+ for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);
+
+ arr[0] += alphabet.indexOf(str.charAt(i++));
+
+ for (j = 0; j < arr.length; j++) {
+
+ if (arr[j] > baseOut - 1) {
+ if (arr[j + 1] == null) arr[j + 1] = 0;
+ arr[j + 1] += arr[j] / baseOut | 0;
+ arr[j] %= baseOut;
+ }
+ }
+ }
+
+ return arr.reverse();
+ }
+
+ // Convert a numeric string of baseIn to a numeric string of baseOut.
+ // If the caller is toString, we are converting from base 10 to baseOut.
+ // If the caller is BigNumber, we are converting from baseIn to base 10.
+ return function (str, baseIn, baseOut, sign, callerIsToString) {
+ var alphabet, d, e, k, r, x, xc, y,
+ i = str.indexOf('.'),
+ dp = DECIMAL_PLACES,
+ rm = ROUNDING_MODE;
+
+ // Non-integer.
+ if (i >= 0) {
+ k = POW_PRECISION;
+
+ // Unlimited precision.
+ POW_PRECISION = 0;
+ str = str.replace('.', '');
+ y = new BigNumber(baseIn);
+ x = y.pow(str.length - i);
+ POW_PRECISION = k;
+
+ // Convert str as if an integer, then restore the fraction part by dividing the
+ // result by its base raised to a power.
+
+ y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),
+ 10, baseOut, decimal);
+ y.e = y.c.length;
+ }
+
+ // Convert the number as integer.
+
+ xc = toBaseOut(str, baseIn, baseOut, callerIsToString
+ ? (alphabet = ALPHABET, decimal)
+ : (alphabet = decimal, ALPHABET));
+
+ // xc now represents str as an integer and converted to baseOut. e is the exponent.
+ e = k = xc.length;
+
+ // Remove trailing zeros.
+ for (; xc[--k] == 0; xc.pop());
+
+ // Zero?
+ if (!xc[0]) return alphabet.charAt(0);
+
+ // Does str represent an integer? If so, no need for the division.
+ if (i < 0) {
+ --e;
+ } else {
+ x.c = xc;
+ x.e = e;
+
+ // The sign is needed for correct rounding.
+ x.s = sign;
+ x = div(x, y, dp, rm, baseOut);
+ xc = x.c;
+ r = x.r;
+ e = x.e;
+ }
+
+ // xc now represents str converted to baseOut.
+
+ // THe index of the rounding digit.
+ d = e + dp + 1;
+
+ // The rounding digit: the digit to the right of the digit that may be rounded up.
+ i = xc[d];
+
+ // Look at the rounding digits and mode to determine whether to round up.
+
+ k = baseOut / 2;
+ r = r || d < 0 || xc[d + 1] != null;
+
+ r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
+ : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
+ rm == (x.s < 0 ? 8 : 7));
+
+ // If the index of the rounding digit is not greater than zero, or xc represents
+ // zero, then the result of the base conversion is zero or, if rounding up, a value
+ // such as 0.00001.
+ if (d < 1 || !xc[0]) {
+
+ // 1^-dp or 0
+ str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
+ } else {
+
+ // Truncate xc to the required number of decimal places.
+ xc.length = d;
+
+ // Round up?
+ if (r) {
+
+ // Rounding up may mean the previous digit has to be rounded up and so on.
+ for (--baseOut; ++xc[--d] > baseOut;) {
+ xc[d] = 0;
+
+ if (!d) {
+ ++e;
+ xc = [1].concat(xc);
+ }
+ }
+ }
+
+ // Determine trailing zeros.
+ for (k = xc.length; !xc[--k];);
+
+ // E.g. [4, 11, 15] becomes 4bf.
+ for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));
+
+ // Add leading zeros, decimal point and trailing zeros as required.
+ str = toFixedPoint(str, e, alphabet.charAt(0));
+ }
+
+ // The caller will add the sign.
+ return str;
+ };
+ })();
+
+
+ // Perform division in the specified base. Called by div and convertBase.
+ div = (function () {
+
+ // Assume non-zero x and k.
+ function multiply(x, k, base) {
+ var m, temp, xlo, xhi,
+ carry = 0,
+ i = x.length,
+ klo = k % SQRT_BASE,
+ khi = k / SQRT_BASE | 0;
+
+ for (x = x.slice(); i--;) {
+ xlo = x[i] % SQRT_BASE;
+ xhi = x[i] / SQRT_BASE | 0;
+ m = khi * xlo + xhi * klo;
+ temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;
+ carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
+ x[i] = temp % base;
+ }
+
+ if (carry) x = [carry].concat(x);
+
+ return x;
+ }
+
+ function compare(a, b, aL, bL) {
+ var i, cmp;
+
+ if (aL != bL) {
+ cmp = aL > bL ? 1 : -1;
+ } else {
+
+ for (i = cmp = 0; i < aL; i++) {
+
+ if (a[i] != b[i]) {
+ cmp = a[i] > b[i] ? 1 : -1;
+ break;
+ }
+ }
+ }
+
+ return cmp;
+ }
+
+ function subtract(a, b, aL, base) {
+ var i = 0;
+
+ // Subtract b from a.
+ for (; aL--;) {
+ a[aL] -= i;
+ i = a[aL] < b[aL] ? 1 : 0;
+ a[aL] = i * base + a[aL] - b[aL];
+ }
+
+ // Remove leading zeros.
+ for (; !a[0] && a.length > 1; a.splice(0, 1));
+ }
+
+ // x: dividend, y: divisor.
+ return function (x, y, dp, rm, base) {
+ var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
+ yL, yz,
+ s = x.s == y.s ? 1 : -1,
+ xc = x.c,
+ yc = y.c;
+
+ // Either NaN, Infinity or 0?
+ if (!xc || !xc[0] || !yc || !yc[0]) {
+
+ return new BigNumber(
+
+ // Return NaN if either NaN, or both Infinity or 0.
+ !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :
+
+ // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
+ xc && xc[0] == 0 || !yc ? s * 0 : s / 0
+ );
+ }
+
+ q = new BigNumber(s);
+ qc = q.c = [];
+ e = x.e - y.e;
+ s = dp + e + 1;
+
+ if (!base) {
+ base = BASE;
+ e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
+ s = s / LOG_BASE | 0;
+ }
+
+ // Result exponent may be one less then the current value of e.
+ // The coefficients of the BigNumbers from convertBase may have trailing zeros.
+ for (i = 0; yc[i] == (xc[i] || 0); i++);
+
+ if (yc[i] > (xc[i] || 0)) e--;
+
+ if (s < 0) {
+ qc.push(1);
+ more = true;
+ } else {
+ xL = xc.length;
+ yL = yc.length;
+ i = 0;
+ s += 2;
+
+ // Normalise xc and yc so highest order digit of yc is >= base / 2.
+
+ n = mathfloor(base / (yc[0] + 1));
+
+ // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.
+ // if (n > 1 || n++ == 1 && yc[0] < base / 2) {
+ if (n > 1) {
+ yc = multiply(yc, n, base);
+ xc = multiply(xc, n, base);
+ yL = yc.length;
+ xL = xc.length;
+ }
+
+ xi = yL;
+ rem = xc.slice(0, yL);
+ remL = rem.length;
+
+ // Add zeros to make remainder as long as divisor.
+ for (; remL < yL; rem[remL++] = 0);
+ yz = yc.slice();
+ yz = [0].concat(yz);
+ yc0 = yc[0];
+ if (yc[1] >= base / 2) yc0++;
+ // Not necessary, but to prevent trial digit n > base, when using base 3.
+ // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;
+
+ do {
+ n = 0;
+
+ // Compare divisor and remainder.
+ cmp = compare(yc, rem, yL, remL);
+
+ // If divisor < remainder.
+ if (cmp < 0) {
+
+ // Calculate trial digit, n.
+
+ rem0 = rem[0];
+ if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
+
+ // n is how many times the divisor goes into the current remainder.
+ n = mathfloor(rem0 / yc0);
+
+ // Algorithm:
+ // product = divisor multiplied by trial digit (n).
+ // Compare product and remainder.
+ // If product is greater than remainder:
+ // Subtract divisor from product, decrement trial digit.
+ // Subtract product from remainder.
+ // If product was less than remainder at the last compare:
+ // Compare new remainder and divisor.
+ // If remainder is greater than divisor:
+ // Subtract divisor from remainder, increment trial digit.
+
+ if (n > 1) {
+
+ // n may be > base only when base is 3.
+ if (n >= base) n = base - 1;
+
+ // product = divisor * trial digit.
+ prod = multiply(yc, n, base);
+ prodL = prod.length;
+ remL = rem.length;
+
+ // Compare product and remainder.
+ // If product > remainder then trial digit n too high.
+ // n is 1 too high about 5% of the time, and is not known to have
+ // ever been more than 1 too high.
+ while (compare(prod, rem, prodL, remL) == 1) {
+ n--;
+
+ // Subtract divisor from product.
+ subtract(prod, yL < prodL ? yz : yc, prodL, base);
+ prodL = prod.length;
+ cmp = 1;
+ }
+ } else {
+
+ // n is 0 or 1, cmp is -1.
+ // If n is 0, there is no need to compare yc and rem again below,
+ // so change cmp to 1 to avoid it.
+ // If n is 1, leave cmp as -1, so yc and rem are compared again.
+ if (n == 0) {
+
+ // divisor < remainder, so n must be at least 1.
+ cmp = n = 1;
+ }
+
+ // product = divisor
+ prod = yc.slice();
+ prodL = prod.length;
+ }
+
+ if (prodL < remL) prod = [0].concat(prod);
+
+ // Subtract product from remainder.
+ subtract(rem, prod, remL, base);
+ remL = rem.length;
+
+ // If product was < remainder.
+ if (cmp == -1) {
+
+ // Compare divisor and new remainder.
+ // If divisor < new remainder, subtract divisor from remainder.
+ // Trial digit n too low.
+ // n is 1 too low about 5% of the time, and very rarely 2 too low.
+ while (compare(yc, rem, yL, remL) < 1) {
+ n++;
+
+ // Subtract divisor from remainder.
+ subtract(rem, yL < remL ? yz : yc, remL, base);
+ remL = rem.length;
+ }
+ }
+ } else if (cmp === 0) {
+ n++;
+ rem = [0];
+ } // else cmp === 1 and n will be 0
+
+ // Add the next digit, n, to the result array.
+ qc[i++] = n;
+
+ // Update the remainder.
+ if (rem[0]) {
+ rem[remL++] = xc[xi] || 0;
+ } else {
+ rem = [xc[xi]];
+ remL = 1;
+ }
+ } while ((xi++ < xL || rem[0] != null) && s--);
+
+ more = rem[0] != null;
+
+ // Leading zero?
+ if (!qc[0]) qc.splice(0, 1);
+ }
+
+ if (base == BASE) {
+
+ // To calculate q.e, first get the number of digits of qc[0].
+ for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);
+
+ round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);
+
+ // Caller is convertBase.
+ } else {
+ q.e = e;
+ q.r = +more;
+ }
+
+ return q;
+ };
+ })();
+
+
+ /*
+ * Return a string representing the value of BigNumber n in fixed-point or exponential
+ * notation rounded to the specified decimal places or significant digits.
+ *
+ * n: a BigNumber.
+ * i: the index of the last digit required (i.e. the digit that may be rounded up).
+ * rm: the rounding mode.
+ * id: 1 (toExponential) or 2 (toPrecision).
+ */
+ function format(n, i, rm, id) {
+ var c0, e, ne, len, str;
+
+ if (rm == null) rm = ROUNDING_MODE;
+ else intCheck(rm, 0, 8);
+
+ if (!n.c) return n.toString();
+
+ c0 = n.c[0];
+ ne = n.e;
+
+ if (i == null) {
+ str = coeffToString(n.c);
+ str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)
+ ? toExponential(str, ne)
+ : toFixedPoint(str, ne, '0');
+ } else {
+ n = round(new BigNumber(n), i, rm);
+
+ // n.e may have changed if the value was rounded up.
+ e = n.e;
+
+ str = coeffToString(n.c);
+ len = str.length;
+
+ // toPrecision returns exponential notation if the number of significant digits
+ // specified is less than the number of digits necessary to represent the integer
+ // part of the value in fixed-point notation.
+
+ // Exponential notation.
+ if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
+
+ // Append zeros?
+ for (; len < i; str += '0', len++);
+ str = toExponential(str, e);
+
+ // Fixed-point notation.
+ } else {
+ i -= ne;
+ str = toFixedPoint(str, e, '0');
+
+ // Append zeros?
+ if (e + 1 > len) {
+ if (--i > 0) for (str += '.'; i--; str += '0');
+ } else {
+ i += e - len;
+ if (i > 0) {
+ if (e + 1 == len) str += '.';
+ for (; i--; str += '0');
+ }
+ }
+ }
+ }
+
+ return n.s < 0 && c0 ? '-' + str : str;
+ }
+
+
+ // Handle BigNumber.max and BigNumber.min.
+ function maxOrMin(args, method) {
+ var n,
+ i = 1,
+ m = new BigNumber(args[0]);
+
+ for (; i < args.length; i++) {
+ n = new BigNumber(args[i]);
+
+ // If any number is NaN, return NaN.
+ if (!n.s) {
+ m = n;
+ break;
+ } else if (method.call(m, n)) {
+ m = n;
+ }
+ }
+
+ return m;
+ }
+
+
+ /*
+ * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
+ * Called by minus, plus and times.
+ */
+ function normalise(n, c, e) {
+ var i = 1,
+ j = c.length;
+
+ // Remove trailing zeros.
+ for (; !c[--j]; c.pop());
+
+ // Calculate the base 10 exponent. First get the number of digits of c[0].
+ for (j = c[0]; j >= 10; j /= 10, i++);
+
+ // Overflow?
+ if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
+
+ // Infinity.
+ n.c = n.e = null;
+
+ // Underflow?
+ } else if (e < MIN_EXP) {
+
+ // Zero.
+ n.c = [n.e = 0];
+ } else {
+ n.e = e;
+ n.c = c;
+ }
+
+ return n;
+ }
+
+
+ // Handle values that fail the validity test in BigNumber.
+ parseNumeric = (function () {
+ var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
+ dotAfter = /^([^.]+)\.$/,
+ dotBefore = /^\.([^.]+)$/,
+ isInfinityOrNaN = /^-?(Infinity|NaN)$/,
+ whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
+
+ return function (x, str, isNum, b) {
+ var base,
+ s = isNum ? str : str.replace(whitespaceOrPlus, '');
+
+ // No exception on ±Infinity or NaN.
+ if (isInfinityOrNaN.test(s)) {
+ x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
+ } else {
+ if (!isNum) {
+
+ // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
+ s = s.replace(basePrefix, function (m, p1, p2) {
+ base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
+ return !b || b == base ? p1 : m;
+ });
+
+ if (b) {
+ base = b;
+
+ // E.g. '1.' to '1', '.1' to '0.1'
+ s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');
+ }
+
+ if (str != s) return new BigNumber(s, base);
+ }
+
+ // '[BigNumber Error] Not a number: {n}'
+ // '[BigNumber Error] Not a base {b} number: {n}'
+ if (BigNumber.DEBUG) {
+ throw Error
+ (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);
+ }
+
+ // NaN
+ x.s = null;
+ }
+
+ x.c = x.e = null;
+ }
+ })();
+
+
+ /*
+ * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
+ * If r is truthy, it is known that there are more digits after the rounding digit.
+ */
+ function round(x, sd, rm, r) {
+ var d, i, j, k, n, ni, rd,
+ xc = x.c,
+ pows10 = POWS_TEN;
+
+ // if x is not Infinity or NaN...
+ if (xc) {
+
+ // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
+ // n is a base 1e14 number, the value of the element of array x.c containing rd.
+ // ni is the index of n within x.c.
+ // d is the number of digits of n.
+ // i is the index of rd within n including leading zeros.
+ // j is the actual index of rd within n (if < 0, rd is a leading zero).
+ out: {
+
+ // Get the number of digits of the first element of xc.
+ for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);
+ i = sd - d;
+
+ // If the rounding digit is in the first element of xc...
+ if (i < 0) {
+ i += LOG_BASE;
+ j = sd;
+ n = xc[ni = 0];
+
+ // Get the rounding digit at index j of n.
+ rd = n / pows10[d - j - 1] % 10 | 0;
+ } else {
+ ni = mathceil((i + 1) / LOG_BASE);
+
+ if (ni >= xc.length) {
+
+ if (r) {
+
+ // Needed by sqrt.
+ for (; xc.length <= ni; xc.push(0));
+ n = rd = 0;
+ d = 1;
+ i %= LOG_BASE;
+ j = i - LOG_BASE + 1;
+ } else {
+ break out;
+ }
+ } else {
+ n = k = xc[ni];
+
+ // Get the number of digits of n.
+ for (d = 1; k >= 10; k /= 10, d++);
+
+ // Get the index of rd within n.
+ i %= LOG_BASE;
+
+ // Get the index of rd within n, adjusted for leading zeros.
+ // The number of leading zeros of n is given by LOG_BASE - d.
+ j = i - LOG_BASE + d;
+
+ // Get the rounding digit at index j of n.
+ rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;
+ }
+ }
+
+ r = r || sd < 0 ||
+
+ // Are there any non-zero digits after the rounding digit?
+ // The expression n % pows10[d - j - 1] returns all digits of n to the right
+ // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
+ xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
+
+ r = rm < 4
+ ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
+ : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&
+
+ // Check whether the digit to the left of the rounding digit is odd.
+ ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||
+ rm == (x.s < 0 ? 8 : 7));
+
+ if (sd < 1 || !xc[0]) {
+ xc.length = 0;
+
+ if (r) {
+
+ // Convert sd to decimal places.
+ sd -= x.e + 1;
+
+ // 1, 0.1, 0.01, 0.001, 0.0001 etc.
+ xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
+ x.e = -sd || 0;
+ } else {
+
+ // Zero.
+ xc[0] = x.e = 0;
+ }
+
+ return x;
+ }
+
+ // Remove excess digits.
+ if (i == 0) {
+ xc.length = ni;
+ k = 1;
+ ni--;
+ } else {
+ xc.length = ni + 1;
+ k = pows10[LOG_BASE - i];
+
+ // E.g. 56700 becomes 56000 if 7 is the rounding digit.
+ // j > 0 means i > number of leading zeros of n.
+ xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;
+ }
+
+ // Round up?
+ if (r) {
+
+ for (; ;) {
+
+ // If the digit to be rounded up is in the first element of xc...
+ if (ni == 0) {
+
+ // i will be the length of xc[0] before k is added.
+ for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);
+ j = xc[0] += k;
+ for (k = 1; j >= 10; j /= 10, k++);
+
+ // if i != k the length has increased.
+ if (i != k) {
+ x.e++;
+ if (xc[0] == BASE) xc[0] = 1;
+ }
+
+ break;
+ } else {
+ xc[ni] += k;
+ if (xc[ni] != BASE) break;
+ xc[ni--] = 0;
+ k = 1;
+ }
+ }
+ }
+
+ // Remove trailing zeros.
+ for (i = xc.length; xc[--i] === 0; xc.pop());
+ }
+
+ // Overflow? Infinity.
+ if (x.e > MAX_EXP) {
+ x.c = x.e = null;
+
+ // Underflow? Zero.
+ } else if (x.e < MIN_EXP) {
+ x.c = [x.e = 0];
+ }
+ }
+
+ return x;
+ }
+
+
+ function valueOf(n) {
+ var str,
+ e = n.e;
+
+ if (e === null) return n.toString();
+
+ str = coeffToString(n.c);
+
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS
+ ? toExponential(str, e)
+ : toFixedPoint(str, e, '0');
+
+ return n.s < 0 ? '-' + str : str;
+ }
+
+
+ // PROTOTYPE/INSTANCE METHODS
+
+
+ /*
+ * Return a new BigNumber whose value is the absolute value of this BigNumber.
+ */
+ P.absoluteValue = P.abs = function () {
+ var x = new BigNumber(this);
+ if (x.s < 0) x.s = 1;
+ return x;
+ };
+
+
+ /*
+ * Return
+ * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
+ * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
+ * 0 if they have the same value,
+ * or null if the value of either is NaN.
+ */
+ P.comparedTo = function (y, b) {
+ return compare(this, new BigNumber(y, b));
+ };
+
+
+ /*
+ * If dp is undefined or null or true or false, return the number of decimal places of the
+ * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
+ *
+ * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this
+ * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or
+ * ROUNDING_MODE if rm is omitted.
+ *
+ * [dp] {number} Decimal places: integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
+ */
+ P.decimalPlaces = P.dp = function (dp, rm) {
+ var c, n, v,
+ x = this;
+
+ if (dp != null) {
+ intCheck(dp, 0, MAX);
+ if (rm == null) rm = ROUNDING_MODE;
+ else intCheck(rm, 0, 8);
+
+ return round(new BigNumber(x), dp + x.e + 1, rm);
+ }
+
+ if (!(c = x.c)) return null;
+ n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
+
+ // Subtract the number of trailing zeros of the last number.
+ if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);
+ if (n < 0) n = 0;
+
+ return n;
+ };
+
+
+ /*
+ * n / 0 = I
+ * n / N = N
+ * n / I = 0
+ * 0 / n = 0
+ * 0 / 0 = N
+ * 0 / N = N
+ * 0 / I = 0
+ * N / n = N
+ * N / 0 = N
+ * N / N = N
+ * N / I = N
+ * I / n = I
+ * I / 0 = I
+ * I / N = N
+ * I / I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
+ * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
+ */
+ P.dividedBy = P.div = function (y, b) {
+ return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the integer part of dividing the value of this
+ * BigNumber by the value of BigNumber(y, b).
+ */
+ P.dividedToIntegerBy = P.idiv = function (y, b) {
+ return div(this, new BigNumber(y, b), 0, 1);
+ };
+
+
+ /*
+ * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.
+ *
+ * If m is present, return the result modulo m.
+ * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
+ * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.
+ *
+ * The modular power operation works efficiently when x, n, and m are integers, otherwise it
+ * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.
+ *
+ * n {number|string|BigNumber} The exponent. An integer.
+ * [m] {number|string|BigNumber} The modulus.
+ *
+ * '[BigNumber Error] Exponent not an integer: {n}'
+ */
+ P.exponentiatedBy = P.pow = function (n, m) {
+ var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,
+ x = this;
+
+ n = new BigNumber(n);
+
+ // Allow NaN and ±Infinity, but not other non-integers.
+ if (n.c && !n.isInteger()) {
+ throw Error
+ (bignumberError + 'Exponent not an integer: ' + valueOf(n));
+ }
+
+ if (m != null) m = new BigNumber(m);
+
+ // Exponent of MAX_SAFE_INTEGER is 15.
+ nIsBig = n.e > 14;
+
+ // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.
+ if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {
+
+ // The sign of the result of pow when x is negative depends on the evenness of n.
+ // If +n overflows to ±Infinity, the evenness of n would be not be known.
+ y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));
+ return m ? y.mod(m) : y;
+ }
+
+ nIsNeg = n.s < 0;
+
+ if (m) {
+
+ // x % m returns NaN if abs(m) is zero, or m is NaN.
+ if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);
+
+ isModExp = !nIsNeg && x.isInteger() && m.isInteger();
+
+ if (isModExp) x = x.mod(m);
+
+ // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.
+ // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.
+ } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0
+ // [1, 240000000]
+ ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7
+ // [80000000000000] [99999750000000]
+ : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
+
+ // If x is negative and n is odd, k = -0, else k = 0.
+ k = x.s < 0 && isOdd(n) ? -0 : 0;
+
+ // If x >= 1, k = ±Infinity.
+ if (x.e > -1) k = 1 / k;
+
+ // If n is negative return ±0, else return ±Infinity.
+ return new BigNumber(nIsNeg ? 1 / k : k);
+
+ } else if (POW_PRECISION) {
+
+ // Truncating each coefficient array to a length of k after each multiplication
+ // equates to truncating significant digits to POW_PRECISION + [28, 41],
+ // i.e. there will be a minimum of 28 guard digits retained.
+ k = mathceil(POW_PRECISION / LOG_BASE + 2);
+ }
+
+ if (nIsBig) {
+ half = new BigNumber(0.5);
+ if (nIsNeg) n.s = 1;
+ nIsOdd = isOdd(n);
+ } else {
+ i = Math.abs(+valueOf(n));
+ nIsOdd = i % 2;
+ }
+
+ y = new BigNumber(ONE);
+
+ // Performs 54 loop iterations for n of 9007199254740991.
+ for (; ;) {
+
+ if (nIsOdd) {
+ y = y.times(x);
+ if (!y.c) break;
+
+ if (k) {
+ if (y.c.length > k) y.c.length = k;
+ } else if (isModExp) {
+ y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));
+ }
+ }
+
+ if (i) {
+ i = mathfloor(i / 2);
+ if (i === 0) break;
+ nIsOdd = i % 2;
+ } else {
+ n = n.times(half);
+ round(n, n.e + 1, 1);
+
+ if (n.e > 14) {
+ nIsOdd = isOdd(n);
+ } else {
+ i = +valueOf(n);
+ if (i === 0) break;
+ nIsOdd = i % 2;
+ }
+ }
+
+ x = x.times(x);
+
+ if (k) {
+ if (x.c && x.c.length > k) x.c.length = k;
+ } else if (isModExp) {
+ x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));
+ }
+ }
+
+ if (isModExp) return y;
+ if (nIsNeg) y = ONE.div(y);
+
+ return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer
+ * using rounding mode rm, or ROUNDING_MODE if rm is omitted.
+ *
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'
+ */
+ P.integerValue = function (rm) {
+ var n = new BigNumber(this);
+ if (rm == null) rm = ROUNDING_MODE;
+ else intCheck(rm, 0, 8);
+ return round(n, n.e + 1, rm);
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
+ * otherwise return false.
+ */
+ P.isEqualTo = P.eq = function (y, b) {
+ return compare(this, new BigNumber(y, b)) === 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is a finite number, otherwise return false.
+ */
+ P.isFinite = function () {
+ return !!this.c;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
+ * otherwise return false.
+ */
+ P.isGreaterThan = P.gt = function (y, b) {
+ return compare(this, new BigNumber(y, b)) > 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is greater than or equal to the value of
+ * BigNumber(y, b), otherwise return false.
+ */
+ P.isGreaterThanOrEqualTo = P.gte = function (y, b) {
+ return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;
+
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is an integer, otherwise return false.
+ */
+ P.isInteger = function () {
+ return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
+ * otherwise return false.
+ */
+ P.isLessThan = P.lt = function (y, b) {
+ return compare(this, new BigNumber(y, b)) < 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is less than or equal to the value of
+ * BigNumber(y, b), otherwise return false.
+ */
+ P.isLessThanOrEqualTo = P.lte = function (y, b) {
+ return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is NaN, otherwise return false.
+ */
+ P.isNaN = function () {
+ return !this.s;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is negative, otherwise return false.
+ */
+ P.isNegative = function () {
+ return this.s < 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is positive, otherwise return false.
+ */
+ P.isPositive = function () {
+ return this.s > 0;
+ };
+
+
+ /*
+ * Return true if the value of this BigNumber is 0 or -0, otherwise return false.
+ */
+ P.isZero = function () {
+ return !!this.c && this.c[0] == 0;
+ };
+
+
+ /*
+ * n - 0 = n
+ * n - N = N
+ * n - I = -I
+ * 0 - n = -n
+ * 0 - 0 = 0
+ * 0 - N = N
+ * 0 - I = -I
+ * N - n = N
+ * N - 0 = N
+ * N - N = N
+ * N - I = N
+ * I - n = I
+ * I - 0 = I
+ * I - N = N
+ * I - I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber minus the value of
+ * BigNumber(y, b).
+ */
+ P.minus = function (y, b) {
+ var i, j, t, xLTy,
+ x = this,
+ a = x.s;
+
+ y = new BigNumber(y, b);
+ b = y.s;
+
+ // Either NaN?
+ if (!a || !b) return new BigNumber(NaN);
+
+ // Signs differ?
+ if (a != b) {
+ y.s = -b;
+ return x.plus(y);
+ }
+
+ var xe = x.e / LOG_BASE,
+ ye = y.e / LOG_BASE,
+ xc = x.c,
+ yc = y.c;
+
+ if (!xe || !ye) {
+
+ // Either Infinity?
+ if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);
+
+ // Either zero?
+ if (!xc[0] || !yc[0]) {
+
+ // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
+ return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :
+
+ // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
+ ROUNDING_MODE == 3 ? -0 : 0);
+ }
+ }
+
+ xe = bitFloor(xe);
+ ye = bitFloor(ye);
+ xc = xc.slice();
+
+ // Determine which is the bigger number.
+ if (a = xe - ye) {
+
+ if (xLTy = a < 0) {
+ a = -a;
+ t = xc;
+ } else {
+ ye = xe;
+ t = yc;
+ }
+
+ t.reverse();
+
+ // Prepend zeros to equalise exponents.
+ for (b = a; b--; t.push(0));
+ t.reverse();
+ } else {
+
+ // Exponents equal. Check digit by digit.
+ j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
+
+ for (a = b = 0; b < j; b++) {
+
+ if (xc[b] != yc[b]) {
+ xLTy = xc[b] < yc[b];
+ break;
+ }
+ }
+ }
+
+ // x < y? Point xc to the array of the bigger number.
+ if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
+
+ b = (j = yc.length) - (i = xc.length);
+
+ // Append zeros to xc if shorter.
+ // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
+ if (b > 0) for (; b--; xc[i++] = 0);
+ b = BASE - 1;
+
+ // Subtract yc from xc.
+ for (; j > a;) {
+
+ if (xc[--j] < yc[j]) {
+ for (i = j; i && !xc[--i]; xc[i] = b);
+ --xc[i];
+ xc[j] += BASE;
+ }
+
+ xc[j] -= yc[j];
+ }
+
+ // Remove leading zeros and adjust exponent accordingly.
+ for (; xc[0] == 0; xc.splice(0, 1), --ye);
+
+ // Zero?
+ if (!xc[0]) {
+
+ // Following IEEE 754 (2008) 6.3,
+ // n - n = +0 but n - n = -0 when rounding towards -Infinity.
+ y.s = ROUNDING_MODE == 3 ? -1 : 1;
+ y.c = [y.e = 0];
+ return y;
+ }
+
+ // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
+ // for finite x and y.
+ return normalise(y, xc, ye);
+ };
+
+
+ /*
+ * n % 0 = N
+ * n % N = N
+ * n % I = n
+ * 0 % n = 0
+ * -0 % n = -0
+ * 0 % 0 = N
+ * 0 % N = N
+ * 0 % I = 0
+ * N % n = N
+ * N % 0 = N
+ * N % N = N
+ * N % I = N
+ * I % n = N
+ * I % 0 = N
+ * I % N = N
+ * I % I = N
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
+ * BigNumber(y, b). The result depends on the value of MODULO_MODE.
+ */
+ P.modulo = P.mod = function (y, b) {
+ var q, s,
+ x = this;
+
+ y = new BigNumber(y, b);
+
+ // Return NaN if x is Infinity or NaN, or y is NaN or zero.
+ if (!x.c || !y.s || y.c && !y.c[0]) {
+ return new BigNumber(NaN);
+
+ // Return x if y is Infinity or x is zero.
+ } else if (!y.c || x.c && !x.c[0]) {
+ return new BigNumber(x);
+ }
+
+ if (MODULO_MODE == 9) {
+
+ // Euclidian division: q = sign(y) * floor(x / abs(y))
+ // r = x - qy where 0 <= r < abs(y)
+ s = y.s;
+ y.s = 1;
+ q = div(x, y, 0, 3);
+ y.s = s;
+ q.s *= s;
+ } else {
+ q = div(x, y, 0, MODULO_MODE);
+ }
+
+ y = x.minus(q.times(y));
+
+ // To match JavaScript %, ensure sign of zero is sign of dividend.
+ if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
+
+ return y;
+ };
+
+
+ /*
+ * n * 0 = 0
+ * n * N = N
+ * n * I = I
+ * 0 * n = 0
+ * 0 * 0 = 0
+ * 0 * N = N
+ * 0 * I = N
+ * N * n = N
+ * N * 0 = N
+ * N * N = N
+ * N * I = N
+ * I * n = I
+ * I * 0 = N
+ * I * N = N
+ * I * I = I
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value
+ * of BigNumber(y, b).
+ */
+ P.multipliedBy = P.times = function (y, b) {
+ var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
+ base, sqrtBase,
+ x = this,
+ xc = x.c,
+ yc = (y = new BigNumber(y, b)).c;
+
+ // Either NaN, ±Infinity or ±0?
+ if (!xc || !yc || !xc[0] || !yc[0]) {
+
+ // Return NaN if either is NaN, or one is 0 and the other is Infinity.
+ if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
+ y.c = y.e = y.s = null;
+ } else {
+ y.s *= x.s;
+
+ // Return ±Infinity if either is ±Infinity.
+ if (!xc || !yc) {
+ y.c = y.e = null;
+
+ // Return ±0 if either is ±0.
+ } else {
+ y.c = [0];
+ y.e = 0;
+ }
+ }
+
+ return y;
+ }
+
+ e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
+ y.s *= x.s;
+ xcL = xc.length;
+ ycL = yc.length;
+
+ // Ensure xc points to longer array and xcL to its length.
+ if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
+
+ // Initialise the result array with zeros.
+ for (i = xcL + ycL, zc = []; i--; zc.push(0));
+
+ base = BASE;
+ sqrtBase = SQRT_BASE;
+
+ for (i = ycL; --i >= 0;) {
+ c = 0;
+ ylo = yc[i] % sqrtBase;
+ yhi = yc[i] / sqrtBase | 0;
+
+ for (k = xcL, j = i + k; j > i;) {
+ xlo = xc[--k] % sqrtBase;
+ xhi = xc[k] / sqrtBase | 0;
+ m = yhi * xlo + xhi * ylo;
+ xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;
+ c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
+ zc[j--] = xlo % base;
+ }
+
+ zc[j] = c;
+ }
+
+ if (c) {
+ ++e;
+ } else {
+ zc.splice(0, 1);
+ }
+
+ return normalise(y, zc, e);
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber negated,
+ * i.e. multiplied by -1.
+ */
+ P.negated = function () {
+ var x = new BigNumber(this);
+ x.s = -x.s || null;
+ return x;
+ };
+
+
+ /*
+ * n + 0 = n
+ * n + N = N
+ * n + I = I
+ * 0 + n = n
+ * 0 + 0 = 0
+ * 0 + N = N
+ * 0 + I = I
+ * N + n = N
+ * N + 0 = N
+ * N + N = N
+ * N + I = N
+ * I + n = I
+ * I + 0 = I
+ * I + N = N
+ * I + I = I
+ *
+ * Return a new BigNumber whose value is the value of this BigNumber plus the value of
+ * BigNumber(y, b).
+ */
+ P.plus = function (y, b) {
+ var t,
+ x = this,
+ a = x.s;
+
+ y = new BigNumber(y, b);
+ b = y.s;
+
+ // Either NaN?
+ if (!a || !b) return new BigNumber(NaN);
+
+ // Signs differ?
+ if (a != b) {
+ y.s = -b;
+ return x.minus(y);
+ }
+
+ var xe = x.e / LOG_BASE,
+ ye = y.e / LOG_BASE,
+ xc = x.c,
+ yc = y.c;
+
+ if (!xe || !ye) {
+
+ // Return ±Infinity if either ±Infinity.
+ if (!xc || !yc) return new BigNumber(a / 0);
+
+ // Either zero?
+ // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
+ if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);
+ }
+
+ xe = bitFloor(xe);
+ ye = bitFloor(ye);
+ xc = xc.slice();
+
+ // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
+ if (a = xe - ye) {
+ if (a > 0) {
+ ye = xe;
+ t = yc;
+ } else {
+ a = -a;
+ t = xc;
+ }
+
+ t.reverse();
+ for (; a--; t.push(0));
+ t.reverse();
+ }
+
+ a = xc.length;
+ b = yc.length;
+
+ // Point xc to the longer array, and b to the shorter length.
+ if (a - b < 0) t = yc, yc = xc, xc = t, b = a;
+
+ // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
+ for (a = 0; b;) {
+ a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
+ xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
+ }
+
+ if (a) {
+ xc = [a].concat(xc);
+ ++ye;
+ }
+
+ // No need to check for zero, as +x + +y != 0 && -x + -y != 0
+ // ye = MAX_EXP + 1 possible
+ return normalise(y, xc, ye);
+ };
+
+
+ /*
+ * If sd is undefined or null or true or false, return the number of significant digits of
+ * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.
+ * If sd is true include integer-part trailing zeros in the count.
+ *
+ * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this
+ * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or
+ * ROUNDING_MODE if rm is omitted.
+ *
+ * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.
+ * boolean: whether to count integer-part trailing zeros: true or false.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
+ */
+ P.precision = P.sd = function (sd, rm) {
+ var c, n, v,
+ x = this;
+
+ if (sd != null && sd !== !!sd) {
+ intCheck(sd, 1, MAX);
+ if (rm == null) rm = ROUNDING_MODE;
+ else intCheck(rm, 0, 8);
+
+ return round(new BigNumber(x), sd, rm);
+ }
+
+ if (!(c = x.c)) return null;
+ v = c.length - 1;
+ n = v * LOG_BASE + 1;
+
+ if (v = c[v]) {
+
+ // Subtract the number of trailing zeros of the last element.
+ for (; v % 10 == 0; v /= 10, n--);
+
+ // Add the number of digits of the first element.
+ for (v = c[0]; v >= 10; v /= 10, n++);
+ }
+
+ if (sd && x.e + 1 > n) n = x.e + 1;
+
+ return n;
+ };
+
+
+ /*
+ * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
+ * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
+ *
+ * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'
+ */
+ P.shiftedBy = function (k) {
+ intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
+ return this.times('1e' + k);
+ };
+
+
+ /*
+ * sqrt(-n) = N
+ * sqrt(N) = N
+ * sqrt(-I) = N
+ * sqrt(I) = I
+ * sqrt(0) = 0
+ * sqrt(-0) = -0
+ *
+ * Return a new BigNumber whose value is the square root of the value of this BigNumber,
+ * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
+ */
+ P.squareRoot = P.sqrt = function () {
+ var m, n, r, rep, t,
+ x = this,
+ c = x.c,
+ s = x.s,
+ e = x.e,
+ dp = DECIMAL_PLACES + 4,
+ half = new BigNumber('0.5');
+
+ // Negative/NaN/Infinity/zero?
+ if (s !== 1 || !c || !c[0]) {
+ return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
+ }
+
+ // Initial estimate.
+ s = Math.sqrt(+valueOf(x));
+
+ // Math.sqrt underflow/overflow?
+ // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
+ if (s == 0 || s == 1 / 0) {
+ n = coeffToString(c);
+ if ((n.length + e) % 2 == 0) n += '0';
+ s = Math.sqrt(+n);
+ e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
+
+ if (s == 1 / 0) {
+ n = '1e' + e;
+ } else {
+ n = s.toExponential();
+ n = n.slice(0, n.indexOf('e') + 1) + e;
+ }
+
+ r = new BigNumber(n);
+ } else {
+ r = new BigNumber(s + '');
+ }
+
+ // Check for zero.
+ // r could be zero if MIN_EXP is changed after the this value was created.
+ // This would cause a division by zero (x/t) and hence Infinity below, which would cause
+ // coeffToString to throw.
+ if (r.c[0]) {
+ e = r.e;
+ s = e + dp;
+ if (s < 3) s = 0;
+
+ // Newton-Raphson iteration.
+ for (; ;) {
+ t = r;
+ r = half.times(t.plus(div(x, t, dp, 1)));
+
+ if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
+
+ // The exponent of r may here be one less than the final result exponent,
+ // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
+ // are indexed correctly.
+ if (r.e < e) --s;
+ n = n.slice(s - 3, s + 1);
+
+ // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
+ // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
+ // iteration.
+ if (n == '9999' || !rep && n == '4999') {
+
+ // On the first iteration only, check to see if rounding up gives the
+ // exact result as the nines may infinitely repeat.
+ if (!rep) {
+ round(t, t.e + DECIMAL_PLACES + 2, 0);
+
+ if (t.times(t).eq(x)) {
+ r = t;
+ break;
+ }
+ }
+
+ dp += 4;
+ s += 4;
+ rep = 1;
+ } else {
+
+ // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
+ // result. If not, then there are further digits and m will be truthy.
+ if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
+
+ // Truncate to the first rounding digit.
+ round(r, r.e + DECIMAL_PLACES + 2, 1);
+ m = !r.times(r).eq(x);
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in exponential notation and
+ * rounded using ROUNDING_MODE to dp fixed decimal places.
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
+ */
+ P.toExponential = function (dp, rm) {
+ if (dp != null) {
+ intCheck(dp, 0, MAX);
+ dp++;
+ }
+ return format(this, dp, rm, 1);
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in fixed-point notation rounding
+ * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
+ *
+ * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
+ * but e.g. (-0.00001).toFixed(0) is '-0'.
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
+ */
+ P.toFixed = function (dp, rm) {
+ if (dp != null) {
+ intCheck(dp, 0, MAX);
+ dp = dp + this.e + 1;
+ }
+ return format(this, dp, rm);
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in fixed-point notation rounded
+ * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
+ * of the format or FORMAT object (see BigNumber.set).
+ *
+ * The formatting object may contain some or all of the properties shown below.
+ *
+ * FORMAT = {
+ * prefix: '',
+ * groupSize: 3,
+ * secondaryGroupSize: 0,
+ * groupSeparator: ',',
+ * decimalSeparator: '.',
+ * fractionGroupSize: 0,
+ * fractionGroupSeparator: '\xA0', // non-breaking space
+ * suffix: ''
+ * };
+ *
+ * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ * [format] {object} Formatting options. See FORMAT pbject above.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'
+ * '[BigNumber Error] Argument not an object: {format}'
+ */
+ P.toFormat = function (dp, rm, format) {
+ var str,
+ x = this;
+
+ if (format == null) {
+ if (dp != null && rm && typeof rm == 'object') {
+ format = rm;
+ rm = null;
+ } else if (dp && typeof dp == 'object') {
+ format = dp;
+ dp = rm = null;
+ } else {
+ format = FORMAT;
+ }
+ } else if (typeof format != 'object') {
+ throw Error
+ (bignumberError + 'Argument not an object: ' + format);
+ }
+
+ str = x.toFixed(dp, rm);
+
+ if (x.c) {
+ var i,
+ arr = str.split('.'),
+ g1 = +format.groupSize,
+ g2 = +format.secondaryGroupSize,
+ groupSeparator = format.groupSeparator || '',
+ intPart = arr[0],
+ fractionPart = arr[1],
+ isNeg = x.s < 0,
+ intDigits = isNeg ? intPart.slice(1) : intPart,
+ len = intDigits.length;
+
+ if (g2) i = g1, g1 = g2, g2 = i, len -= i;
+
+ if (g1 > 0 && len > 0) {
+ i = len % g1 || g1;
+ intPart = intDigits.substr(0, i);
+ for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
+ if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
+ if (isNeg) intPart = '-' + intPart;
+ }
+
+ str = fractionPart
+ ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)
+ ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'),
+ '$&' + (format.fractionGroupSeparator || ''))
+ : fractionPart)
+ : intPart;
+ }
+
+ return (format.prefix || '') + str + (format.suffix || '');
+ };
+
+
+ /*
+ * Return an array of two BigNumbers representing the value of this BigNumber as a simple
+ * fraction with an integer numerator and an integer denominator.
+ * The denominator will be a positive non-zero value less than or equal to the specified
+ * maximum denominator. If a maximum denominator is not specified, the denominator will be
+ * the lowest value necessary to represent the number exactly.
+ *
+ * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.
+ *
+ * '[BigNumber Error] Argument {not an integer|out of range} : {md}'
+ */
+ P.toFraction = function (md) {
+ var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,
+ x = this,
+ xc = x.c;
+
+ if (md != null) {
+ n = new BigNumber(md);
+
+ // Throw if md is less than one or is not an integer, unless it is Infinity.
+ if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
+ throw Error
+ (bignumberError + 'Argument ' +
+ (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));
+ }
+ }
+
+ if (!xc) return new BigNumber(x);
+
+ d = new BigNumber(ONE);
+ n1 = d0 = new BigNumber(ONE);
+ d1 = n0 = new BigNumber(ONE);
+ s = coeffToString(xc);
+
+ // Determine initial denominator.
+ // d is a power of 10 and the minimum max denominator that specifies the value exactly.
+ e = d.e = s.length - x.e - 1;
+ d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
+ md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;
+
+ exp = MAX_EXP;
+ MAX_EXP = 1 / 0;
+ n = new BigNumber(s);
+
+ // n0 = d1 = 0
+ n0.c[0] = 0;
+
+ for (; ;) {
+ q = div(n, d, 0, 1);
+ d2 = d0.plus(q.times(d1));
+ if (d2.comparedTo(md) == 1) break;
+ d0 = d1;
+ d1 = d2;
+ n1 = n0.plus(q.times(d2 = n1));
+ n0 = d2;
+ d = n.minus(q.times(d2 = d));
+ n = d2;
+ }
+
+ d2 = div(md.minus(d0), d1, 0, 1);
+ n0 = n0.plus(d2.times(n1));
+ d0 = d0.plus(d2.times(d1));
+ n0.s = n1.s = x.s;
+ e = e * 2;
+
+ // Determine which fraction is closer to x, n0/d0 or n1/d1
+ r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(
+ div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];
+
+ MAX_EXP = exp;
+
+ return r;
+ };
+
+
+ /*
+ * Return the value of this BigNumber converted to a number primitive.
+ */
+ P.toNumber = function () {
+ return +valueOf(this);
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber rounded to sd significant digits
+ * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
+ * necessary to represent the integer part of the value in fixed-point notation, then use
+ * exponential notation.
+ *
+ * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
+ * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
+ *
+ * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'
+ */
+ P.toPrecision = function (sd, rm) {
+ if (sd != null) intCheck(sd, 1, MAX);
+ return format(this, sd, rm, 2);
+ };
+
+
+ /*
+ * Return a string representing the value of this BigNumber in base b, or base 10 if b is
+ * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
+ * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
+ * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
+ * TO_EXP_NEG, return exponential notation.
+ *
+ * [b] {number} Integer, 2 to ALPHABET.length inclusive.
+ *
+ * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'
+ */
+ P.toString = function (b) {
+ var str,
+ n = this,
+ s = n.s,
+ e = n.e;
+
+ // Infinity or NaN?
+ if (e === null) {
+ if (s) {
+ str = 'Infinity';
+ if (s < 0) str = '-' + str;
+ } else {
+ str = 'NaN';
+ }
+ } else {
+ if (b == null) {
+ str = e <= TO_EXP_NEG || e >= TO_EXP_POS
+ ? toExponential(coeffToString(n.c), e)
+ : toFixedPoint(coeffToString(n.c), e, '0');
+ } else if (b === 10) {
+ n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
+ str = toFixedPoint(coeffToString(n.c), n.e, '0');
+ } else {
+ intCheck(b, 2, ALPHABET.length, 'Base');
+ str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);
+ }
+
+ if (s < 0 && n.c[0]) str = '-' + str;
+ }
+
+ return str;
+ };
+
+
+ /*
+ * Return as toString, but do not accept a base argument, and include the minus sign for
+ * negative zero.
+ */
+ P.valueOf = P.toJSON = function () {
+ return valueOf(this);
+ };
+
+
+ P._isBigNumber = true;
+
+ P[Symbol.toStringTag] = 'BigNumber';
+
+ // Node.js v10.12.0+
+ P[Symbol.for('nodejs.util.inspect.custom')] = P.valueOf;
+
+ if (configObject != null) BigNumber.set(configObject);
+
+ return BigNumber;
+}
+
+
+// PRIVATE HELPER FUNCTIONS
+
+// These functions don't need access to variables,
+// e.g. DECIMAL_PLACES, in the scope of the `clone` function above.
+
+
+function bitFloor(n) {
+ var i = n | 0;
+ return n > 0 || n === i ? i : i - 1;
+}
+
+
+// Return a coefficient array as a string of base 10 digits.
+function coeffToString(a) {
+ var s, z,
+ i = 1,
+ j = a.length,
+ r = a[0] + '';
+
+ for (; i < j;) {
+ s = a[i++] + '';
+ z = LOG_BASE - s.length;
+ for (; z--; s = '0' + s);
+ r += s;
+ }
+
+ // Determine trailing zeros.
+ for (j = r.length; r.charCodeAt(--j) === 48;);
+
+ return r.slice(0, j + 1 || 1);
+}
+
+
+// Compare the value of BigNumbers x and y.
+function compare(x, y) {
+ var a, b,
+ xc = x.c,
+ yc = y.c,
+ i = x.s,
+ j = y.s,
+ k = x.e,
+ l = y.e;
+
+ // Either NaN?
+ if (!i || !j) return null;
+
+ a = xc && !xc[0];
+ b = yc && !yc[0];
+
+ // Either zero?
+ if (a || b) return a ? b ? 0 : -j : i;
+
+ // Signs differ?
+ if (i != j) return i;
+
+ a = i < 0;
+ b = k == l;
+
+ // Either Infinity?
+ if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
+
+ // Compare exponents.
+ if (!b) return k > l ^ a ? 1 : -1;
+
+ j = (k = xc.length) < (l = yc.length) ? k : l;
+
+ // Compare digit by digit.
+ for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
+
+ // Compare lengths.
+ return k == l ? 0 : k > l ^ a ? 1 : -1;
+}
+
+
+/*
+ * Check that n is a primitive number, an integer, and in range, otherwise throw.
+ */
+function intCheck(n, min, max, name) {
+ if (n < min || n > max || n !== mathfloor(n)) {
+ throw Error
+ (bignumberError + (name || 'Argument') + (typeof n == 'number'
+ ? n < min || n > max ? ' out of range: ' : ' not an integer: '
+ : ' not a primitive number: ') + String(n));
+ }
+}
+
+
+// Assumes finite n.
+function isOdd(n) {
+ var k = n.c.length - 1;
+ return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;
+}
+
+
+function toExponential(str, e) {
+ return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +
+ (e < 0 ? 'e' : 'e+') + e;
+}
+
+
+function toFixedPoint(str, e, z) {
+ var len, zs;
+
+ // Negative exponent?
+ if (e < 0) {
+
+ // Prepend zeros.
+ for (zs = z + '.'; ++e; zs += z);
+ str = zs + str;
+
+ // Positive exponent
+ } else {
+ len = str.length;
+
+ // Append zeros.
+ if (++e > len) {
+ for (zs = z, e -= len; --e; zs += z);
+ str += zs;
+ } else if (e < len) {
+ str = str.slice(0, e) + '.' + str.slice(e);
+ }
+ }
+
+ return str;
+}
+
+
+// EXPORT
+
+
+export var BigNumber = clone();
+
+export default BigNumber;
diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html
index 424a914..1ed4a87 100644
--- a/node_modules/bignumber.js/doc/API.html
+++ b/node_modules/bignumber.js/doc/API.html
@@ -1,2237 +1,2237 @@
-
-
-
-
-
-
-bignumber.js API
-
-
-
-
-
-
-
-
-
bignumber.js
-
-
A JavaScript library for arbitrary-precision arithmetic.
-
Hosted on GitHub.
-
-
API
-
-
- See the README on GitHub for a
- quick-start introduction.
-
-
- In all examples below, var and semicolons are not shown, and if a commented-out
- value is in quotes it means toString has been called on the preceding expression.
-
-
-
-
CONSTRUCTOR
-
-
-
- BigNumberBigNumber(n [, base]) ⇒ BigNumber
-
-
- n: number|string|BigNumber
- base: number: integer, 2 to 36 inclusive. (See
- ALPHABET to extend this range).
-
-
- Returns a new instance of a BigNumber object with value n, where n
- is a numeric value in the specified base, or base 10 if
- base is omitted or is null or undefined.
-
-
-x = new BigNumber(123.4567) // '123.4567'
-// 'new' is optional
-y = BigNumber(x) // '123.4567'
-
- If n is a base 10 value it can be in normal (fixed-point) or
- exponential notation. Values in other bases must be in normal notation. Values in any base can
- have fraction digits, i.e. digits after the decimal point.
-
-
-new BigNumber(43210) // '43210'
-new BigNumber('4.321e+4') // '43210'
-new BigNumber('-735.0918e-430') // '-7.350918e-428'
-new BigNumber('123412421.234324', 5) // '607236.557696'
-
- Signed 0, signed Infinity and NaN are supported.
-
-
-new BigNumber('-Infinity') // '-Infinity'
-new BigNumber(NaN) // 'NaN'
-new BigNumber(-0) // '0'
-new BigNumber('.5') // '0.5'
-new BigNumber('+2') // '2'
-
- String values in hexadecimal literal form, e.g. '0xff', are valid, as are
- string values with the octal and binary prefixs '0o' and '0b'.
- String values in octal literal form without the prefix will be interpreted as
- decimals, e.g. '011' is interpreted as 11, not 9.
-
-
-new BigNumber(-10110100.1, 2) // '-180.5'
-new BigNumber('-0b10110100.1') // '-180.5'
-new BigNumber('ff.8', 16) // '255.5'
-new BigNumber('0xff.8') // '255.5'
-
- If a base is specified, n is rounded according to the current
- DECIMAL_PLACES and
- ROUNDING_MODE settings. This includes base
- 10 so don't include a base parameter for decimal values unless
- this behaviour is wanted.
-
-
BigNumber.config({ DECIMAL_PLACES: 5 })
-new BigNumber(1.23456789) // '1.23456789'
-new BigNumber(1.23456789, 10) // '1.23457'
-
An error is thrown if base is invalid. See Errors.
-
- There is no limit to the number of digits of a value of type string (other than
- that of JavaScript's maximum array size). See RANGE to set
- the maximum and minimum possible exponent value of a BigNumber.
-
-
-new BigNumber('5032485723458348569331745.33434346346912144534543')
-new BigNumber('4.321e10000000')
-
BigNumber NaN is returned if n is invalid
- (unless BigNumber.DEBUG is true, see below).
-
-new BigNumber('.1*') // 'NaN'
-new BigNumber('blurgh') // 'NaN'
-new BigNumber(9, 2) // 'NaN'
-
- To aid in debugging, if BigNumber.DEBUG is true then an error will
- be thrown on an invalid n. An error will also be thrown if n is of
- type number with more than 15 significant digits, as calling
- toString or valueOf on
- these numbers may not result in the intended value.
-
-
-console.log(823456789123456.3) // 823456789123456.2
-new BigNumber(823456789123456.3) // '823456789123456.2'
-BigNumber.DEBUG = true
-// '[BigNumber Error] Number primitive has more than 15 significant digits'
-new BigNumber(823456789123456.3)
-// '[BigNumber Error] Not a base 2 number'
-new BigNumber(9, 2)
-
- A BigNumber can also be created from an object literal.
- Use isBigNumber to check that it is well-formed.
-
-
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123'
-
-
-
-
-
Methods
-
The static methods of a BigNumber constructor.
-
-
-
-
-
clone
- .clone([object]) ⇒ BigNumber constructor
-
-
object: object
-
- Returns a new independent BigNumber constructor with configuration as described by
- object (see config), or with the default
- configuration if object is null or undefined.
-
-
- Throws if object is not an object. See Errors.
-
-
BigNumber.config({ DECIMAL_PLACES: 5 })
-BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
-
-x = new BigNumber(1)
-y = new BN(1)
-
-x.div(3) // 0.33333
-y.div(3) // 0.333333333
-
-// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
-BN = BigNumber.clone()
-BN.config({ DECIMAL_PLACES: 9 })
-
-
-
-
configset([object]) ⇒ object
-
- object: object: an object that contains some or all of the following
- properties.
-
-
Configures the settings for this particular BigNumber constructor.
-
-
- DECIMAL_PLACES
- -
- number: integer,
0 to 1e+9 inclusive
- Default value: 20
-
- -
- The maximum number of decimal places of the results of operations involving
- division, i.e. division, square root and base conversion operations, and power
- operations with negative exponents.
-
- -
-
BigNumber.config({ DECIMAL_PLACES: 5 })
-BigNumber.set({ DECIMAL_PLACES: 5 }) // equivalent
-
-
-
-
- ROUNDING_MODE
- -
- number: integer,
0 to 8 inclusive
- Default value: 4 (ROUND_HALF_UP)
-
- -
- The rounding mode used in the above operations and the default rounding mode of
-
decimalPlaces,
- precision,
- toExponential,
- toFixed,
- toFormat and
- toPrecision.
-
- - The modes are available as enumerated properties of the BigNumber constructor.
- -
-
BigNumber.config({ ROUNDING_MODE: 0 })
-BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) // equivalent
-
-
-
-
- EXPONENTIAL_AT
- -
- number: integer, magnitude
0 to 1e+9 inclusive, or
-
- number[]: [ integer -1e+9 to 0 inclusive, integer
- 0 to 1e+9 inclusive ]
- Default value: [-7, 20]
-
- -
- The exponent value(s) at which
toString returns exponential notation.
-
- -
- If a single number is assigned, the value is the exponent magnitude.
- If an array of two numbers is assigned then the first number is the negative exponent
- value at and beneath which exponential notation is used, and the second number is the
- positive exponent value at and above which the same.
-
- -
- For example, to emulate JavaScript numbers in terms of the exponent values at which they
- begin to use exponential notation, use
[-7, 20].
-
- -
-
BigNumber.config({ EXPONENTIAL_AT: 2 })
-new BigNumber(12.3) // '12.3' e is only 1
-new BigNumber(123) // '1.23e+2'
-new BigNumber(0.123) // '0.123' e is only -1
-new BigNumber(0.0123) // '1.23e-2'
-
-BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
-new BigNumber(123456789) // '123456789' e is only 8
-new BigNumber(0.000000123) // '1.23e-7'
-
-// Almost never return exponential notation:
-BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
-
-// Always return exponential notation:
-BigNumber.config({ EXPONENTIAL_AT: 0 })
-
- -
- Regardless of the value of
EXPONENTIAL_AT, the toFixed method
- will always return a value in normal notation and the toExponential method
- will always return a value in exponential form.
-
- -
- Calling
toString with a base argument, e.g. toString(10), will
- also always return normal notation.
-
-
-
-
- RANGE
- -
- number: integer, magnitude
1 to 1e+9 inclusive, or
-
- number[]: [ integer -1e+9 to -1 inclusive, integer
- 1 to 1e+9 inclusive ]
- Default value: [-1e+9, 1e+9]
-
- -
- The exponent value(s) beyond which overflow to
Infinity and underflow to
- zero occurs.
-
- -
- If a single number is assigned, it is the maximum exponent magnitude: values wth a
- positive exponent of greater magnitude become
Infinity and those with a
- negative exponent of greater magnitude become zero.
- -
- If an array of two numbers is assigned then the first number is the negative exponent
- limit and the second number is the positive exponent limit.
-
- -
- For example, to emulate JavaScript numbers in terms of the exponent values at which they
- become zero and
Infinity, use [-324, 308].
-
- -
-
BigNumber.config({ RANGE: 500 })
-BigNumber.config().RANGE // [ -500, 500 ]
-new BigNumber('9.999e499') // '9.999e+499'
-new BigNumber('1e500') // 'Infinity'
-new BigNumber('1e-499') // '1e-499'
-new BigNumber('1e-500') // '0'
-
-BigNumber.config({ RANGE: [-3, 4] })
-new BigNumber(99999) // '99999' e is only 4
-new BigNumber(100000) // 'Infinity' e is 5
-new BigNumber(0.001) // '0.01' e is only -3
-new BigNumber(0.0001) // '0' e is -4
-
- -
- The largest possible magnitude of a finite BigNumber is
-
9.999...e+1000000000.
- The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000.
-
-
-
-
- CRYPTO
- -
- boolean:
true or false.
- Default value: false
-
- -
- The value that determines whether cryptographically-secure pseudo-random number
- generation is used.
-
- -
- If
CRYPTO is set to true then the
- random method will generate random digits using
- crypto.getRandomValues in browsers that support it, or
- crypto.randomBytes if using Node.js.
-
- -
- If neither function is supported by the host environment then attempting to set
-
CRYPTO to true will fail and an exception will be thrown.
-
- -
- If
CRYPTO is false then the source of randomness used will be
- Math.random (which is assumed to generate at least 30 bits of
- randomness).
-
- - See
random.
- -
-
-// Node.js
-global.crypto = require('crypto')
-
-BigNumber.config({ CRYPTO: true })
-BigNumber.config().CRYPTO // true
-BigNumber.random() // 0.54340758610486147524
-
-
-
-
- MODULO_MODE
- -
- number: integer,
0 to 9 inclusive
- Default value: 1 (ROUND_DOWN)
-
- - The modulo mode used when calculating the modulus:
a mod n.
- -
- The quotient,
q = a / n, is calculated according to the
- ROUNDING_MODE that corresponds to the chosen
- MODULO_MODE.
-
- - The remainder,
r, is calculated as: r = a - n * q.
- -
- The modes that are most commonly used for the modulus/remainder operation are shown in
- the following table. Although the other rounding modes can be used, they may not give
- useful results.
-
- -
-
- | Property | Value | Description |
-
- | ROUND_UP | 0 |
-
- The remainder is positive if the dividend is negative, otherwise it is negative.
- |
-
-
- | ROUND_DOWN | 1 |
-
- The remainder has the same sign as the dividend.
- This uses 'truncating division' and matches the behaviour of JavaScript's
- remainder operator %.
- |
-
-
- | ROUND_FLOOR | 3 |
-
- The remainder has the same sign as the divisor.
- This matches Python's % operator.
- |
-
-
- | ROUND_HALF_EVEN | 6 |
- The IEEE 754 remainder function. |
-
-
- | EUCLID | 9 |
-
- The remainder is always positive. Euclidian division:
- q = sign(n) * floor(a / abs(n))
- |
-
-
-
- -
- The rounding/modulo modes are available as enumerated properties of the BigNumber
- constructor.
-
- - See
modulo.
- -
-
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
-BigNumber.config({ MODULO_MODE: 9 }) // equivalent
-
-
-
-
- POW_PRECISION
- -
- number: integer,
0 to 1e+9 inclusive.
- Default value: 0
-
- -
- The maximum precision, i.e. number of significant digits, of the result of the power
- operation (unless a modulus is specified).
-
- - If set to
0, the number of significant digits will not be limited.
- - See
exponentiatedBy.
- BigNumber.config({ POW_PRECISION: 100 })
-
-
-
- FORMAT
- - object
- -
- The
FORMAT object configures the format of the string returned by the
- toFormat method.
-
- -
- The example below shows the properties of the
FORMAT object that are
- recognised, and their default values.
-
- -
- Unlike the other configuration properties, the values of the properties of the
-
FORMAT object will not be checked for validity. The existing
- FORMAT object will simply be replaced by the object that is passed in.
- The object can include any number of the properties shown below.
-
- - See
toFormat for examples of usage.
- -
-
-BigNumber.config({
- FORMAT: {
- // string to prepend
- prefix: '',
- // decimal separator
- decimalSeparator: '.',
- // grouping separator of the integer part
- groupSeparator: ',',
- // primary grouping size of the integer part
- groupSize: 3,
- // secondary grouping size of the integer part
- secondaryGroupSize: 0,
- // grouping separator of the fraction part
- fractionGroupSeparator: ' ',
- // grouping size of the fraction part
- fractionGroupSize: 0,
- // string to append
- suffix: ''
- }
-});
-
-
-
-
- ALPHABET
- -
- string
- Default value: '0123456789abcdefghijklmnopqrstuvwxyz'
-
- -
- The alphabet used for base conversion. The length of the alphabet corresponds to the
- maximum value of the base argument that can be passed to the
-
BigNumber constructor or
- toString.
-
- -
- There is no maximum length for the alphabet, but it must be at least 2 characters long, and
- it must not contain whitespace or a repeated character, or the sign indicators
-
'+' and '-', or the decimal separator '.'.
-
- -
-
// duodecimal (base 12)
-BigNumber.config({ ALPHABET: '0123456789TE' })
-x = new BigNumber('T', 12)
-x.toString() // '10'
-x.toString(12) // 'T'
-
-
-
-
-
-
-
Returns an object with the above properties and their current values.
-
- Throws if object is not an object, or if an invalid value is assigned to
- one or more of the above properties. See Errors.
-
-
-BigNumber.config({
- DECIMAL_PLACES: 40,
- ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
- EXPONENTIAL_AT: [-10, 20],
- RANGE: [-500, 500],
- CRYPTO: true,
- MODULO_MODE: BigNumber.ROUND_FLOOR,
- POW_PRECISION: 80,
- FORMAT: {
- groupSize: 3,
- groupSeparator: ' ',
- decimalSeparator: ','
- },
- ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
-});
-
-obj = BigNumber.config();
-obj.DECIMAL_PLACES // 40
-obj.RANGE // [-500, 500]
-
-
-
-
- isBigNumber.isBigNumber(value) ⇒ boolean
-
-
value: any
-
- Returns true if value is a BigNumber instance, otherwise returns
- false.
-
-
x = 42
-y = new BigNumber(x)
-
-BigNumber.isBigNumber(x) // false
-y instanceof BigNumber // true
-BigNumber.isBigNumber(y) // true
-
-BN = BigNumber.clone();
-z = new BN(x)
-z instanceof BigNumber // false
-BigNumber.isBigNumber(z) // true
-
- If value is a BigNumber instance and BigNumber.DEBUG is true,
- then this method will also check if value is well-formed, and throw if it is not.
- See Errors.
-
-
- The check can be useful if creating a BigNumber from an object literal.
- See BigNumber.
-
-
-x = new BigNumber(10)
-
-// Change x.c to an illegitimate value.
-x.c = NaN
-
-BigNumber.DEBUG = false
-
-// No error.
-BigNumber.isBigNumber(x) // true
-
-BigNumber.DEBUG = true
-
-// Error.
-BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber'
-
-
-
-
maximum.max(n...) ⇒ BigNumber
-
- n: number|string|BigNumber
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the maximum of the arguments.
-
-
The return value is always exact and unrounded.
-
x = new BigNumber('3257869345.0378653')
-BigNumber.maximum(4e9, x, '123456789.9') // '4000000000'
-
-arr = [12, '13', new BigNumber(14)]
-BigNumber.max.apply(null, arr) // '14'
-
-
-
-
minimum.min(n...) ⇒ BigNumber
-
- n: number|string|BigNumber
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the minimum of the arguments.
-
-
The return value is always exact and unrounded.
-
x = new BigNumber('3257869345.0378653')
-BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9'
-
-arr = [2, new BigNumber(-14), '-15.9999', -12]
-BigNumber.min.apply(null, arr) // '-15.9999'
-
-
-
-
- random.random([dp]) ⇒ BigNumber
-
-
dp: number: integer, 0 to 1e+9 inclusive
-
- Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and
- less than 1.
-
-
- The return value will have dp decimal places (or less if trailing zeros are
- produced).
- If dp is omitted then the number of decimal places will default to the current
- DECIMAL_PLACES setting.
-
-
- Depending on the value of this BigNumber constructor's
- CRYPTO setting and the support for the
- crypto object in the host environment, the random digits of the return value are
- generated by either Math.random (fastest), crypto.getRandomValues
- (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js).
-
-
- To be able to set CRYPTO to true when using
- Node.js, the crypto object must be available globally:
-
-
global.crypto = require('crypto')
-
- If CRYPTO is true, i.e. one of the
- crypto methods is to be used, the value of a returned BigNumber should be
- cryptographically-secure and statistically indistinguishable from a random value.
-
-
- Throws if dp is invalid. See Errors.
-
-
BigNumber.config({ DECIMAL_PLACES: 10 })
-BigNumber.random() // '0.4117936847'
-BigNumber.random(20) // '0.78193327636914089009'
-
-
-
-
sum.sum(n...) ⇒ BigNumber
-
- n: number|string|BigNumber
- See BigNumber for further parameter details.
-
-
Returns a BigNumber whose value is the sum of the arguments.
-
The return value is always exact and unrounded.
-
x = new BigNumber('3257869345.0378653')
-BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653'
-
-arr = [2, new BigNumber(14), '15.9999', 12]
-BigNumber.sum.apply(null, arr) // '43.9999'
-
-
-
-
Properties
-
- The library's enumerated rounding modes are stored as properties of the constructor.
- (They are not referenced internally by the library itself.)
-
-
- Rounding modes 0 to 6 (inclusive) are the same as those of Java's
- BigDecimal class.
-
-
-
- | Property |
- Value |
- Description |
-
-
- | ROUND_UP |
- 0 |
- Rounds away from zero |
-
-
- | ROUND_DOWN |
- 1 |
- Rounds towards zero |
-
-
- | ROUND_CEIL |
- 2 |
- Rounds towards Infinity |
-
-
- | ROUND_FLOOR |
- 3 |
- Rounds towards -Infinity |
-
-
- | ROUND_HALF_UP |
- 4 |
-
- Rounds towards nearest neighbour.
- If equidistant, rounds away from zero
- |
-
-
- | ROUND_HALF_DOWN |
- 5 |
-
- Rounds towards nearest neighbour.
- If equidistant, rounds towards zero
- |
-
-
- | ROUND_HALF_EVEN |
- 6 |
-
- Rounds towards nearest neighbour.
- If equidistant, rounds towards even neighbour
- |
-
-
- | ROUND_HALF_CEIL |
- 7 |
-
- Rounds towards nearest neighbour.
- If equidistant, rounds towards Infinity
- |
-
-
- | ROUND_HALF_FLOOR |
- 8 |
-
- Rounds towards nearest neighbour.
- If equidistant, rounds towards -Infinity
- |
-
-
-
-BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
-BigNumber.config({ ROUNDING_MODE: 2 }) // equivalent
-
-
DEBUG
-
undefined|false|true
-
- If BigNumber.DEBUG is set true then an error will be thrown
- if this BigNumber constructor receives an invalid value, such as
- a value of type number with more than 15 significant digits.
- See BigNumber.
-
-
- An error will also be thrown if the isBigNumber
- method receives a BigNumber that is not well-formed.
- See isBigNumber.
-
-
BigNumber.DEBUG = true
-
-
-
INSTANCE
-
-
-
Methods
-
The methods inherited by a BigNumber instance from its constructor's prototype object.
-
A BigNumber is immutable in the sense that it is not changed by its methods.
-
- The treatment of ±0, ±Infinity and NaN is
- consistent with how JavaScript treats these values.
-
-
Many method names have a shorter alias.
-
-
-
-
absoluteValue.abs() ⇒ BigNumber
-
- Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of
- this BigNumber.
-
-
The return value is always exact and unrounded.
-
-x = new BigNumber(-0.8)
-y = x.absoluteValue() // '0.8'
-z = y.abs() // '0.8'
-
-
-
-
- comparedTo.comparedTo(n [, base]) ⇒ number
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- | Returns | |
-
- 1 |
- If the value of this BigNumber is greater than the value of n |
-
-
- -1 |
- If the value of this BigNumber is less than the value of n |
-
-
- 0 |
- If this BigNumber and n have the same value |
-
-
- null |
- If the value of either this BigNumber or n is NaN |
-
-
-
-x = new BigNumber(Infinity)
-y = new BigNumber(5)
-x.comparedTo(y) // 1
-x.comparedTo(x.minus(1)) // 0
-y.comparedTo(NaN) // null
-y.comparedTo('110', 2) // -1
-
-
-
-
- decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number
-
-
- dp: number: integer, 0 to 1e+9 inclusive
- rm: number: integer, 0 to 8 inclusive
-
-
- If dp is a number, returns a BigNumber whose value is the value of this BigNumber
- rounded by rounding mode rm to a maximum of dp decimal places.
-
-
- If dp is omitted, or is null or undefined, the return
- value is the number of decimal places of the value of this BigNumber, or null if
- the value of this BigNumber is ±Infinity or NaN.
-
-
- If rm is omitted, or is null or undefined,
- ROUNDING_MODE is used.
-
-
- Throws if dp or rm is invalid. See Errors.
-
-
-x = new BigNumber(1234.56)
-x.decimalPlaces(1) // '1234.6'
-x.dp() // 2
-x.decimalPlaces(2) // '1234.56'
-x.dp(10) // '1234.56'
-x.decimalPlaces(0, 1) // '1234'
-x.dp(0, 6) // '1235'
-x.decimalPlaces(1, 1) // '1234.5'
-x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6'
-x // '1234.56'
-y = new BigNumber('9.9e-101')
-y.dp() // 102
-
-
-
-
dividedBy.div(n [, base]) ⇒ BigNumber
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the value of this BigNumber divided by
- n, rounded according to the current
- DECIMAL_PLACES and
- ROUNDING_MODE settings.
-
-
-x = new BigNumber(355)
-y = new BigNumber(113)
-x.dividedBy(y) // '3.14159292035398230088'
-x.div(5) // '71'
-x.div(47, 16) // '5'
-
-
-
-
- dividedToIntegerBy.idiv(n [, base]) ⇒
- BigNumber
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by
- n.
-
-
-x = new BigNumber(5)
-y = new BigNumber(3)
-x.dividedToIntegerBy(y) // '1'
-x.idiv(0.7) // '7'
-x.idiv('0.f', 16) // '5'
-
-
-
-
- exponentiatedBy.pow(n [, m]) ⇒ BigNumber
-
-
- n: number|string|BigNumber: integer
- m: number|string|BigNumber
-
-
- Returns a BigNumber whose value is the value of this BigNumber exponentiated by
- n, i.e. raised to the power n, and optionally modulo a modulus
- m.
-
-
- Throws if n is not an integer. See Errors.
-
-
- If n is negative the result is rounded according to the current
- DECIMAL_PLACES and
- ROUNDING_MODE settings.
-
-
- As the number of digits of the result of the power operation can grow so large so quickly,
- e.g. 123.45610000 has over 50000 digits, the number of significant
- digits calculated is limited to the value of the
- POW_PRECISION setting (unless a modulus
- m is specified).
-
-
- By default POW_PRECISION is set to 0.
- This means that an unlimited number of significant digits will be calculated, and that the
- method's performance will decrease dramatically for larger exponents.
-
-
- If m is specified and the value of m, n and this
- BigNumber are integers, and n is positive, then a fast modular exponentiation
- algorithm is used, otherwise the operation will be performed as
- x.exponentiatedBy(n).modulo(m) with a
- POW_PRECISION of 0.
-
-
-Math.pow(0.7, 2) // 0.48999999999999994
-x = new BigNumber(0.7)
-x.exponentiatedBy(2) // '0.49'
-BigNumber(3).pow(-2) // '0.11111111111111111111'
-
-
-
-
- integerValue.integerValue([rm]) ⇒ BigNumber
-
-
- rm: number: integer, 0 to 8 inclusive
-
-
- Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using
- rounding mode rm.
-
-
- If rm is omitted, or is null or undefined,
- ROUNDING_MODE is used.
-
-
- Throws if rm is invalid. See Errors.
-
-
-x = new BigNumber(123.456)
-x.integerValue() // '123'
-x.integerValue(BigNumber.ROUND_CEIL) // '124'
-y = new BigNumber(-12.7)
-y.integerValue() // '-13'
-y.integerValue(BigNumber.ROUND_DOWN) // '-12'
-
- The following is an example of how to add a prototype method that emulates JavaScript's
- Math.round function. Math.ceil, Math.floor and
- Math.trunc can be emulated in the same way with
- BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and
- BigNumber.ROUND_DOWN respectively.
-
-
-BigNumber.prototype.round = function (n) {
- return n.integerValue(BigNumber.ROUND_HALF_CEIL);
-};
-x.round() // '123'
-
-
-
-
isEqualTo.eq(n [, base]) ⇒ boolean
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns true if the value of this BigNumber is equal to the value of
- n, otherwise returns false.
- As with JavaScript, NaN does not equal NaN.
-
-
Note: This method uses the comparedTo method internally.
-
-0 === 1e-324 // true
-x = new BigNumber(0)
-x.isEqualTo('1e-324') // false
-BigNumber(-0).eq(x) // true ( -0 === 0 )
-BigNumber(255).eq('ff', 16) // true
-
-y = new BigNumber(NaN)
-y.isEqualTo(NaN) // false
-
-
-
-
isFinite.isFinite() ⇒ boolean
-
- Returns true if the value of this BigNumber is a finite number, otherwise
- returns false.
-
-
- The only possible non-finite values of a BigNumber are NaN, Infinity
- and -Infinity.
-
-
-x = new BigNumber(1)
-x.isFinite() // true
-y = new BigNumber(Infinity)
-y.isFinite() // false
-
- Note: The native method isFinite() can be used if
- n <= Number.MAX_VALUE.
-
-
-
-
-
isGreaterThan.gt(n [, base]) ⇒ boolean
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns true if the value of this BigNumber is greater than the value of
- n, otherwise returns false.
-
-
Note: This method uses the comparedTo method internally.
-
-0.1 > (0.3 - 0.2) // true
-x = new BigNumber(0.1)
-x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false
-BigNumber(0).gt(x) // false
-BigNumber(11, 3).gt(11.1, 2) // true
-
-
-
-
- isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns true if the value of this BigNumber is greater than or equal to the value
- of n, otherwise returns false.
-
-
Note: This method uses the comparedTo method internally.
-
-(0.3 - 0.2) >= 0.1 // false
-x = new BigNumber(0.3).minus(0.2)
-x.isGreaterThanOrEqualTo(0.1) // true
-BigNumber(1).gte(x) // true
-BigNumber(10, 18).gte('i', 36) // true
-
-
-
-
isInteger.isInteger() ⇒ boolean
-
- Returns true if the value of this BigNumber is an integer, otherwise returns
- false.
-
-
-x = new BigNumber(1)
-x.isInteger() // true
-y = new BigNumber(123.456)
-y.isInteger() // false
-
-
-
-
isLessThan.lt(n [, base]) ⇒ boolean
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns true if the value of this BigNumber is less than the value of
- n, otherwise returns false.
-
-
Note: This method uses the comparedTo method internally.
-
-(0.3 - 0.2) < 0.1 // true
-x = new BigNumber(0.3).minus(0.2)
-x.isLessThan(0.1) // false
-BigNumber(0).lt(x) // true
-BigNumber(11.1, 2).lt(11, 3) // true
-
-
-
-
- isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns true if the value of this BigNumber is less than or equal to the value of
- n, otherwise returns false.
-
-
Note: This method uses the comparedTo method internally.
-
-0.1 <= (0.3 - 0.2) // false
-x = new BigNumber(0.1)
-x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true
-BigNumber(-1).lte(x) // true
-BigNumber(10, 18).lte('i', 36) // true
-
-
-
-
isNaN.isNaN() ⇒ boolean
-
- Returns true if the value of this BigNumber is NaN, otherwise
- returns false.
-
-
-x = new BigNumber(NaN)
-x.isNaN() // true
-y = new BigNumber('Infinity')
-y.isNaN() // false
-
Note: The native method isNaN() can also be used.
-
-
-
-
isNegative.isNegative() ⇒ boolean
-
- Returns true if the sign of this BigNumber is negative, otherwise returns
- false.
-
-
-x = new BigNumber(-0)
-x.isNegative() // true
-y = new BigNumber(2)
-y.isNegative() // false
-
Note: n < 0 can be used if n <= -Number.MIN_VALUE.
-
-
-
-
isPositive.isPositive() ⇒ boolean
-
- Returns true if the sign of this BigNumber is positive, otherwise returns
- false.
-
-
-x = new BigNumber(-0)
-x.isPositive() // false
-y = new BigNumber(2)
-y.isPositive() // true
-
-
-
-
isZero.isZero() ⇒ boolean
-
- Returns true if the value of this BigNumber is zero or minus zero, otherwise
- returns false.
-
-
-x = new BigNumber(-0)
-x.isZero() && x.isNegative() // true
-y = new BigNumber(Infinity)
-y.isZero() // false
-
Note: n == 0 can be used if n >= Number.MIN_VALUE.
-
-
-
-
- minus.minus(n [, base]) ⇒ BigNumber
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
Returns a BigNumber whose value is the value of this BigNumber minus n.
-
The return value is always exact and unrounded.
-
-0.3 - 0.1 // 0.19999999999999998
-x = new BigNumber(0.3)
-x.minus(0.1) // '0.2'
-x.minus(0.6, 20) // '0'
-
-
-
-
modulo.mod(n [, base]) ⇒ BigNumber
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e.
- the integer remainder of dividing this BigNumber by n.
-
-
- The value returned, and in particular its sign, is dependent on the value of the
- MODULO_MODE setting of this BigNumber constructor.
- If it is 1 (default value), the result will have the same sign as this BigNumber,
- and it will match that of Javascript's % operator (within the limits of double
- precision) and BigDecimal's remainder method.
-
-
The return value is always exact and unrounded.
-
- See MODULO_MODE for a description of the other
- modulo modes.
-
-
-1 % 0.9 // 0.09999999999999998
-x = new BigNumber(1)
-x.modulo(0.9) // '0.1'
-y = new BigNumber(33)
-y.mod('a', 33) // '3'
-
-
-
-
- multipliedBy.times(n [, base]) ⇒ BigNumber
-
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
- Returns a BigNumber whose value is the value of this BigNumber multiplied by n.
-
-
The return value is always exact and unrounded.
-
-0.6 * 3 // 1.7999999999999998
-x = new BigNumber(0.6)
-y = x.multipliedBy(3) // '1.8'
-BigNumber('7e+500').times(y) // '1.26e+501'
-x.multipliedBy('-a', 16) // '-6'
-
-
-
-
negated.negated() ⇒ BigNumber
-
- Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by
- -1.
-
-
-x = new BigNumber(1.8)
-x.negated() // '-1.8'
-y = new BigNumber(-1.3)
-y.negated() // '1.3'
-
-
-
-
plus.plus(n [, base]) ⇒ BigNumber
-
- n: number|string|BigNumber
- base: number
- See BigNumber for further parameter details.
-
-
Returns a BigNumber whose value is the value of this BigNumber plus n.
-
The return value is always exact and unrounded.
-
-0.1 + 0.2 // 0.30000000000000004
-x = new BigNumber(0.1)
-y = x.plus(0.2) // '0.3'
-BigNumber(0.7).plus(x).plus(y) // '1'
-x.plus('0.1', 8) // '0.225'
-
-
-
-
- precision.sd([d [, rm]]) ⇒ BigNumber|number
-
-
- d: number|boolean: integer, 1 to 1e+9
- inclusive, or true or false
- rm: number: integer, 0 to 8 inclusive.
-
-
- If d is a number, returns a BigNumber whose value is the value of this BigNumber
- rounded to a precision of d significant digits using rounding mode
- rm.
-
-
- If d is omitted or is null or undefined, the return
- value is the number of significant digits of the value of this BigNumber, or null
- if the value of this BigNumber is ±Infinity or NaN.
-
-
- If d is true then any trailing zeros of the integer
- part of a number are counted as significant digits, otherwise they are not.
-
-
- If rm is omitted or is null or undefined,
- ROUNDING_MODE will be used.
-
-
- Throws if d or rm is invalid. See Errors.
-
-
-x = new BigNumber(9876.54321)
-x.precision(6) // '9876.54'
-x.sd() // 9
-x.precision(6, BigNumber.ROUND_UP) // '9876.55'
-x.sd(2) // '9900'
-x.precision(2, 1) // '9800'
-x // '9876.54321'
-y = new BigNumber(987000)
-y.precision() // 3
-y.sd(true) // 6
-
-
-
-
shiftedBy.shiftedBy(n) ⇒ BigNumber
-
- n: number: integer,
- -9007199254740991 to 9007199254740991 inclusive
-
-
- Returns a BigNumber whose value is the value of this BigNumber shifted by n
- places.
-
- The shift is of the decimal point, i.e. of powers of ten, and is to the left if n
- is negative or to the right if n is positive.
-
-
The return value is always exact and unrounded.
-
- Throws if n is invalid. See Errors.
-
-
-x = new BigNumber(1.23)
-x.shiftedBy(3) // '1230'
-x.shiftedBy(-3) // '0.00123'
-
-
-
-
squareRoot.sqrt() ⇒ BigNumber
-
- Returns a BigNumber whose value is the square root of the value of this BigNumber,
- rounded according to the current
- DECIMAL_PLACES and
- ROUNDING_MODE settings.
-
-
- The return value will be correctly rounded, i.e. rounded as if the result was first calculated
- to an infinite number of correct digits before rounding.
-
-
-x = new BigNumber(16)
-x.squareRoot() // '4'
-y = new BigNumber(3)
-y.sqrt() // '1.73205080756887729353'
-
-
-
-
- toExponential.toExponential([dp [, rm]]) ⇒ string
-
-
- dp: number: integer, 0 to 1e+9 inclusive
- rm: number: integer, 0 to 8 inclusive
-
-
- Returns a string representing the value of this BigNumber in exponential notation rounded
- using rounding mode rm to dp decimal places, i.e with one digit
- before the decimal point and dp digits after it.
-
-
- If the value of this BigNumber in exponential notation has fewer than dp fraction
- digits, the return value will be appended with zeros accordingly.
-
-
- If dp is omitted, or is null or undefined, the number
- of digits after the decimal point defaults to the minimum number of digits necessary to
- represent the value exactly.
- If rm is omitted or is null or undefined,
- ROUNDING_MODE is used.
-
-
- Throws if dp or rm is invalid. See Errors.
-
-
-x = 45.6
-y = new BigNumber(x)
-x.toExponential() // '4.56e+1'
-y.toExponential() // '4.56e+1'
-x.toExponential(0) // '5e+1'
-y.toExponential(0) // '5e+1'
-x.toExponential(1) // '4.6e+1'
-y.toExponential(1) // '4.6e+1'
-y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN)
-x.toExponential(3) // '4.560e+1'
-y.toExponential(3) // '4.560e+1'
-
-
-
-
- toFixed.toFixed([dp [, rm]]) ⇒ string
-
-
- dp: number: integer, 0 to 1e+9 inclusive
- rm: number: integer, 0 to 8 inclusive
-
-
- Returns a string representing the value of this BigNumber in normal (fixed-point) notation
- rounded to dp decimal places using rounding mode rm.
-
-
- If the value of this BigNumber in normal notation has fewer than dp fraction
- digits, the return value will be appended with zeros accordingly.
-
-
- Unlike Number.prototype.toFixed, which returns exponential notation if a number
- is greater or equal to 1021, this method will always return normal
- notation.
-
-
- If dp is omitted or is null or undefined, the return
- value will be unrounded and in normal notation. This is also unlike
- Number.prototype.toFixed, which returns the value to zero decimal places.
- It is useful when fixed-point notation is required and the current
- EXPONENTIAL_AT setting causes
- toString to return exponential notation.
- If rm is omitted or is null or undefined,
- ROUNDING_MODE is used.
-
-
- Throws if dp or rm is invalid. See Errors.
-
-
-x = 3.456
-y = new BigNumber(x)
-x.toFixed() // '3'
-y.toFixed() // '3.456'
-y.toFixed(0) // '3'
-x.toFixed(2) // '3.46'
-y.toFixed(2) // '3.46'
-y.toFixed(2, 1) // '3.45' (ROUND_DOWN)
-x.toFixed(5) // '3.45600'
-y.toFixed(5) // '3.45600'
-
-
-
-
- toFormat.toFormat([dp [, rm[, format]]]) ⇒ string
-
-
- dp: number: integer, 0 to 1e+9 inclusive
- rm: number: integer, 0 to 8 inclusive
- format: object: see FORMAT
-
-
-
- Returns a string representing the value of this BigNumber in normal (fixed-point) notation
- rounded to dp decimal places using rounding mode rm, and formatted
- according to the properties of the format object.
-
-
- See FORMAT and the examples below for the properties of the
- format object, their types, and their usage. A formatting object may contain
- some or all of the recognised properties.
-
-
- If dp is omitted or is null or undefined, then the
- return value is not rounded to a fixed number of decimal places.
- If rm is omitted or is null or undefined,
- ROUNDING_MODE is used.
- If format is omitted or is null or undefined, the
- FORMAT object is used.
-
-
- Throws if dp, rm or format is invalid. See
- Errors.
-
-
-fmt = {
- prefix = '',
- decimalSeparator: '.',
- groupSeparator: ',',
- groupSize: 3,
- secondaryGroupSize: 0,
- fractionGroupSeparator: ' ',
- fractionGroupSize: 0,
- suffix = ''
-}
-
-x = new BigNumber('123456789.123456789')
-
-// Set the global formatting options
-BigNumber.config({ FORMAT: fmt })
-
-x.toFormat() // '123,456,789.123456789'
-x.toFormat(3) // '123,456,789.123'
-
-// If a reference to the object assigned to FORMAT has been retained,
-// the format properties can be changed directly
-fmt.groupSeparator = ' '
-fmt.fractionGroupSize = 5
-x.toFormat() // '123 456 789.12345 6789'
-
-// Alternatively, pass the formatting options as an argument
-fmt = {
- prefix: '=> ',
- decimalSeparator: ',',
- groupSeparator: '.',
- groupSize: 3,
- secondaryGroupSize: 2
-}
-
-x.toFormat() // '123 456 789.12345 6789'
-x.toFormat(fmt) // '=> 12.34.56.789,123456789'
-x.toFormat(2, fmt) // '=> 12.34.56.789,12'
-x.toFormat(3, BigNumber.ROUND_UP, fmt) // '=> 12.34.56.789,124'
-
-
-
-
- toFraction.toFraction([maximum_denominator])
- ⇒ [BigNumber, BigNumber]
-
-
- maximum_denominator:
- number|string|BigNumber: integer >= 1 and <=
- Infinity
-
-
- Returns an array of two BigNumbers representing the value of this BigNumber as a simple
- fraction with an integer numerator and an integer denominator. The denominator will be a
- positive non-zero value less than or equal to maximum_denominator.
-
-
- If a maximum_denominator is not specified, or is null or
- undefined, the denominator will be the lowest value necessary to represent the
- number exactly.
-
-
- Throws if maximum_denominator is invalid. See Errors.
-
-
-x = new BigNumber(1.75)
-x.toFraction() // '7, 4'
-
-pi = new BigNumber('3.14159265358')
-pi.toFraction() // '157079632679,50000000000'
-pi.toFraction(100000) // '312689, 99532'
-pi.toFraction(10000) // '355, 113'
-pi.toFraction(100) // '311, 99'
-pi.toFraction(10) // '22, 7'
-pi.toFraction(1) // '3, 1'
-
-
-
-
toJSON.toJSON() ⇒ string
-
As valueOf.
-
-x = new BigNumber('177.7e+457')
-y = new BigNumber(235.4325)
-z = new BigNumber('0.0098074')
-
-// Serialize an array of three BigNumbers
-str = JSON.stringify( [x, y, z] )
-// "["1.777e+459","235.4325","0.0098074"]"
-
-// Return an array of three BigNumbers
-JSON.parse(str, function (key, val) {
- return key === '' ? val : new BigNumber(val)
-})
-
-
-
-
toNumber.toNumber() ⇒ number
-
Returns the value of this BigNumber as a JavaScript number primitive.
-
- This method is identical to using type coercion with the unary plus operator.
-
-
-x = new BigNumber(456.789)
-x.toNumber() // 456.789
-+x // 456.789
-
-y = new BigNumber('45987349857634085409857349856430985')
-y.toNumber() // 4.598734985763409e+34
-
-z = new BigNumber(-0)
-1 / z.toNumber() // -Infinity
-1 / +z // -Infinity
-
-
-
-
- toPrecision.toPrecision([sd [, rm]]) ⇒ string
-
-
- sd: number: integer, 1 to 1e+9 inclusive
- rm: number: integer, 0 to 8 inclusive
-
-
- Returns a string representing the value of this BigNumber rounded to sd
- significant digits using rounding mode rm.
-
-
- If sd is less than the number of digits necessary to represent the integer part
- of the value in normal (fixed-point) notation, then exponential notation is used.
-
-
- If sd is omitted, or is null or undefined, then the
- return value is the same as n.toString().
- If rm is omitted or is null or undefined,
- ROUNDING_MODE is used.
-
-
- Throws if sd or rm is invalid. See Errors.
-
-
-x = 45.6
-y = new BigNumber(x)
-x.toPrecision() // '45.6'
-y.toPrecision() // '45.6'
-x.toPrecision(1) // '5e+1'
-y.toPrecision(1) // '5e+1'
-y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP)
-y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN)
-x.toPrecision(5) // '45.600'
-y.toPrecision(5) // '45.600'
-
-
-
-
toString.toString([base]) ⇒ string
-
- base: number: integer, 2 to ALPHABET.length
- inclusive (see ALPHABET).
-
-
- Returns a string representing the value of this BigNumber in the specified base, or base
- 10 if base is omitted or is null or
- undefined.
-
-
- For bases above 10, and using the default base conversion alphabet
- (see ALPHABET), values from 10 to
- 35 are represented by a-z
- (as with Number.prototype.toString).
-
-
- If a base is specified the value is rounded according to the current
- DECIMAL_PLACES
- and ROUNDING_MODE settings.
-
-
- If a base is not specified, and this BigNumber has a positive
- exponent that is equal to or greater than the positive component of the
- current EXPONENTIAL_AT setting,
- or a negative exponent equal to or less than the negative component of the
- setting, then exponential notation is returned.
-
-
If base is null or undefined it is ignored.
-
- Throws if base is invalid. See Errors.
-
-
-x = new BigNumber(750000)
-x.toString() // '750000'
-BigNumber.config({ EXPONENTIAL_AT: 5 })
-x.toString() // '7.5e+5'
-
-y = new BigNumber(362.875)
-y.toString(2) // '101101010.111'
-y.toString(9) // '442.77777777777777777778'
-y.toString(32) // 'ba.s'
-
-BigNumber.config({ DECIMAL_PLACES: 4 });
-z = new BigNumber('1.23456789')
-z.toString() // '1.23456789'
-z.toString(10) // '1.2346'
-
-
-
-
valueOf.valueOf() ⇒ string
-
- As toString, but does not accept a base argument and includes
- the minus sign for negative zero.
-
-
-x = new BigNumber('-0')
-x.toString() // '0'
-x.valueOf() // '-0'
-y = new BigNumber('1.777e+457')
-y.valueOf() // '1.777e+457'
-
-
-
-
Properties
-
The properties of a BigNumber instance:
-
-
- | Property |
- Description |
- Type |
- Value |
-
-
- | c |
- coefficient* |
- number[] |
- Array of base 1e14 numbers |
-
-
- | e |
- exponent |
- number |
- Integer, -1000000000 to 1000000000 inclusive |
-
-
- | s |
- sign |
- number |
- -1 or 1 |
-
-
-
*significand
-
- The value of any of the c, e and s properties may also
- be null.
-
-
- The above properties are best considered to be read-only. In early versions of this library it
- was okay to change the exponent of a BigNumber by writing to its exponent property directly,
- but this is no longer reliable as the value of the first element of the coefficient array is
- now dependent on the exponent.
-
-
- Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are
- not necessarily preserved.
-
-
x = new BigNumber(0.123) // '0.123'
-x.toExponential() // '1.23e-1'
-x.c // '1,2,3'
-x.e // -1
-x.s // 1
-
-y = new Number(-123.4567000e+2) // '-12345.67'
-y.toExponential() // '-1.234567e+4'
-z = new BigNumber('-123.4567000e+2') // '-12345.67'
-z.toExponential() // '-1.234567e+4'
-z.c // '1,2,3,4,5,6,7'
-z.e // 4
-z.s // -1
-
-
-
-
Zero, NaN and Infinity
-
- The table below shows how ±0, NaN and
- ±Infinity are stored.
-
-
-
- | |
- c |
- e |
- s |
-
-
- | ±0 |
- [0] |
- 0 |
- ±1 |
-
-
- | NaN |
- null |
- null |
- null |
-
-
- | ±Infinity |
- null |
- null |
- ±1 |
-
-
-
-x = new Number(-0) // 0
-1 / x == -Infinity // true
-
-y = new BigNumber(-0) // '0'
-y.c // '0' ( [0].toString() )
-y.e // 0
-y.s // -1
-
-
-
-
Errors
-
The table below shows the errors that are thrown.
-
- The errors are generic Error objects whose message begins
- '[BigNumber Error]'.
-
-
-
- | Method |
- Throws |
-
-
-
- BigNumber
- comparedTo
- dividedBy
- dividedToIntegerBy
- isEqualTo
- isGreaterThan
- isGreaterThanOrEqualTo
- isLessThan
- isLessThanOrEqualTo
- minus
- modulo
- plus
- multipliedBy
- |
- Base not a primitive number |
-
-
- | Base not an integer |
-
-
- | Base out of range |
-
-
- | Number primitive has more than 15 significant digits* |
-
-
- | Not a base... number* |
-
-
- | Not a number* |
-
-
- clone |
- Object expected |
-
-
- config |
- Object expected |
-
-
- DECIMAL_PLACES not a primitive number |
-
-
- DECIMAL_PLACES not an integer |
-
-
- DECIMAL_PLACES out of range |
-
-
- ROUNDING_MODE not a primitive number |
-
-
- ROUNDING_MODE not an integer |
-
-
- ROUNDING_MODE out of range |
-
-
- EXPONENTIAL_AT not a primitive number |
-
-
- EXPONENTIAL_AT not an integer |
-
-
- EXPONENTIAL_AT out of range |
-
-
- RANGE not a primitive number |
-
-
- RANGE not an integer |
-
-
- RANGE cannot be zero |
-
-
- RANGE cannot be zero |
-
-
- CRYPTO not true or false |
-
-
- crypto unavailable |
-
-
- MODULO_MODE not a primitive number |
-
-
- MODULO_MODE not an integer |
-
-
- MODULO_MODE out of range |
-
-
- POW_PRECISION not a primitive number |
-
-
- POW_PRECISION not an integer |
-
-
- POW_PRECISION out of range |
-
-
- FORMAT not an object |
-
-
- ALPHABET invalid |
-
-
-
- decimalPlaces
- precision
- random
- shiftedBy
- toExponential
- toFixed
- toFormat
- toPrecision
- |
- Argument not a primitive number |
-
-
- | Argument not an integer |
-
-
- | Argument out of range |
-
-
-
- decimalPlaces
- precision
- |
- Argument not true or false |
-
-
- exponentiatedBy |
- Argument not an integer |
-
-
- isBigNumber |
- Invalid BigNumber* |
-
-
-
- minimum
- maximum
- |
- Not a number* |
-
-
-
- random
- |
- crypto unavailable |
-
-
-
- toFormat
- |
- Argument not an object |
-
-
- toFraction |
- Argument not an integer |
-
-
- | Argument out of range |
-
-
- toString |
- Base not a primitive number |
-
-
- | Base not an integer |
-
-
- | Base out of range |
-
-
-
*Only thrown if BigNumber.DEBUG is true.
-
To determine if an exception is a BigNumber Error:
-
-try {
- // ...
-} catch (e) {
- if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
- // ...
- }
-}
-
-
-
-
Type coercion
-
- To prevent the accidental use of a BigNumber in primitive number operations, or the
- accidental addition of a BigNumber to a string, the valueOf method can be safely
- overwritten as shown below.
-
-
- The valueOf method is the same as the
- toJSON method, and both are the same as the
- toString method except they do not take a base
- argument and they include the minus sign for negative zero.
-
-
-BigNumber.prototype.valueOf = function () {
- throw Error('valueOf called!')
-}
-
-x = new BigNumber(1)
-x / 2 // '[BigNumber Error] valueOf called!'
-x + 'abc' // '[BigNumber Error] valueOf called!'
-
-
-
-
-
FAQ
-
-
Why are trailing fractional zeros removed from BigNumbers?
-
- Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the
- precision of a value. This can be useful but the results of arithmetic operations can be
- misleading.
-
-
-x = new BigDecimal("1.0")
-y = new BigDecimal("1.1000")
-z = x.add(y) // 2.1000
-
-x = new BigDecimal("1.20")
-y = new BigDecimal("3.45000")
-z = x.multiply(y) // 4.1400000
-
- To specify the precision of a value is to specify that the value lies
- within a certain range.
-
-
- In the first example, x has a value of 1.0. The trailing zero shows
- the precision of the value, implying that it is in the range 0.95 to
- 1.05. Similarly, the precision indicated by the trailing zeros of y
- indicates that the value is in the range 1.09995 to 1.10005.
-
-
- If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995,
- and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the
- range of the result of the addition implied by the precision of its operands is
- 2.04995 to 2.15005.
-
-
- The result given by BigDecimal of 2.1000 however, indicates that the value is in
- the range 2.09995 to 2.10005 and therefore the precision implied by
- its trailing zeros may be misleading.
-
-
- In the second example, the true range is 4.122744 to 4.157256 yet
- the BigDecimal answer of 4.1400000 indicates a range of 4.13999995
- to 4.14000005. Again, the precision implied by the trailing zeros may be
- misleading.
-
-
- This library, like binary floating point and most calculators, does not retain trailing
- fractional zeros. Instead, the toExponential, toFixed and
- toPrecision methods enable trailing zeros to be added if and when required.
-
-
-
-
-
+
+
+
+
+
+
+bignumber.js API
+
+
+
+
+
+
+
+
+
bignumber.js
+
+
A JavaScript library for arbitrary-precision arithmetic.
+
Hosted on GitHub.
+
+
API
+
+
+ See the README on GitHub for a
+ quick-start introduction.
+
+
+ In all examples below, var and semicolons are not shown, and if a commented-out
+ value is in quotes it means toString has been called on the preceding expression.
+
+
+
+
CONSTRUCTOR
+
+
+
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber
+
+
+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See
+ ALPHABET to extend this range).
+
+
+ Returns a new instance of a BigNumber object with value n, where n
+ is a numeric value in the specified base, or base 10 if
+ base is omitted or is null or undefined.
+
+
+x = new BigNumber(123.4567) // '123.4567'
+// 'new' is optional
+y = BigNumber(x) // '123.4567'
+
+ If n is a base 10 value it can be in normal (fixed-point) or
+ exponential notation. Values in other bases must be in normal notation. Values in any base can
+ have fraction digits, i.e. digits after the decimal point.
+
+
+new BigNumber(43210) // '43210'
+new BigNumber('4.321e+4') // '43210'
+new BigNumber('-735.0918e-430') // '-7.350918e-428'
+new BigNumber('123412421.234324', 5) // '607236.557696'
+
+ Signed 0, signed Infinity and NaN are supported.
+
+
+new BigNumber('-Infinity') // '-Infinity'
+new BigNumber(NaN) // 'NaN'
+new BigNumber(-0) // '0'
+new BigNumber('.5') // '0.5'
+new BigNumber('+2') // '2'
+
+ String values in hexadecimal literal form, e.g. '0xff', are valid, as are
+ string values with the octal and binary prefixs '0o' and '0b'.
+ String values in octal literal form without the prefix will be interpreted as
+ decimals, e.g. '011' is interpreted as 11, not 9.
+
+
+new BigNumber(-10110100.1, 2) // '-180.5'
+new BigNumber('-0b10110100.1') // '-180.5'
+new BigNumber('ff.8', 16) // '255.5'
+new BigNumber('0xff.8') // '255.5'
+
+ If a base is specified, n is rounded according to the current
+ DECIMAL_PLACES and
+ ROUNDING_MODE settings. This includes base
+ 10 so don't include a base parameter for decimal values unless
+ this behaviour is wanted.
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789) // '1.23456789'
+new BigNumber(1.23456789, 10) // '1.23457'
+
An error is thrown if base is invalid. See Errors.
+
+ There is no limit to the number of digits of a value of type string (other than
+ that of JavaScript's maximum array size). See RANGE to set
+ the maximum and minimum possible exponent value of a BigNumber.
+
+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+
BigNumber NaN is returned if n is invalid
+ (unless BigNumber.DEBUG is true, see below).
+
+new BigNumber('.1*') // 'NaN'
+new BigNumber('blurgh') // 'NaN'
+new BigNumber(9, 2) // 'NaN'
+
+ To aid in debugging, if BigNumber.DEBUG is true then an error will
+ be thrown on an invalid n. An error will also be thrown if n is of
+ type number with more than 15 significant digits, as calling
+ toString or valueOf on
+ these numbers may not result in the intended value.
+
+
+console.log(823456789123456.3) // 823456789123456.2
+new BigNumber(823456789123456.3) // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+
+ A BigNumber can also be created from an object literal.
+ Use isBigNumber to check that it is well-formed.
+
+
new BigNumber({ s: 1, e: 2, c: [ 777, 12300000000000 ], _isBigNumber: true }) // '777.123'
+
+
+
+
+
Methods
+
The static methods of a BigNumber constructor.
+
+
+
+
+
clone
+ .clone([object]) ⇒ BigNumber constructor
+
+
object: object
+
+ Returns a new independent BigNumber constructor with configuration as described by
+ object (see config), or with the default
+ configuration if object is null or undefined.
+
+
+ Throws if object is not an object. See Errors.
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3) // 0.33333
+y.div(3) // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+
+
+
+
configset([object]) ⇒ object
+
+ object: object: an object that contains some or all of the following
+ properties.
+
+
Configures the settings for this particular BigNumber constructor.
+
+
+ DECIMAL_PLACES
+ -
+ number: integer,
0 to 1e+9 inclusive
+ Default value: 20
+
+ -
+ The maximum number of decimal places of the results of operations involving
+ division, i.e. division, square root and base conversion operations, and power
+ operations with negative exponents.
+
+ -
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 }) // equivalent
+
+
+
+
+ ROUNDING_MODE
+ -
+ number: integer,
0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP)
+
+ -
+ The rounding mode used in the above operations and the default rounding mode of
+
decimalPlaces,
+ precision,
+ toExponential,
+ toFixed,
+ toFormat and
+ toPrecision.
+
+ - The modes are available as enumerated properties of the BigNumber constructor.
+ -
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) // equivalent
+
+
+
+
+ EXPONENTIAL_AT
+ -
+ number: integer, magnitude
0 to 1e+9 inclusive, or
+
+ number[]: [ integer -1e+9 to 0 inclusive, integer
+ 0 to 1e+9 inclusive ]
+ Default value: [-7, 20]
+
+ -
+ The exponent value(s) at which
toString returns exponential notation.
+
+ -
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent
+ value at and beneath which exponential notation is used, and the second number is the
+ positive exponent value at and above which the same.
+
+ -
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they
+ begin to use exponential notation, use
[-7, 20].
+
+ -
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3) // '12.3' e is only 1
+new BigNumber(123) // '1.23e+2'
+new BigNumber(0.123) // '0.123' e is only -1
+new BigNumber(0.0123) // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789) // '123456789' e is only 8
+new BigNumber(0.000000123) // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+ -
+ Regardless of the value of
EXPONENTIAL_AT, the toFixed method
+ will always return a value in normal notation and the toExponential method
+ will always return a value in exponential form.
+
+ -
+ Calling
toString with a base argument, e.g. toString(10), will
+ also always return normal notation.
+
+
+
+
+ RANGE
+ -
+ number: integer, magnitude
1 to 1e+9 inclusive, or
+
+ number[]: [ integer -1e+9 to -1 inclusive, integer
+ 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9]
+
+ -
+ The exponent value(s) beyond which overflow to
Infinity and underflow to
+ zero occurs.
+
+ -
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a
+ positive exponent of greater magnitude become
Infinity and those with a
+ negative exponent of greater magnitude become zero.
+ -
+ If an array of two numbers is assigned then the first number is the negative exponent
+ limit and the second number is the positive exponent limit.
+
+ -
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they
+ become zero and
Infinity, use [-324, 308].
+
+ -
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE // [ -500, 500 ]
+new BigNumber('9.999e499') // '9.999e+499'
+new BigNumber('1e500') // 'Infinity'
+new BigNumber('1e-499') // '1e-499'
+new BigNumber('1e-500') // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999) // '99999' e is only 4
+new BigNumber(100000) // 'Infinity' e is 5
+new BigNumber(0.001) // '0.01' e is only -3
+new BigNumber(0.0001) // '0' e is -4
+
+ -
+ The largest possible magnitude of a finite BigNumber is
+
9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000.
+
+
+
+
+ CRYPTO
+ -
+ boolean:
true or false.
+ Default value: false
+
+ -
+ The value that determines whether cryptographically-secure pseudo-random number
+ generation is used.
+
+ -
+ If
CRYPTO is set to true then the
+ random method will generate random digits using
+ crypto.getRandomValues in browsers that support it, or
+ crypto.randomBytes if using Node.js.
+
+ -
+ If neither function is supported by the host environment then attempting to set
+
CRYPTO to true will fail and an exception will be thrown.
+
+ -
+ If
CRYPTO is false then the source of randomness used will be
+ Math.random (which is assumed to generate at least 30 bits of
+ randomness).
+
+ - See
random.
+ -
+
+// Node.js
+global.crypto = require('crypto')
+
+BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO // true
+BigNumber.random() // 0.54340758610486147524
+
+
+
+
+ MODULO_MODE
+ -
+ number: integer,
0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN)
+
+ - The modulo mode used when calculating the modulus:
a mod n.
+ -
+ The quotient,
q = a / n, is calculated according to the
+ ROUNDING_MODE that corresponds to the chosen
+ MODULO_MODE.
+
+ - The remainder,
r, is calculated as: r = a - n * q.
+ -
+ The modes that are most commonly used for the modulus/remainder operation are shown in
+ the following table. Although the other rounding modes can be used, they may not give
+ useful results.
+
+ -
+
+ | Property | Value | Description |
+
+ | ROUND_UP | 0 |
+
+ The remainder is positive if the dividend is negative, otherwise it is negative.
+ |
+
+
+ | ROUND_DOWN | 1 |
+
+ The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's
+ remainder operator %.
+ |
+
+
+ | ROUND_FLOOR | 3 |
+
+ The remainder has the same sign as the divisor.
+ This matches Python's % operator.
+ |
+
+
+ | ROUND_HALF_EVEN | 6 |
+ The IEEE 754 remainder function. |
+
+
+ | EUCLID | 9 |
+
+ The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n))
+ |
+
+
+
+ -
+ The rounding/modulo modes are available as enumerated properties of the BigNumber
+ constructor.
+
+ - See
modulo.
+ -
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 }) // equivalent
+
+
+
+
+ POW_PRECISION
+ -
+ number: integer,
0 to 1e+9 inclusive.
+ Default value: 0
+
+ -
+ The maximum precision, i.e. number of significant digits, of the result of the power
+ operation (unless a modulus is specified).
+
+ - If set to
0, the number of significant digits will not be limited.
+ - See
exponentiatedBy.
+ BigNumber.config({ POW_PRECISION: 100 })
+
+
+
+ FORMAT
+ - object
+ -
+ The
FORMAT object configures the format of the string returned by the
+ toFormat method.
+
+ -
+ The example below shows the properties of the
FORMAT object that are
+ recognised, and their default values.
+
+ -
+ Unlike the other configuration properties, the values of the properties of the
+
FORMAT object will not be checked for validity. The existing
+ FORMAT object will simply be replaced by the object that is passed in.
+ The object can include any number of the properties shown below.
+
+ - See
toFormat for examples of usage.
+ -
+
+BigNumber.config({
+ FORMAT: {
+ // string to prepend
+ prefix: '',
+ // decimal separator
+ decimalSeparator: '.',
+ // grouping separator of the integer part
+ groupSeparator: ',',
+ // primary grouping size of the integer part
+ groupSize: 3,
+ // secondary grouping size of the integer part
+ secondaryGroupSize: 0,
+ // grouping separator of the fraction part
+ fractionGroupSeparator: ' ',
+ // grouping size of the fraction part
+ fractionGroupSize: 0,
+ // string to append
+ suffix: ''
+ }
+});
+
+
+
+
+ ALPHABET
+ -
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz'
+
+ -
+ The alphabet used for base conversion. The length of the alphabet corresponds to the
+ maximum value of the base argument that can be passed to the
+
BigNumber constructor or
+ toString.
+
+ -
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and
+ it must not contain whitespace or a repeated character, or the sign indicators
+
'+' and '-', or the decimal separator '.'.
+
+ -
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString() // '10'
+x.toString(12) // 'T'
+
+
+
+
+
+
+
Returns an object with the above properties and their current values.
+
+ Throws if object is not an object, or if an invalid value is assigned to
+ one or more of the above properties. See Errors.
+
+
+BigNumber.config({
+ DECIMAL_PLACES: 40,
+ ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+ EXPONENTIAL_AT: [-10, 20],
+ RANGE: [-500, 500],
+ CRYPTO: true,
+ MODULO_MODE: BigNumber.ROUND_FLOOR,
+ POW_PRECISION: 80,
+ FORMAT: {
+ groupSize: 3,
+ groupSeparator: ' ',
+ decimalSeparator: ','
+ },
+ ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES // 40
+obj.RANGE // [-500, 500]
+
+
+
+
+ isBigNumber.isBigNumber(value) ⇒ boolean
+
+
value: any
+
+ Returns true if value is a BigNumber instance, otherwise returns
+ false.
+
+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x) // false
+y instanceof BigNumber // true
+BigNumber.isBigNumber(y) // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber // false
+BigNumber.isBigNumber(z) // true
+
+ If value is a BigNumber instance and BigNumber.DEBUG is true,
+ then this method will also check if value is well-formed, and throw if it is not.
+ See Errors.
+
+
+ The check can be useful if creating a BigNumber from an object literal.
+ See BigNumber.
+
+
+x = new BigNumber(10)
+
+// Change x.c to an illegitimate value.
+x.c = NaN
+
+BigNumber.DEBUG = false
+
+// No error.
+BigNumber.isBigNumber(x) // true
+
+BigNumber.DEBUG = true
+
+// Error.
+BigNumber.isBigNumber(x) // '[BigNumber Error] Invalid BigNumber'
+
+
+
+
maximum.max(n...) ⇒ BigNumber
+
+ n: number|string|BigNumber
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the maximum of the arguments.
+
+
The return value is always exact and unrounded.
+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9') // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max.apply(null, arr) // '14'
+
+
+
+
minimum.min(n...) ⇒ BigNumber
+
+ n: number|string|BigNumber
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the minimum of the arguments.
+
+
The return value is always exact and unrounded.
+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min.apply(null, arr) // '-15.9999'
+
+
+
+
+ random.random([dp]) ⇒ BigNumber
+
+
dp: number: integer, 0 to 1e+9 inclusive
+
+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and
+ less than 1.
+
+
+ The return value will have dp decimal places (or less if trailing zeros are
+ produced).
+ If dp is omitted then the number of decimal places will default to the current
+ DECIMAL_PLACES setting.
+
+
+ Depending on the value of this BigNumber constructor's
+ CRYPTO setting and the support for the
+ crypto object in the host environment, the random digits of the return value are
+ generated by either Math.random (fastest), crypto.getRandomValues
+ (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js).
+
+
+ To be able to set CRYPTO to true when using
+ Node.js, the crypto object must be available globally:
+
+
global.crypto = require('crypto')
+
+ If CRYPTO is true, i.e. one of the
+ crypto methods is to be used, the value of a returned BigNumber should be
+ cryptographically-secure and statistically indistinguishable from a random value.
+
+
+ Throws if dp is invalid. See Errors.
+
+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random() // '0.4117936847'
+BigNumber.random(20) // '0.78193327636914089009'
+
+
+
+
sum.sum(n...) ⇒ BigNumber
+
+ n: number|string|BigNumber
+ See BigNumber for further parameter details.
+
+
Returns a BigNumber whose value is the sum of the arguments.
+
The return value is always exact and unrounded.
+
x = new BigNumber('3257869345.0378653')
+BigNumber.sum(4e9, x, '123456789.9') // '7381326134.9378653'
+
+arr = [2, new BigNumber(14), '15.9999', 12]
+BigNumber.sum.apply(null, arr) // '43.9999'
+
+
+
+
Properties
+
+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.)
+
+
+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's
+ BigDecimal class.
+
+
+
+ | Property |
+ Value |
+ Description |
+
+
+ | ROUND_UP |
+ 0 |
+ Rounds away from zero |
+
+
+ | ROUND_DOWN |
+ 1 |
+ Rounds towards zero |
+
+
+ | ROUND_CEIL |
+ 2 |
+ Rounds towards Infinity |
+
+
+ | ROUND_FLOOR |
+ 3 |
+ Rounds towards -Infinity |
+
+
+ | ROUND_HALF_UP |
+ 4 |
+
+ Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero
+ |
+
+
+ | ROUND_HALF_DOWN |
+ 5 |
+
+ Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero
+ |
+
+
+ | ROUND_HALF_EVEN |
+ 6 |
+
+ Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour
+ |
+
+
+ | ROUND_HALF_CEIL |
+ 7 |
+
+ Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity
+ |
+
+
+ | ROUND_HALF_FLOOR |
+ 8 |
+
+ Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity
+ |
+
+
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 }) // equivalent
+
+
DEBUG
+
undefined|false|true
+
+ If BigNumber.DEBUG is set true then an error will be thrown
+ if this BigNumber constructor receives an invalid value, such as
+ a value of type number with more than 15 significant digits.
+ See BigNumber.
+
+
+ An error will also be thrown if the isBigNumber
+ method receives a BigNumber that is not well-formed.
+ See isBigNumber.
+
+
BigNumber.DEBUG = true
+
+
+
INSTANCE
+
+
+
Methods
+
The methods inherited by a BigNumber instance from its constructor's prototype object.
+
A BigNumber is immutable in the sense that it is not changed by its methods.
+
+ The treatment of ±0, ±Infinity and NaN is
+ consistent with how JavaScript treats these values.
+
+
Many method names have a shorter alias.
+
+
+
+
absoluteValue.abs() ⇒ BigNumber
+
+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of
+ this BigNumber.
+
+
The return value is always exact and unrounded.
+
+x = new BigNumber(-0.8)
+y = x.absoluteValue() // '0.8'
+z = y.abs() // '0.8'
+
+
+
+
+ comparedTo.comparedTo(n [, base]) ⇒ number
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ | Returns | |
+
+ 1 |
+ If the value of this BigNumber is greater than the value of n |
+
+
+ -1 |
+ If the value of this BigNumber is less than the value of n |
+
+
+ 0 |
+ If this BigNumber and n have the same value |
+
+
+ null |
+ If the value of either this BigNumber or n is NaN |
+
+
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y) // 1
+x.comparedTo(x.minus(1)) // 0
+y.comparedTo(NaN) // null
+y.comparedTo('110', 2) // -1
+
+
+
+
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number
+
+
+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+
+
+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber
+ rounded by rounding mode rm to a maximum of dp decimal places.
+
+
+ If dp is omitted, or is null or undefined, the return
+ value is the number of decimal places of the value of this BigNumber, or null if
+ the value of this BigNumber is ±Infinity or NaN.
+
+
+ If rm is omitted, or is null or undefined,
+ ROUNDING_MODE is used.
+
+
+ Throws if dp or rm is invalid. See Errors.
+
+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1) // '1234.6'
+x.dp() // 2
+x.decimalPlaces(2) // '1234.56'
+x.dp(10) // '1234.56'
+x.decimalPlaces(0, 1) // '1234'
+x.dp(0, 6) // '1235'
+x.decimalPlaces(1, 1) // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6'
+x // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp() // 102
+
+
+
+
dividedBy.div(n [, base]) ⇒ BigNumber
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the value of this BigNumber divided by
+ n, rounded according to the current
+ DECIMAL_PLACES and
+ ROUNDING_MODE settings.
+
+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y) // '3.14159292035398230088'
+x.div(5) // '71'
+x.div(47, 16) // '5'
+
+
+
+
+ dividedToIntegerBy.idiv(n [, base]) ⇒
+ BigNumber
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by
+ n.
+
+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y) // '1'
+x.idiv(0.7) // '7'
+x.idiv('0.f', 16) // '5'
+
+
+
+
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber
+
+
+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber
+
+
+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by
+ n, i.e. raised to the power n, and optionally modulo a modulus
+ m.
+
+
+ Throws if n is not an integer. See Errors.
+
+
+ If n is negative the result is rounded according to the current
+ DECIMAL_PLACES and
+ ROUNDING_MODE settings.
+
+
+ As the number of digits of the result of the power operation can grow so large so quickly,
+ e.g. 123.45610000 has over 50000 digits, the number of significant
+ digits calculated is limited to the value of the
+ POW_PRECISION setting (unless a modulus
+ m is specified).
+
+
+ By default POW_PRECISION is set to 0.
+ This means that an unlimited number of significant digits will be calculated, and that the
+ method's performance will decrease dramatically for larger exponents.
+
+
+ If m is specified and the value of m, n and this
+ BigNumber are integers, and n is positive, then a fast modular exponentiation
+ algorithm is used, otherwise the operation will be performed as
+ x.exponentiatedBy(n).modulo(m) with a
+ POW_PRECISION of 0.
+
+
+Math.pow(0.7, 2) // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2) // '0.49'
+BigNumber(3).pow(-2) // '0.11111111111111111111'
+
+
+
+
+ integerValue.integerValue([rm]) ⇒ BigNumber
+
+
+ rm: number: integer, 0 to 8 inclusive
+
+
+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using
+ rounding mode rm.
+
+
+ If rm is omitted, or is null or undefined,
+ ROUNDING_MODE is used.
+
+
+ Throws if rm is invalid. See Errors.
+
+
+x = new BigNumber(123.456)
+x.integerValue() // '123'
+x.integerValue(BigNumber.ROUND_CEIL) // '124'
+y = new BigNumber(-12.7)
+y.integerValue() // '-13'
+y.integerValue(BigNumber.ROUND_DOWN) // '-12'
+
+ The following is an example of how to add a prototype method that emulates JavaScript's
+ Math.round function. Math.ceil, Math.floor and
+ Math.trunc can be emulated in the same way with
+ BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and
+ BigNumber.ROUND_DOWN respectively.
+
+
+BigNumber.prototype.round = function (n) {
+ return n.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round() // '123'
+
+
+
+
isEqualTo.eq(n [, base]) ⇒ boolean
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns true if the value of this BigNumber is equal to the value of
+ n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN.
+
+
Note: This method uses the comparedTo method internally.
+
+0 === 1e-324 // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324') // false
+BigNumber(-0).eq(x) // true ( -0 === 0 )
+BigNumber(255).eq('ff', 16) // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN) // false
+
+
+
+
isFinite.isFinite() ⇒ boolean
+
+ Returns true if the value of this BigNumber is a finite number, otherwise
+ returns false.
+
+
+ The only possible non-finite values of a BigNumber are NaN, Infinity
+ and -Infinity.
+
+
+x = new BigNumber(1)
+x.isFinite() // true
+y = new BigNumber(Infinity)
+y.isFinite() // false
+
+ Note: The native method isFinite() can be used if
+ n <= Number.MAX_VALUE.
+
+
+
+
+
isGreaterThan.gt(n [, base]) ⇒ boolean
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns true if the value of this BigNumber is greater than the value of
+ n, otherwise returns false.
+
+
Note: This method uses the comparedTo method internally.
+
+0.1 > (0.3 - 0.2) // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false
+BigNumber(0).gt(x) // false
+BigNumber(11, 3).gt(11.1, 2) // true
+
+
+
+
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns true if the value of this BigNumber is greater than or equal to the value
+ of n, otherwise returns false.
+
+
Note: This method uses the comparedTo method internally.
+
+(0.3 - 0.2) >= 0.1 // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1) // true
+BigNumber(1).gte(x) // true
+BigNumber(10, 18).gte('i', 36) // true
+
+
+
+
isInteger.isInteger() ⇒ boolean
+
+ Returns true if the value of this BigNumber is an integer, otherwise returns
+ false.
+
+
+x = new BigNumber(1)
+x.isInteger() // true
+y = new BigNumber(123.456)
+y.isInteger() // false
+
+
+
+
isLessThan.lt(n [, base]) ⇒ boolean
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns true if the value of this BigNumber is less than the value of
+ n, otherwise returns false.
+
+
Note: This method uses the comparedTo method internally.
+
+(0.3 - 0.2) < 0.1 // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1) // false
+BigNumber(0).lt(x) // true
+BigNumber(11.1, 2).lt(11, 3) // true
+
+
+
+
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns true if the value of this BigNumber is less than or equal to the value of
+ n, otherwise returns false.
+
+
Note: This method uses the comparedTo method internally.
+
+0.1 <= (0.3 - 0.2) // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true
+BigNumber(-1).lte(x) // true
+BigNumber(10, 18).lte('i', 36) // true
+
+
+
+
isNaN.isNaN() ⇒ boolean
+
+ Returns true if the value of this BigNumber is NaN, otherwise
+ returns false.
+
+
+x = new BigNumber(NaN)
+x.isNaN() // true
+y = new BigNumber('Infinity')
+y.isNaN() // false
+
Note: The native method isNaN() can also be used.
+
+
+
+
isNegative.isNegative() ⇒ boolean
+
+ Returns true if the sign of this BigNumber is negative, otherwise returns
+ false.
+
+
+x = new BigNumber(-0)
+x.isNegative() // true
+y = new BigNumber(2)
+y.isNegative() // false
+
Note: n < 0 can be used if n <= -Number.MIN_VALUE.
+
+
+
+
isPositive.isPositive() ⇒ boolean
+
+ Returns true if the sign of this BigNumber is positive, otherwise returns
+ false.
+
+
+x = new BigNumber(-0)
+x.isPositive() // false
+y = new BigNumber(2)
+y.isPositive() // true
+
+
+
+
isZero.isZero() ⇒ boolean
+
+ Returns true if the value of this BigNumber is zero or minus zero, otherwise
+ returns false.
+
+
+x = new BigNumber(-0)
+x.isZero() && x.isNegative() // true
+y = new BigNumber(Infinity)
+y.isZero() // false
+
Note: n == 0 can be used if n >= Number.MIN_VALUE.
+
+
+
+
+ minus.minus(n [, base]) ⇒ BigNumber
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
Returns a BigNumber whose value is the value of this BigNumber minus n.
+
The return value is always exact and unrounded.
+
+0.3 - 0.1 // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1) // '0.2'
+x.minus(0.6, 20) // '0'
+
+
+
+
modulo.mod(n [, base]) ⇒ BigNumber
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e.
+ the integer remainder of dividing this BigNumber by n.
+
+
+ The value returned, and in particular its sign, is dependent on the value of the
+ MODULO_MODE setting of this BigNumber constructor.
+ If it is 1 (default value), the result will have the same sign as this BigNumber,
+ and it will match that of Javascript's % operator (within the limits of double
+ precision) and BigDecimal's remainder method.
+
+
The return value is always exact and unrounded.
+
+ See MODULO_MODE for a description of the other
+ modulo modes.
+
+
+1 % 0.9 // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9) // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33) // '3'
+
+
+
+
+ multipliedBy.times(n [, base]) ⇒ BigNumber
+
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n.
+
+
The return value is always exact and unrounded.
+
+0.6 * 3 // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3) // '1.8'
+BigNumber('7e+500').times(y) // '1.26e+501'
+x.multipliedBy('-a', 16) // '-6'
+
+
+
+
negated.negated() ⇒ BigNumber
+
+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by
+ -1.
+
+
+x = new BigNumber(1.8)
+x.negated() // '-1.8'
+y = new BigNumber(-1.3)
+y.negated() // '1.3'
+
+
+
+
plus.plus(n [, base]) ⇒ BigNumber
+
+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details.
+
+
Returns a BigNumber whose value is the value of this BigNumber plus n.
+
The return value is always exact and unrounded.
+
+0.1 + 0.2 // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2) // '0.3'
+BigNumber(0.7).plus(x).plus(y) // '1'
+x.plus('0.1', 8) // '0.225'
+
+
+
+
+ precision.sd([d [, rm]]) ⇒ BigNumber|number
+
+
+ d: number|boolean: integer, 1 to 1e+9
+ inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive.
+
+
+ If d is a number, returns a BigNumber whose value is the value of this BigNumber
+ rounded to a precision of d significant digits using rounding mode
+ rm.
+
+
+ If d is omitted or is null or undefined, the return
+ value is the number of significant digits of the value of this BigNumber, or null
+ if the value of this BigNumber is ±Infinity or NaN.
+
+
+ If d is true then any trailing zeros of the integer
+ part of a number are counted as significant digits, otherwise they are not.
+
+
+ If rm is omitted or is null or undefined,
+ ROUNDING_MODE will be used.
+
+
+ Throws if d or rm is invalid. See Errors.
+
+
+x = new BigNumber(9876.54321)
+x.precision(6) // '9876.54'
+x.sd() // 9
+x.precision(6, BigNumber.ROUND_UP) // '9876.55'
+x.sd(2) // '9900'
+x.precision(2, 1) // '9800'
+x // '9876.54321'
+y = new BigNumber(987000)
+y.precision() // 3
+y.sd(true) // 6
+
+
+
+
shiftedBy.shiftedBy(n) ⇒ BigNumber
+
+ n: number: integer,
+ -9007199254740991 to 9007199254740991 inclusive
+
+
+ Returns a BigNumber whose value is the value of this BigNumber shifted by n
+ places.
+
+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n
+ is negative or to the right if n is positive.
+
+
The return value is always exact and unrounded.
+
+ Throws if n is invalid. See Errors.
+
+
+x = new BigNumber(1.23)
+x.shiftedBy(3) // '1230'
+x.shiftedBy(-3) // '0.00123'
+
+
+
+
squareRoot.sqrt() ⇒ BigNumber
+
+ Returns a BigNumber whose value is the square root of the value of this BigNumber,
+ rounded according to the current
+ DECIMAL_PLACES and
+ ROUNDING_MODE settings.
+
+
+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated
+ to an infinite number of correct digits before rounding.
+
+
+x = new BigNumber(16)
+x.squareRoot() // '4'
+y = new BigNumber(3)
+y.sqrt() // '1.73205080756887729353'
+
+
+
+
+ toExponential.toExponential([dp [, rm]]) ⇒ string
+
+
+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+
+
+ Returns a string representing the value of this BigNumber in exponential notation rounded
+ using rounding mode rm to dp decimal places, i.e with one digit
+ before the decimal point and dp digits after it.
+
+
+ If the value of this BigNumber in exponential notation has fewer than dp fraction
+ digits, the return value will be appended with zeros accordingly.
+
+
+ If dp is omitted, or is null or undefined, the number
+ of digits after the decimal point defaults to the minimum number of digits necessary to
+ represent the value exactly.
+ If rm is omitted or is null or undefined,
+ ROUNDING_MODE is used.
+
+
+ Throws if dp or rm is invalid. See Errors.
+
+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential() // '4.56e+1'
+y.toExponential() // '4.56e+1'
+x.toExponential(0) // '5e+1'
+y.toExponential(0) // '5e+1'
+x.toExponential(1) // '4.6e+1'
+y.toExponential(1) // '4.6e+1'
+y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN)
+x.toExponential(3) // '4.560e+1'
+y.toExponential(3) // '4.560e+1'
+
+
+
+
+ toFixed.toFixed([dp [, rm]]) ⇒ string
+
+
+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+
+
+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation
+ rounded to dp decimal places using rounding mode rm.
+
+
+ If the value of this BigNumber in normal notation has fewer than dp fraction
+ digits, the return value will be appended with zeros accordingly.
+
+
+ Unlike Number.prototype.toFixed, which returns exponential notation if a number
+ is greater or equal to 1021, this method will always return normal
+ notation.
+
+
+ If dp is omitted or is null or undefined, the return
+ value will be unrounded and in normal notation. This is also unlike
+ Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current
+ EXPONENTIAL_AT setting causes
+ toString to return exponential notation.
+ If rm is omitted or is null or undefined,
+ ROUNDING_MODE is used.
+
+
+ Throws if dp or rm is invalid. See Errors.
+
+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed() // '3'
+y.toFixed() // '3.456'
+y.toFixed(0) // '3'
+x.toFixed(2) // '3.46'
+y.toFixed(2) // '3.46'
+y.toFixed(2, 1) // '3.45' (ROUND_DOWN)
+x.toFixed(5) // '3.45600'
+y.toFixed(5) // '3.45600'
+
+
+
+
+ toFormat.toFormat([dp [, rm[, format]]]) ⇒ string
+
+
+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+ format: object: see FORMAT
+
+
+
+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation
+ rounded to dp decimal places using rounding mode rm, and formatted
+ according to the properties of the format object.
+
+
+ See FORMAT and the examples below for the properties of the
+ format object, their types, and their usage. A formatting object may contain
+ some or all of the recognised properties.
+
+
+ If dp is omitted or is null or undefined, then the
+ return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined,
+ ROUNDING_MODE is used.
+ If format is omitted or is null or undefined, the
+ FORMAT object is used.
+
+
+ Throws if dp, rm or format is invalid. See
+ Errors.
+
+
+fmt = {
+ prefix = '',
+ decimalSeparator: '.',
+ groupSeparator: ',',
+ groupSize: 3,
+ secondaryGroupSize: 0,
+ fractionGroupSeparator: ' ',
+ fractionGroupSize: 0,
+ suffix = ''
+}
+
+x = new BigNumber('123456789.123456789')
+
+// Set the global formatting options
+BigNumber.config({ FORMAT: fmt })
+
+x.toFormat() // '123,456,789.123456789'
+x.toFormat(3) // '123,456,789.123'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+fmt.groupSeparator = ' '
+fmt.fractionGroupSize = 5
+x.toFormat() // '123 456 789.12345 6789'
+
+// Alternatively, pass the formatting options as an argument
+fmt = {
+ prefix: '=> ',
+ decimalSeparator: ',',
+ groupSeparator: '.',
+ groupSize: 3,
+ secondaryGroupSize: 2
+}
+
+x.toFormat() // '123 456 789.12345 6789'
+x.toFormat(fmt) // '=> 12.34.56.789,123456789'
+x.toFormat(2, fmt) // '=> 12.34.56.789,12'
+x.toFormat(3, BigNumber.ROUND_UP, fmt) // '=> 12.34.56.789,124'
+
+
+
+
+ toFraction.toFraction([maximum_denominator])
+ ⇒ [BigNumber, BigNumber]
+
+
+ maximum_denominator:
+ number|string|BigNumber: integer >= 1 and <=
+ Infinity
+
+
+ Returns an array of two BigNumbers representing the value of this BigNumber as a simple
+ fraction with an integer numerator and an integer denominator. The denominator will be a
+ positive non-zero value less than or equal to maximum_denominator.
+
+
+ If a maximum_denominator is not specified, or is null or
+ undefined, the denominator will be the lowest value necessary to represent the
+ number exactly.
+
+
+ Throws if maximum_denominator is invalid. See Errors.
+
+
+x = new BigNumber(1.75)
+x.toFraction() // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction() // '157079632679,50000000000'
+pi.toFraction(100000) // '312689, 99532'
+pi.toFraction(10000) // '355, 113'
+pi.toFraction(100) // '311, 99'
+pi.toFraction(10) // '22, 7'
+pi.toFraction(1) // '3, 1'
+
+
+
+
toJSON.toJSON() ⇒ string
+
As valueOf.
+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+ return key === '' ? val : new BigNumber(val)
+})
+
+
+
+
toNumber.toNumber() ⇒ number
+
Returns the value of this BigNumber as a JavaScript number primitive.
+
+ This method is identical to using type coercion with the unary plus operator.
+
+
+x = new BigNumber(456.789)
+x.toNumber() // 456.789
++x // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber() // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber() // -Infinity
+1 / +z // -Infinity
+
+
+
+
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string
+
+
+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive
+
+
+ Returns a string representing the value of this BigNumber rounded to sd
+ significant digits using rounding mode rm.
+
+
+ If sd is less than the number of digits necessary to represent the integer part
+ of the value in normal (fixed-point) notation, then exponential notation is used.
+
+
+ If sd is omitted, or is null or undefined, then the
+ return value is the same as n.toString().
+ If rm is omitted or is null or undefined,
+ ROUNDING_MODE is used.
+
+
+ Throws if sd or rm is invalid. See Errors.
+
+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision() // '45.6'
+y.toPrecision() // '45.6'
+x.toPrecision(1) // '5e+1'
+y.toPrecision(1) // '5e+1'
+y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP)
+y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN)
+x.toPrecision(5) // '45.600'
+y.toPrecision(5) // '45.600'
+
+
+
+
toString.toString([base]) ⇒ string
+
+ base: number: integer, 2 to ALPHABET.length
+ inclusive (see ALPHABET).
+
+
+ Returns a string representing the value of this BigNumber in the specified base, or base
+ 10 if base is omitted or is null or
+ undefined.
+
+
+ For bases above 10, and using the default base conversion alphabet
+ (see ALPHABET), values from 10 to
+ 35 are represented by a-z
+ (as with Number.prototype.toString).
+
+
+ If a base is specified the value is rounded according to the current
+ DECIMAL_PLACES
+ and ROUNDING_MODE settings.
+
+
+ If a base is not specified, and this BigNumber has a positive
+ exponent that is equal to or greater than the positive component of the
+ current EXPONENTIAL_AT setting,
+ or a negative exponent equal to or less than the negative component of the
+ setting, then exponential notation is returned.
+
+
If base is null or undefined it is ignored.
+
+ Throws if base is invalid. See Errors.
+
+
+x = new BigNumber(750000)
+x.toString() // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString() // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2) // '101101010.111'
+y.toString(9) // '442.77777777777777777778'
+y.toString(32) // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString() // '1.23456789'
+z.toString(10) // '1.2346'
+
+
+
+
valueOf.valueOf() ⇒ string
+
+ As toString, but does not accept a base argument and includes
+ the minus sign for negative zero.
+
+
+x = new BigNumber('-0')
+x.toString() // '0'
+x.valueOf() // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf() // '1.777e+457'
+
+
+
+
Properties
+
The properties of a BigNumber instance:
+
+
+ | Property |
+ Description |
+ Type |
+ Value |
+
+
+ | c |
+ coefficient* |
+ number[] |
+ Array of base 1e14 numbers |
+
+
+ | e |
+ exponent |
+ number |
+ Integer, -1000000000 to 1000000000 inclusive |
+
+
+ | s |
+ sign |
+ number |
+ -1 or 1 |
+
+
+
*significand
+
+ The value of any of the c, e and s properties may also
+ be null.
+
+
+ The above properties are best considered to be read-only. In early versions of this library it
+ was okay to change the exponent of a BigNumber by writing to its exponent property directly,
+ but this is no longer reliable as the value of the first element of the coefficient array is
+ now dependent on the exponent.
+
+
+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are
+ not necessarily preserved.
+
+
x = new BigNumber(0.123) // '0.123'
+x.toExponential() // '1.23e-1'
+x.c // '1,2,3'
+x.e // -1
+x.s // 1
+
+y = new Number(-123.4567000e+2) // '-12345.67'
+y.toExponential() // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2') // '-12345.67'
+z.toExponential() // '-1.234567e+4'
+z.c // '1,2,3,4,5,6,7'
+z.e // 4
+z.s // -1
+
+
+
+
Zero, NaN and Infinity
+
+ The table below shows how ±0, NaN and
+ ±Infinity are stored.
+
+
+
+ | |
+ c |
+ e |
+ s |
+
+
+ | ±0 |
+ [0] |
+ 0 |
+ ±1 |
+
+
+ | NaN |
+ null |
+ null |
+ null |
+
+
+ | ±Infinity |
+ null |
+ null |
+ ±1 |
+
+
+
+x = new Number(-0) // 0
+1 / x == -Infinity // true
+
+y = new BigNumber(-0) // '0'
+y.c // '0' ( [0].toString() )
+y.e // 0
+y.s // -1
+
+
+
+
Errors
+
The table below shows the errors that are thrown.
+
+ The errors are generic Error objects whose message begins
+ '[BigNumber Error]'.
+
+
+
+ | Method |
+ Throws |
+
+
+
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy
+ |
+ Base not a primitive number |
+
+
+ | Base not an integer |
+
+
+ | Base out of range |
+
+
+ | Number primitive has more than 15 significant digits* |
+
+
+ | Not a base... number* |
+
+
+ | Not a number* |
+
+
+ clone |
+ Object expected |
+
+
+ config |
+ Object expected |
+
+
+ DECIMAL_PLACES not a primitive number |
+
+
+ DECIMAL_PLACES not an integer |
+
+
+ DECIMAL_PLACES out of range |
+
+
+ ROUNDING_MODE not a primitive number |
+
+
+ ROUNDING_MODE not an integer |
+
+
+ ROUNDING_MODE out of range |
+
+
+ EXPONENTIAL_AT not a primitive number |
+
+
+ EXPONENTIAL_AT not an integer |
+
+
+ EXPONENTIAL_AT out of range |
+
+
+ RANGE not a primitive number |
+
+
+ RANGE not an integer |
+
+
+ RANGE cannot be zero |
+
+
+ RANGE cannot be zero |
+
+
+ CRYPTO not true or false |
+
+
+ crypto unavailable |
+
+
+ MODULO_MODE not a primitive number |
+
+
+ MODULO_MODE not an integer |
+
+
+ MODULO_MODE out of range |
+
+
+ POW_PRECISION not a primitive number |
+
+
+ POW_PRECISION not an integer |
+
+
+ POW_PRECISION out of range |
+
+
+ FORMAT not an object |
+
+
+ ALPHABET invalid |
+
+
+
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision
+ |
+ Argument not a primitive number |
+
+
+ | Argument not an integer |
+
+
+ | Argument out of range |
+
+
+
+ decimalPlaces
+ precision
+ |
+ Argument not true or false |
+
+
+ exponentiatedBy |
+ Argument not an integer |
+
+
+ isBigNumber |
+ Invalid BigNumber* |
+
+
+
+ minimum
+ maximum
+ |
+ Not a number* |
+
+
+
+ random
+ |
+ crypto unavailable |
+
+
+
+ toFormat
+ |
+ Argument not an object |
+
+
+ toFraction |
+ Argument not an integer |
+
+
+ | Argument out of range |
+
+
+ toString |
+ Base not a primitive number |
+
+
+ | Base not an integer |
+
+
+ | Base out of range |
+
+
+
*Only thrown if BigNumber.DEBUG is true.
+
To determine if an exception is a BigNumber Error:
+
+try {
+ // ...
+} catch (e) {
+ if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+ // ...
+ }
+}
+
+
+
+
Type coercion
+
+ To prevent the accidental use of a BigNumber in primitive number operations, or the
+ accidental addition of a BigNumber to a string, the valueOf method can be safely
+ overwritten as shown below.
+
+
+ The valueOf method is the same as the
+ toJSON method, and both are the same as the
+ toString method except they do not take a base
+ argument and they include the minus sign for negative zero.
+
+
+BigNumber.prototype.valueOf = function () {
+ throw Error('valueOf called!')
+}
+
+x = new BigNumber(1)
+x / 2 // '[BigNumber Error] valueOf called!'
+x + 'abc' // '[BigNumber Error] valueOf called!'
+
+
+
+
+
FAQ
+
+
Why are trailing fractional zeros removed from BigNumbers?
+
+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the
+ precision of a value. This can be useful but the results of arithmetic operations can be
+ misleading.
+
+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y) // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y) // 4.1400000
+
+ To specify the precision of a value is to specify that the value lies
+ within a certain range.
+
+
+ In the first example, x has a value of 1.0. The trailing zero shows
+ the precision of the value, implying that it is in the range 0.95 to
+ 1.05. Similarly, the precision indicated by the trailing zeros of y
+ indicates that the value is in the range 1.09995 to 1.10005.
+
+
+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995,
+ and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the
+ range of the result of the addition implied by the precision of its operands is
+ 2.04995 to 2.15005.
+
+
+ The result given by BigDecimal of 2.1000 however, indicates that the value is in
+ the range 2.09995 to 2.10005 and therefore the precision implied by
+ its trailing zeros may be misleading.
+
+
+ In the second example, the true range is 4.122744 to 4.157256 yet
+ the BigDecimal answer of 4.1400000 indicates a range of 4.13999995
+ to 4.14000005. Again, the precision implied by the trailing zeros may be
+ misleading.
+
+
+ This library, like binary floating point and most calculators, does not retain trailing
+ fractional zeros. Instead, the toExponential, toFixed and
+ toPrecision methods enable trailing zeros to be added if and when required.
+
+
+
+
+
diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json
index 475a813..885136c 100644
--- a/node_modules/bignumber.js/package.json
+++ b/node_modules/bignumber.js/package.json
@@ -1,40 +1,40 @@
-{
- "name": "bignumber.js",
- "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
- "version": "9.0.0",
- "keywords": [
- "arbitrary",
- "precision",
- "arithmetic",
- "big",
- "number",
- "decimal",
- "float",
- "biginteger",
- "bigdecimal",
- "bignumber",
- "bigint",
- "bignum"
- ],
- "repository": {
- "type": "git",
- "url": "https://github.com/MikeMcl/bignumber.js.git"
- },
- "main": "bignumber",
- "module": "bignumber.mjs",
- "browser": "bignumber.js",
- "types": "bignumber.d.ts",
- "author": {
- "name": "Michael Mclaughlin",
- "email": "M8ch88l@gmail.com"
- },
- "engines": {
- "node": "*"
- },
- "license": "MIT",
- "scripts": {
- "test": "node test/test",
- "build": "uglifyjs bignumber.js --source-map -c -m -o bignumber.min.js"
- },
- "dependencies": {}
-}
+{
+ "name": "bignumber.js",
+ "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
+ "version": "9.0.0",
+ "keywords": [
+ "arbitrary",
+ "precision",
+ "arithmetic",
+ "big",
+ "number",
+ "decimal",
+ "float",
+ "biginteger",
+ "bigdecimal",
+ "bignumber",
+ "bigint",
+ "bignum"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/MikeMcl/bignumber.js.git"
+ },
+ "main": "bignumber",
+ "module": "bignumber.mjs",
+ "browser": "bignumber.js",
+ "types": "bignumber.d.ts",
+ "author": {
+ "name": "Michael Mclaughlin",
+ "email": "M8ch88l@gmail.com"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "license": "MIT",
+ "scripts": {
+ "test": "node test/test",
+ "build": "uglifyjs bignumber.js --source-map -c -m -o bignumber.min.js"
+ },
+ "dependencies": {}
+}
diff --git a/node_modules/concat-stream/package.json b/node_modules/concat-stream/package.json
index f709022..3797828 100644
--- a/node_modules/concat-stream/package.json
+++ b/node_modules/concat-stream/package.json
@@ -1,6 +1,6 @@
{
"name": "concat-stream",
- "version": "1.6.2",
+ "version": "2.0.0",
"description": "writable stream that concatenates strings or binary data and calls a callback with the result",
"tags": [
"stream",
@@ -17,7 +17,7 @@
"url": "http://github.com/maxogden/concat-stream/issues"
},
"engines": [
- "node >= 0.8"
+ "node >= 6.0"
],
"main": "index.js",
"files": [
@@ -30,7 +30,7 @@
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
- "readable-stream": "^2.2.2",
+ "readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
},
"devDependencies": {
diff --git a/node_modules/multer/README.md b/node_modules/multer/README.md
index 499f6e8..1e062ee 100644
--- a/node_modules/multer/README.md
+++ b/node_modules/multer/README.md
@@ -1,25 +1,30 @@
-# Multer [](https://github.com/expressjs/multer/actions/workflows/ci.yml) [](https://coveralls.io/r/expressjs/multer?branch=master) [](https://badge.fury.io/js/multer) [](https://github.com/feross/standard)
+# Multer [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][test-image]][test-url] [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer]
Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written
on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency.
**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`).
-## Translations
+## Translations
This README is also available in other languages:
-- [Español](https://github.com/expressjs/multer/blob/master/doc/README-es.md) (Spanish)
-- [简体中文](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) (Chinese)
-- [한국어](https://github.com/expressjs/multer/blob/master/doc/README-ko.md) (Korean)
-- [Русский язык](https://github.com/expressjs/multer/blob/master/doc/README-ru.md) (Russian)
-- [Việt Nam](https://github.com/expressjs/multer/blob/master/doc/README-vi.md) (Vietnam)
-- [Português](https://github.com/expressjs/multer/blob/master/doc/README-pt-br.md) (Portuguese Brazil)
+| | |
+| ------------------------------------------------------------------------------ | --------------- |
+| [العربية](https://github.com/expressjs/multer/blob/main/doc/README-ar.md) | Arabic |
+| [简体中文](https://github.com/expressjs/multer/blob/main/doc/README-zh-cn.md) | Chinese |
+| [Français](https://github.com/expressjs/multer/blob/main/doc/README-fr.md) | French |
+| [한국어](https://github.com/expressjs/multer/blob/main/doc/README-ko.md) | Korean |
+| [Português](https://github.com/expressjs/multer/blob/main/doc/README-pt-br.md) | Portuguese (BR) |
+| [Русский язык](https://github.com/expressjs/multer/blob/main/doc/README-ru.md) | Russian |
+| [Español](https://github.com/expressjs/multer/blob/main/doc/README-es.md) | Spanish |
+| [O'zbek tili](https://github.com/expressjs/multer/blob/main/doc/README-uz.md) | Uzbek |
+| [Việt Nam](https://github.com/expressjs/multer/blob/main/doc/README-vi.md) | Vietnamese |
## Installation
```sh
-$ npm install --save multer
+$ npm install multer
```
## Usage
@@ -53,8 +58,8 @@ app.post('/photos/upload', upload.array('photos', 12), function (req, res, next)
// req.body will contain the text fields, if there were any
})
-const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
-app.post('/cool-profile', cpUpload, function (req, res, next) {
+const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
+app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
@@ -78,14 +83,14 @@ app.post('/profile', upload.none(), function (req, res, next) {
})
```
-Here's an example on how multer is used an HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields:
+Here's an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields:
```html
```
@@ -96,9 +101,9 @@ Then in your javascript file you would add these lines to access both the file a
const multer = require('multer')
const upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
- // req.file is the name of your file in the form above, here 'uploaded_file'
- // req.body will hold the text fields, if there were any
- console.log(req.file, req.body)
+ // req.file is the name of your file in the form above, here 'uploaded_file'
+ // req.body will hold the text fields, if there were any
+ console.log(req.file, req.body)
});
```
@@ -229,7 +234,7 @@ If no `filename` is given, each file will be given a random name that doesn't
include any file extension.
**Note:** Multer will not append any file extension for you, your function
-should return a filename complete with an file extension.
+should return a filename complete with a file extension.
Each function gets passed both the request (`req`) and some information about
the file (`file`) to aid with the decision.
@@ -239,7 +244,7 @@ order that the client transmits fields and files to the server.
For understanding the calling convention used in the callback (needing to pass
null as the first param), refer to
-[Node.js error handling](https://www.joyent.com/node-js/production/design/errors)
+[Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors)
#### `MemoryStorage`
@@ -305,7 +310,7 @@ When encountering an error, Multer will delegate the error to Express. You can
display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).
If you want to catch errors specifically from Multer, you can call the
-middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/master/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
+middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
```javascript
const multer = require('multer')
@@ -326,8 +331,18 @@ app.post('/profile', function (req, res) {
## Custom storage engine
-For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/master/StorageEngine.md).
+For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md).
## License
[MIT](LICENSE)
+
+[ci-image]: https://github.com/expressjs/multer/actions/workflows/ci.yml/badge.svg
+[ci-url]: https://github.com/expressjs/multer/actions/workflows/ci.yml
+[test-url]: https://coveralls.io/r/expressjs/multer?branch=main
+[test-image]: https://badgen.net/coveralls/c/github/expressjs/multer/main
+[npm-downloads-image]: https://badgen.net/npm/dm/multer
+[npm-url]: https://npmjs.org/package/multer
+[npm-version-image]: https://badgen.net/npm/v/multer
+[ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/multer/badge
+[ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/multer
\ No newline at end of file
diff --git a/node_modules/multer/lib/make-middleware.js b/node_modules/multer/lib/make-middleware.js
index 81a90cf..09b2160 100644
--- a/node_modules/multer/lib/make-middleware.js
+++ b/node_modules/multer/lib/make-middleware.js
@@ -101,6 +101,8 @@ function makeMiddleware (setup) {
// handle files
busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) {
+ if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
+
// don't attach to the files object, if there is no file
if (!filename) return fileStream.resume()
diff --git a/node_modules/multer/package.json b/node_modules/multer/package.json
index 862aec4..a5d3ac7 100644
--- a/node_modules/multer/package.json
+++ b/node_modules/multer/package.json
@@ -1,7 +1,7 @@
{
"name": "multer",
"description": "Middleware for handling `multipart/form-data`.",
- "version": "2.0.0",
+ "version": "2.0.1",
"contributors": [
"Hage Yaapa (http://www.hacksparrow.com)",
"Jaret Pfluger ",
@@ -20,19 +20,20 @@
],
"dependencies": {
"append-field": "^1.0.0",
- "busboy": "^1.0.0",
- "concat-stream": "^1.5.2",
- "mkdirp": "^0.5.4",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "mkdirp": "^0.5.6",
"object-assign": "^4.1.1",
- "type-is": "^1.6.4",
- "xtend": "^4.0.0"
+ "type-is": "^1.6.18",
+ "xtend": "^4.0.2"
},
"devDependencies": {
"deep-equal": "^2.0.3",
- "express": "^4.13.1",
- "form-data": "^1.0.0-rc1",
- "fs-temp": "^1.1.2",
- "mocha": "^11.3.0",
+ "express": "^4.21.2",
+ "form-data": "^4.0.2",
+ "fs-temp": "^1.2.1",
+ "mocha": "^11.5.0",
+ "nyc": "^15.1.0",
"rimraf": "^2.4.1",
"standard": "^14.3.3",
"testdata-w3c-json-form": "^1.0.0"
diff --git a/node_modules/nodemon/bin/windows-kill.exe b/node_modules/nodemon/bin/windows-kill.exe
old mode 100644
new mode 100755
diff --git a/node_modules/readable-stream/.travis.yml b/node_modules/readable-stream/.travis.yml
deleted file mode 100644
index f62cdac..0000000
--- a/node_modules/readable-stream/.travis.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-sudo: false
-language: node_js
-before_install:
- - (test $NPM_LEGACY && npm install -g npm@2 && npm install -g npm@3) || true
-notifications:
- email: false
-matrix:
- fast_finish: true
- include:
- - node_js: '0.8'
- env: NPM_LEGACY=true
- - node_js: '0.10'
- env: NPM_LEGACY=true
- - node_js: '0.11'
- env: NPM_LEGACY=true
- - node_js: '0.12'
- env: NPM_LEGACY=true
- - node_js: 1
- env: NPM_LEGACY=true
- - node_js: 2
- env: NPM_LEGACY=true
- - node_js: 3
- env: NPM_LEGACY=true
- - node_js: 4
- - node_js: 5
- - node_js: 6
- - node_js: 7
- - node_js: 8
- - node_js: 9
-script: "npm run test"
-env:
- global:
- - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc=
- - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI=
diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md
index f1c5a93..19117c1 100644
--- a/node_modules/readable-stream/README.md
+++ b/node_modules/readable-stream/README.md
@@ -1,30 +1,81 @@
# readable-stream
-***Node-core v8.17.0 streams for userland*** [](https://travis-ci.org/nodejs/readable-stream)
+***Node.js core streams for userland*** [](https://travis-ci.com/nodejs/readable-stream)
[](https://nodei.co/npm/readable-stream/)
[](https://nodei.co/npm/readable-stream/)
-[](https://saucelabs.com/u/readable-stream)
+[](https://saucelabs.com/u/readabe-stream)
```bash
npm install --save readable-stream
```
-***Node-core streams for userland***
+This package is a mirror of the streams implementations in Node.js.
-This package is a mirror of the Streams2 and Streams3 implementations in
-Node-core.
-
-Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.17.0/docs/api/stream.html).
+Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html).
If you want to guarantee a stable streams base, regardless of what version of
Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
As of version 2.0.0 **readable-stream** uses semantic versioning.
+## Version 3.x.x
+
+v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows:
+
+1. Error codes: https://github.com/nodejs/node/pull/13310,
+ https://github.com/nodejs/node/pull/13291,
+ https://github.com/nodejs/node/pull/16589,
+ https://github.com/nodejs/node/pull/15042,
+ https://github.com/nodejs/node/pull/15665,
+ https://github.com/nodejs/readable-stream/pull/344
+2. 'readable' have precedence over flowing
+ https://github.com/nodejs/node/pull/18994
+3. make virtual methods errors consistent
+ https://github.com/nodejs/node/pull/18813
+4. updated streams error handling
+ https://github.com/nodejs/node/pull/18438
+5. writable.end should return this.
+ https://github.com/nodejs/node/pull/18780
+6. readable continues to read when push('')
+ https://github.com/nodejs/node/pull/18211
+7. add custom inspect to BufferList
+ https://github.com/nodejs/node/pull/17907
+8. always defer 'readable' with nextTick
+ https://github.com/nodejs/node/pull/17979
+
+## Version 2.x.x
+v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11.
+
+### Big Thanks
+
+Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
+
+# Usage
+
+You can swap your `require('stream')` with `require('readable-stream')`
+without any changes, if you are just using one of the main classes and
+functions.
+
+```js
+const {
+ Readable,
+ Writable,
+ Transform,
+ Duplex,
+ pipeline,
+ finished
+} = require('readable-stream')
+````
+
+Note that `require('stream')` will return `Stream`, while
+`require('readable-stream')` will return `Readable`. We discourage using
+whatever is exported directly, but rather use one of the properties as
+shown in the example above.
+
# Streams Working Group
`readable-stream` is maintained by the Streams Working Group, which
@@ -44,15 +95,12 @@ Node.js. The responsibilities of the Streams Working Group include:
## Team Members
-* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) <christopher.s.dickinson@gmail.com>
- - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com>
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
-* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) <rod@vagg.org>
- - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
-* **Sam Newman** ([@sonewman](https://github.com/sonewman)) <newmansam@outlook.com>
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com>
-* **Domenic Denicola** ([@domenic](https://github.com/domenic)) <d@domenic.me>
* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com>
- Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com>
+* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com>
+
+[sauce]: https://saucelabs.com
diff --git a/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md
deleted file mode 100644
index 83275f1..0000000
--- a/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# streams WG Meeting 2015-01-30
-
-## Links
-
-* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg
-* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106
-* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/
-
-## Agenda
-
-Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting.
-
-* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105)
-* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101)
-* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102)
-* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99)
-
-## Minutes
-
-### adopt a charter
-
-* group: +1's all around
-
-### What versioning scheme should be adopted?
-* group: +1’s 3.0.0
-* domenic+group: pulling in patches from other sources where appropriate
-* mikeal: version independently, suggesting versions for io.js
-* mikeal+domenic: work with TC to notify in advance of changes
-simpler stream creation
-
-### streamline creation of streams
-* sam: streamline creation of streams
-* domenic: nice simple solution posted
- but, we lose the opportunity to change the model
- may not be backwards incompatible (double check keys)
-
- **action item:** domenic will check
-
-### remove implicit flowing of streams on(‘data’)
-* add isFlowing / isPaused
-* mikeal: worrying that we’re documenting polyfill methods – confuses users
-* domenic: more reflective API is probably good, with warning labels for users
-* new section for mad scientists (reflective stream access)
-* calvin: name the “third state”
-* mikeal: maybe borrow the name from whatwg?
-* domenic: we’re missing the “third state”
-* consensus: kind of difficult to name the third state
-* mikeal: figure out differences in states / compat
-* mathias: always flow on data – eliminates third state
- * explore what it breaks
-
-**action items:**
-* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream)
-* ask rod/build for infrastructure
-* **chris**: explore the “flow on data” approach
-* add isPaused/isFlowing
-* add new docs section
-* move isPaused to that section
-
-
diff --git a/node_modules/readable-stream/duplex-browser.js b/node_modules/readable-stream/duplex-browser.js
deleted file mode 100644
index f8b2db8..0000000
--- a/node_modules/readable-stream/duplex-browser.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./lib/_stream_duplex.js');
diff --git a/node_modules/readable-stream/duplex.js b/node_modules/readable-stream/duplex.js
deleted file mode 100644
index 46924cb..0000000
--- a/node_modules/readable-stream/duplex.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./readable').Duplex
diff --git a/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/readable-stream/lib/_stream_duplex.js
index 57003c3..19abfa6 100644
--- a/node_modules/readable-stream/lib/_stream_duplex.js
+++ b/node_modules/readable-stream/lib/_stream_duplex.js
@@ -26,90 +26,92 @@
'use strict';
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
/**/
var objectKeys = Object.keys || function (obj) {
var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
+ for (var key in obj) keys.push(key);
+ return keys;
};
/**/
module.exports = Duplex;
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
-
-util.inherits(Duplex, Readable);
-
+require('inherits')(Duplex, Readable);
{
- // avoid scope creep, the keys array can then be collected
+ // Allow the keys array to be GC'ed.
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
-
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
-
Readable.call(this, options);
Writable.call(this, options);
-
- if (options && options.readable === false) this.readable = false;
-
- if (options && options.writable === false) this.writable = false;
-
this.allowHalfOpen = true;
- if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
-
- this.once('end', onend);
+ if (options) {
+ if (options.readable === false) this.readable = false;
+ if (options.writable === false) this.writable = false;
+ if (options.allowHalfOpen === false) {
+ this.allowHalfOpen = false;
+ this.once('end', onend);
+ }
+ }
}
-
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
- get: function () {
+ get: function get() {
return this._writableState.highWaterMark;
}
});
+Object.defineProperty(Duplex.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
+Object.defineProperty(Duplex.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+});
// the no-half-open enforcer
function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
+ // If the writable side ended, then we're ok.
+ if (this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
- pna.nextTick(onEndNT, this);
+ process.nextTick(onEndNT, this);
}
-
function onEndNT(self) {
self.end();
}
-
Object.defineProperty(Duplex.prototype, 'destroyed', {
- get: function () {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
- set: function (value) {
+ set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
@@ -121,11 +123,4 @@ Object.defineProperty(Duplex.prototype, 'destroyed', {
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
-});
-
-Duplex.prototype._destroy = function (err, cb) {
- this.push(null);
- this.end();
-
- pna.nextTick(cb, err);
-};
\ No newline at end of file
+});
\ No newline at end of file
diff --git a/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/readable-stream/lib/_stream_passthrough.js
index 612edb4..24a6bdd 100644
--- a/node_modules/readable-stream/lib/_stream_passthrough.js
+++ b/node_modules/readable-stream/lib/_stream_passthrough.js
@@ -26,22 +26,12 @@
'use strict';
module.exports = PassThrough;
-
var Transform = require('./_stream_transform');
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-util.inherits(PassThrough, Transform);
-
+require('inherits')(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
-
Transform.call(this, options);
}
-
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
\ No newline at end of file
diff --git a/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/readable-stream/lib/_stream_readable.js
index 3af95cb..df1f608 100644
--- a/node_modules/readable-stream/lib/_stream_readable.js
+++ b/node_modules/readable-stream/lib/_stream_readable.js
@@ -21,17 +21,8 @@
'use strict';
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
module.exports = Readable;
-/**/
-var isArray = require('isarray');
-/**/
-
/**/
var Duplex;
/**/
@@ -40,8 +31,7 @@ Readable.ReadableState = ReadableState;
/**/
var EE = require('events').EventEmitter;
-
-var EElistenerCount = function (emitter, type) {
+var EElistenerCount = function EElistenerCount(emitter, type) {
return emitter.listeners(type).length;
};
/**/
@@ -50,9 +40,7 @@ var EElistenerCount = function (emitter, type) {
var Stream = require('./internal/streams/stream');
/**/
-/**/
-
-var Buffer = require('safe-buffer').Buffer;
+var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
@@ -61,31 +49,33 @@ function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
-/**/
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
/**/
var debugUtil = require('util');
-var debug = void 0;
+var debug;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
- debug = function () {};
+ debug = function debug() {};
}
/**/
-var BufferList = require('./internal/streams/BufferList');
+var BufferList = require('./internal/streams/buffer_list');
var destroyImpl = require('./internal/streams/destroy');
+var _require = require('./internal/streams/state'),
+ getHighWaterMark = _require.getHighWaterMark;
+var _require$codes = require('../errors').codes,
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
+
+// Lazy loaded to improve the startup performance.
var StringDecoder;
-
-util.inherits(Readable, Stream);
-
+var createReadableStreamAsyncIterator;
+var from;
+require('inherits')(Readable, Stream);
+var errorOrDestroy = destroyImpl.errorOrDestroy;
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
-
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
@@ -95,12 +85,10 @@ function prependListener(emitter, event, fn) {
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
- 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]];
+ if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
-
-function ReadableState(options, stream) {
+function ReadableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
-
options = options || {};
// Duplex streams are both readable and writable, but share
@@ -108,24 +96,16 @@ function ReadableState(options, stream) {
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
-
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
- var hwm = options.highWaterMark;
- var readableHwm = options.readableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
+ this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
@@ -151,6 +131,13 @@ function ReadableState(options, stream) {
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
+ this.paused = true;
+
+ // Should close be emitted on destroy. Defaults to true.
+ this.emitClose = options.emitClose !== false;
+
+ // Should .destroy() be called after 'end' (and potentially 'finish')
+ this.autoDestroy = !!options.autoDestroy;
// has it been destroyed
this.destroyed = false;
@@ -165,7 +152,6 @@ function ReadableState(options, stream) {
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
-
this.decoder = null;
this.encoding = null;
if (options.encoding) {
@@ -174,34 +160,35 @@ function ReadableState(options, stream) {
this.encoding = options.encoding;
}
}
-
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
-
if (!(this instanceof Readable)) return new Readable(options);
- this._readableState = new ReadableState(options, this);
+ // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the ReadableState constructor, at least with V8 6.5
+ var isDuplex = this instanceof Duplex;
+ this._readableState = new ReadableState(options, this, isDuplex);
// legacy
this.readable = true;
-
if (options) {
if (typeof options.read === 'function') this._read = options.read;
-
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
-
Stream.call(this);
}
-
Object.defineProperty(Readable.prototype, 'destroyed', {
- get: function () {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
- set: function (value) {
+ set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
@@ -213,11 +200,9 @@ Object.defineProperty(Readable.prototype, 'destroyed', {
this._readableState.destroyed = value;
}
});
-
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
- this.push(null);
cb(err);
};
@@ -228,7 +213,6 @@ Readable.prototype._destroy = function (err, cb) {
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
-
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
@@ -241,7 +225,6 @@ Readable.prototype.push = function (chunk, encoding) {
} else {
skipChunkCheck = true;
}
-
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
@@ -249,8 +232,8 @@ Readable.prototype.push = function (chunk, encoding) {
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
-
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
+ debug('readableAddChunk', chunk);
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
@@ -259,16 +242,17 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
- stream.emit('error', er);
+ errorOrDestroy(stream, er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
-
if (addToFront) {
- if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
+ if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
} else if (state.ended) {
- stream.emit('error', new Error('stream.push() after EOF'));
+ errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
+ } else if (state.destroyed) {
+ return false;
} else {
state.reading = false;
if (state.decoder && !encoding) {
@@ -280,45 +264,34 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
}
} else if (!addToFront) {
state.reading = false;
+ maybeReadMore(stream, state);
}
}
- return needMoreData(state);
+ // We can push more data if we are below the highWaterMark.
+ // Also, if we have no data yet, we can stand some more bytes.
+ // This is to work around cases where hwm=0, such as the repl.
+ return !state.ended && (state.length < state.highWaterMark || state.length === 0);
}
-
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
+ state.awaitDrain = 0;
stream.emit('data', chunk);
- stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
-
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
-
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
}
return er;
}
-
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
-}
-
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
@@ -326,15 +299,29 @@ Readable.prototype.isPaused = function () {
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
+ var decoder = new StringDecoder(enc);
+ this._readableState.decoder = decoder;
+ // If setEncoding(null), decoder.encoding equals utf8
+ this._readableState.encoding = this._readableState.decoder.encoding;
+
+ // Iterate over current buffer to convert already stored Buffers:
+ var p = this._readableState.buffer.head;
+ var content = '';
+ while (p !== null) {
+ content += decoder.write(p.data);
+ p = p.next;
+ }
+ this._readableState.buffer.clear();
+ if (content !== '') this._readableState.buffer.push(content);
+ this._readableState.length = content.length;
return this;
};
-// Don't raise the hwm > 8MB
-var MAX_HWM = 0x800000;
+// Don't raise the hwm > 1GB
+var MAX_HWM = 0x40000000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
+ // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
@@ -376,18 +363,16 @@ Readable.prototype.read = function (n) {
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
-
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
- if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
+ if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
-
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
@@ -446,17 +431,15 @@ Readable.prototype.read = function (n) {
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
-
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
-
if (ret === null) {
- state.needReadable = true;
+ state.needReadable = state.length <= state.highWaterMark;
n = 0;
} else {
state.length -= n;
+ state.awaitDrain = 0;
}
-
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
@@ -465,13 +448,11 @@ Readable.prototype.read = function (n) {
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
-
if (ret !== null) this.emit('data', ret);
-
return ret;
};
-
function onEofChunk(stream, state) {
+ debug('onEofChunk');
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
@@ -481,9 +462,19 @@ function onEofChunk(stream, state) {
}
}
state.ended = true;
-
- // emit 'readable' now to make sure it gets picked up.
- emitReadable(stream);
+ if (state.sync) {
+ // if we are sync, wait until next tick to emit the data.
+ // Otherwise we risk emitting data in the flow()
+ // the readable code triggers during a read() call
+ emitReadable(stream);
+ } else {
+ // emit 'readable' now to make sure it gets picked up.
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ state.emittedReadable = true;
+ emitReadable_(stream);
+ }
+ }
}
// Don't emit readable right away in sync mode, because this can trigger
@@ -491,17 +482,29 @@ function onEofChunk(stream, state) {
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
+ debug('emitReadable', state.needReadable, state.emittedReadable);
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
- if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
+ process.nextTick(emitReadable_, stream);
}
}
-
function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
+ var state = stream._readableState;
+ debug('emitReadable_', state.destroyed, state.length, state.ended);
+ if (!state.destroyed && (state.length || state.ended)) {
+ stream.emit('readable');
+ state.emittedReadable = false;
+ }
+
+ // The stream needs another readable event if
+ // 1. It is not flowing, as the flow mechanism will take
+ // care of it.
+ // 2. It is not ended.
+ // 3. It is below the highWaterMark, so we can schedule
+ // another readable later.
+ state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
flow(stream);
}
@@ -514,18 +517,40 @@ function emitReadable_(stream) {
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
- pna.nextTick(maybeReadMore_, stream, state);
+ process.nextTick(maybeReadMore_, stream, state);
}
}
-
function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
+ // Attempt to read more data if we should.
+ //
+ // The conditions for reading more data are (one of):
+ // - Not enough data buffered (state.length < state.highWaterMark). The loop
+ // is responsible for filling the buffer with enough data if such data
+ // is available. If highWaterMark is 0 and we are not in the flowing mode
+ // we should _not_ attempt to buffer any extra data. We'll get more data
+ // when the stream consumer calls read() instead.
+ // - No data in the buffer, and the stream is in flowing mode. In this mode
+ // the loop below is responsible for ensuring read() is called. Failing to
+ // call read here would abort the flow and there's no other mechanism for
+ // continuing the flow if the stream consumer has just subscribed to the
+ // 'data' event.
+ //
+ // In addition to the above conditions to keep reading data, the following
+ // conditions prevent the data from being read:
+ // - The stream has ended (state.ended).
+ // - There is already a pending 'read' operation (state.reading). This is a
+ // case where the the stream has called the implementation defined _read()
+ // method, but they are processing the call asynchronously and have _not_
+ // called push() with new data. In this case we skip performing more
+ // read()s. The execution ends in this method again after the _read() ends
+ // up calling push() with more data.
+ while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
+ var len = state.length;
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
- break;else len = state.length;
+ break;
}
state.readingMore = false;
}
@@ -535,13 +560,11 @@ function maybeReadMore_(stream, state) {
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
- this.emit('error', new Error('_read() is not implemented'));
+ errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
};
-
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
-
switch (state.pipesCount) {
case 0:
state.pipes = dest;
@@ -555,12 +578,9 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
-
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
-
var endFn = doEnd ? onend : unpipe;
- if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
-
+ if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
@@ -571,7 +591,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
}
}
}
-
function onend() {
debug('onend');
dest.end();
@@ -583,7 +602,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
-
var cleanedUp = false;
function cleanup() {
debug('cleanup');
@@ -596,7 +614,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
-
cleanedUp = true;
// if the reader is waiting for a drain event from this
@@ -606,18 +623,12 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
-
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
- increasedAwaitDrain = false;
var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
+ debug('dest.write', ret);
+ if (ret === false) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
@@ -625,7 +636,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', state.awaitDrain);
state.awaitDrain++;
- increasedAwaitDrain = true;
}
src.pause();
}
@@ -637,7 +647,7 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
+ if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
}
// Make sure our error handler is attached before userland ones.
@@ -655,7 +665,6 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
unpipe();
}
dest.once('finish', onfinish);
-
function unpipe() {
debug('unpipe');
src.unpipe(dest);
@@ -669,12 +678,10 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
debug('pipe resume');
src.resume();
}
-
return dest;
};
-
function pipeOnDrain(src) {
- return function () {
+ return function pipeOnDrainFunctionResult() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
@@ -684,10 +691,11 @@ function pipeOnDrain(src) {
}
};
}
-
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
- var unpipeInfo = { hasUnpiped: false };
+ var unpipeInfo = {
+ hasUnpiped: false
+ };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
@@ -696,7 +704,6 @@ Readable.prototype.unpipe = function (dest) {
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
-
if (!dest) dest = state.pipes;
// got a match.
@@ -716,22 +723,19 @@ Readable.prototype.unpipe = function (dest) {
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
-
- for (var i = 0; i < len; i++) {
- dests[i].emit('unpipe', this, { hasUnpiped: false });
- }return this;
+ for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {
+ hasUnpiped: false
+ });
+ return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
-
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
-
dest.emit('unpipe', this, unpipeInfo);
-
return this;
};
@@ -739,27 +743,69 @@ Readable.prototype.unpipe = function (dest) {
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
-
+ var state = this._readableState;
if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
+ // update readableListening so that resume() may be a no-op
+ // a few lines down. This is needed to support once('readable').
+ state.readableListening = this.listenerCount('readable') > 0;
+
+ // Try start flowing on next tick if stream isn't explicitly paused
+ if (state.flowing !== false) this.resume();
} else if (ev === 'readable') {
- var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
+ state.flowing = false;
state.emittedReadable = false;
- if (!state.reading) {
- pna.nextTick(nReadingNextTick, this);
- } else if (state.length) {
+ debug('on readable', state.length, state.reading);
+ if (state.length) {
emitReadable(this);
+ } else if (!state.reading) {
+ process.nextTick(nReadingNextTick, this);
}
}
}
-
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
+Readable.prototype.removeListener = function (ev, fn) {
+ var res = Stream.prototype.removeListener.call(this, ev, fn);
+ if (ev === 'readable') {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+ return res;
+};
+Readable.prototype.removeAllListeners = function (ev) {
+ var res = Stream.prototype.removeAllListeners.apply(this, arguments);
+ if (ev === 'readable' || ev === undefined) {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+ return res;
+};
+function updateReadableListening(self) {
+ var state = self._readableState;
+ state.readableListening = self.listenerCount('readable') > 0;
+ if (state.resumeScheduled && !state.paused) {
+ // flowing needs to be set to true now, otherwise
+ // the upcoming resume will not flow.
+ state.flowing = true;
+ // crude way to check if we should resume
+ } else if (self.listenerCount('data') > 0) {
+ self.resume();
+ }
+}
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
@@ -771,46 +817,45 @@ Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
- state.flowing = true;
+ // we flow only if there is no one listening
+ // for readable, but we still have to call
+ // resume()
+ state.flowing = !state.readableListening;
resume(this, state);
}
+ state.paused = false;
return this;
};
-
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
- pna.nextTick(resume_, stream, state);
+ process.nextTick(resume_, stream, state);
}
}
-
function resume_(stream, state) {
+ debug('resume', state.reading);
if (!state.reading) {
- debug('resume read 0');
stream.read(0);
}
-
state.resumeScheduled = false;
- state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
-
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
- if (false !== this._readableState.flowing) {
+ if (this._readableState.flowing !== false) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
+ this._readableState.paused = true;
return this;
};
-
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
- while (state.flowing && stream.read() !== null) {}
+ while (state.flowing && stream.read() !== null);
}
// wrap an old-style stream as the async data source.
@@ -818,27 +863,22 @@ function flow(stream) {
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
-
var state = this._readableState;
var paused = false;
-
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
-
_this.push(null);
});
-
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
-
var ret = _this.push(chunk);
if (!ret) {
paused = true;
@@ -850,8 +890,8 @@ Readable.prototype.wrap = function (stream) {
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
- this[i] = function (method) {
- return function () {
+ this[i] = function methodWrap(method) {
+ return function methodWrapReturnFunction() {
return stream[method].apply(stream, arguments);
};
}(i);
@@ -872,22 +912,60 @@ Readable.prototype.wrap = function (stream) {
stream.resume();
}
};
-
return this;
};
-
+if (typeof Symbol === 'function') {
+ Readable.prototype[Symbol.asyncIterator] = function () {
+ if (createReadableStreamAsyncIterator === undefined) {
+ createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
+ }
+ return createReadableStreamAsyncIterator(this);
+ };
+}
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
- get: function () {
+ get: function get() {
return this._readableState.highWaterMark;
}
});
+Object.defineProperty(Readable.prototype, 'readableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState && this._readableState.buffer;
+ }
+});
+Object.defineProperty(Readable.prototype, 'readableFlowing', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.flowing;
+ },
+ set: function set(state) {
+ if (this._readableState) {
+ this._readableState.flowing = state;
+ }
+ }
+});
// exposed for testing purposes only.
Readable._fromList = fromList;
+Object.defineProperty(Readable.prototype, 'readableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.length;
+ }
+});
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
@@ -896,121 +974,51 @@ Readable._fromList = fromList;
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
-
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
- 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);
+ if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
-
- return ret;
-}
-
-// Extracts only enough buffered data to satisfy the amount requested.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
+ ret = state.buffer.consume(n, state.decoder);
}
return ret;
}
-
-// Copies a specified amount of characters from the list of buffered data
-// chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
-// Copies a specified amount of bytes from the list of buffered data chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBuffer(n, list) {
- var ret = Buffer.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
function endReadable(stream) {
var state = stream._readableState;
-
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
-
+ debug('endReadable', state.endEmitted);
if (!state.endEmitted) {
state.ended = true;
- pna.nextTick(endReadableNT, state, stream);
+ process.nextTick(endReadableNT, state, stream);
}
}
-
function endReadableNT(state, stream) {
+ debug('endReadableNT', state.endEmitted, state.length);
+
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the writable side is ready for autoDestroy as well
+ var wState = stream._writableState;
+ if (!wState || wState.autoDestroy && wState.finished) {
+ stream.destroy();
+ }
+ }
}
}
-
+if (typeof Symbol === 'function') {
+ Readable.from = function (iterable, opts) {
+ if (from === undefined) {
+ from = require('./internal/streams/from');
+ }
+ return from(Readable, iterable, opts);
+ };
+}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
diff --git a/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/readable-stream/lib/_stream_transform.js
index fcfc105..1ccb715 100644
--- a/node_modules/readable-stream/lib/_stream_transform.js
+++ b/node_modules/readable-stream/lib/_stream_transform.js
@@ -64,46 +64,35 @@
'use strict';
module.exports = Transform;
-
+var _require$codes = require('../errors').codes,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
+ ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = require('./_stream_duplex');
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-util.inherits(Transform, Duplex);
-
+require('inherits')(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
-
var cb = ts.writecb;
-
- if (!cb) {
- return this.emit('error', new Error('write callback called multiple times'));
+ if (cb === null) {
+ return this.emit('error', new ERR_MULTIPLE_CALLBACK());
}
-
ts.writechunk = null;
ts.writecb = null;
-
- if (data != null) // single equals check for both `null` and `undefined`
+ if (data != null)
+ // single equals check for both `null` and `undefined`
this.push(data);
-
cb(er);
-
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
-
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
-
Duplex.call(this, options);
-
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
@@ -120,21 +109,17 @@ function Transform(options) {
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
-
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
-
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
-
function prefinish() {
var _this = this;
-
- if (typeof this._flush === 'function') {
+ if (typeof this._flush === 'function' && !this._readableState.destroyed) {
this._flush(function (er, data) {
done(_this, er, data);
});
@@ -142,7 +127,6 @@ function prefinish() {
done(this, null, null);
}
}
-
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
@@ -159,9 +143,8 @@ Transform.prototype.push = function (chunk, encoding) {
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
- throw new Error('_transform() is not implemented');
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
-
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
@@ -178,8 +161,7 @@ Transform.prototype._write = function (chunk, encoding, cb) {
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
-
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
+ if (ts.writechunk !== null && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
@@ -188,27 +170,21 @@ Transform.prototype._read = function (n) {
ts.needTransform = true;
}
};
-
Transform.prototype._destroy = function (err, cb) {
- var _this2 = this;
-
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
- _this2.emit('close');
});
};
-
function done(stream, er, data) {
if (er) return stream.emit('error', er);
-
- if (data != null) // single equals check for both `null` and `undefined`
+ if (data != null)
+ // single equals check for both `null` and `undefined`
stream.push(data);
+ // TODO(BridgeAR): Write a test for these two error cases
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
- if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
-
- if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
-
+ if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
+ if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null);
}
\ No newline at end of file
diff --git a/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/readable-stream/lib/_stream_writable.js
index e1e897f..292415e 100644
--- a/node_modules/readable-stream/lib/_stream_writable.js
+++ b/node_modules/readable-stream/lib/_stream_writable.js
@@ -25,11 +25,6 @@
'use strict';
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
module.exports = Writable;
/* */
@@ -44,7 +39,6 @@ function WriteReq(chunk, encoding, cb) {
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
-
this.next = null;
this.entry = null;
this.finish = function () {
@@ -53,21 +47,12 @@ function CorkedRequest(state) {
}
/* */
-/**/
-var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
-/**/
-
/**/
var Duplex;
/**/
Writable.WritableState = WritableState;
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
/**/
var internalUtil = {
deprecate: require('util-deprecate')
@@ -78,9 +63,7 @@ var internalUtil = {
var Stream = require('./internal/streams/stream');
/**/
-/**/
-
-var Buffer = require('safe-buffer').Buffer;
+var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
@@ -88,44 +71,41 @@ function _uint8ArrayToBuffer(chunk) {
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
-
-/**/
-
var destroyImpl = require('./internal/streams/destroy');
-
-util.inherits(Writable, Stream);
-
+var _require = require('./internal/streams/state'),
+ getHighWaterMark = _require.getHighWaterMark;
+var _require$codes = require('../errors').codes,
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
+ ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
+ ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
+ ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
+ ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
+var errorOrDestroy = destroyImpl.errorOrDestroy;
+require('inherits')(Writable, Stream);
function nop() {}
-
-function WritableState(options, stream) {
+function WritableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
-
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
+ // values for the readable and the writable sides of the duplex stream,
+ // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
-
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
- var hwm = options.highWaterMark;
- var writableHwm = options.writableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
+ this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
// if _final has been called
this.finalCalled = false;
@@ -185,7 +165,6 @@ function WritableState(options, stream) {
// the amount that is being written when _write is called.
this.writelen = 0;
-
this.bufferedRequest = null;
this.lastBufferedRequest = null;
@@ -200,6 +179,12 @@ function WritableState(options, stream) {
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
+ // Should close be emitted on destroy. Defaults to true.
+ this.emitClose = options.emitClose !== false;
+
+ // Should .destroy() be called after 'finish' (and potentially 'end')
+ this.autoDestroy = !!options.autoDestroy;
+
// count buffered requests
this.bufferedRequestCount = 0;
@@ -207,7 +192,6 @@ function WritableState(options, stream) {
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
-
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
@@ -217,11 +201,10 @@ WritableState.prototype.getBuffer = function getBuffer() {
}
return out;
};
-
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
+ get: internalUtil.deprecate(function writableStateBufferGetter() {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
@@ -234,19 +217,17 @@ var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function (object) {
+ value: function value(object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
-
return object && object._writableState instanceof WritableState;
}
});
} else {
- realHasInstance = function (object) {
+ realHasInstance = function realHasInstance(object) {
return object instanceof this;
};
}
-
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
@@ -257,123 +238,109 @@ function Writable(options) {
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
- if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
- return new Writable(options);
- }
- this._writableState = new WritableState(options, this);
+ // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the WritableState constructor, at least with V8 6.5
+ var isDuplex = this instanceof Duplex;
+ if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
+ this._writableState = new WritableState(options, this, isDuplex);
// legacy.
this.writable = true;
-
if (options) {
if (typeof options.write === 'function') this._write = options.write;
-
if (typeof options.writev === 'function') this._writev = options.writev;
-
if (typeof options.destroy === 'function') this._destroy = options.destroy;
-
if (typeof options.final === 'function') this._final = options.final;
}
-
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
+ errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
-
function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
+ var er = new ERR_STREAM_WRITE_AFTER_END();
// TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- pna.nextTick(cb, er);
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
-
+ var er;
if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
+ er = new ERR_STREAM_NULL_VALUES();
+ } else if (typeof chunk !== 'string' && !state.objectMode) {
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
}
if (er) {
- stream.emit('error', er);
- pna.nextTick(cb, er);
- valid = false;
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
+ return false;
}
- return valid;
+ return true;
}
-
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
-
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
-
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
-
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
-
if (typeof cb !== 'function') cb = nop;
-
- if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
+ if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
-
return ret;
};
-
Writable.prototype.cork = function () {
- var state = this._writableState;
-
- state.corked++;
+ this._writableState.corked++;
};
-
Writable.prototype.uncork = function () {
var state = this._writableState;
-
if (state.corked) {
state.corked--;
-
if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
-
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
- 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);
+ if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
-
+Object.defineProperty(Writable.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
-
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
- get: function () {
+ get: function get() {
return this._writableState.highWaterMark;
}
});
@@ -391,13 +358,10 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
}
}
var len = state.objectMode ? 1 : chunk.length;
-
state.length += len;
-
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
-
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
@@ -416,75 +380,63 @@ function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
-
return ret;
}
-
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
- if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
+ if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
-
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
-
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
- pna.nextTick(cb, er);
+ process.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
- pna.nextTick(finishMaybe, stream, state);
+ process.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
- stream.emit('error', er);
+ errorOrDestroy(stream, er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
- stream.emit('error', er);
+ errorOrDestroy(stream, er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
-
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
-
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
-
+ if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
onwriteStateUpdate(state);
-
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
-
+ var finished = needFinish(state) || stream.destroyed;
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
-
if (sync) {
- /**/
- asyncWrite(afterWrite, stream, state, finished, cb);
- /**/
+ process.nextTick(afterWrite, stream, state, finished, cb);
} else {
afterWrite(stream, state, finished, cb);
}
}
}
-
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
@@ -506,14 +458,12 @@ function onwriteDrain(stream, state) {
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
-
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
-
var count = 0;
var allBuffers = true;
while (entry) {
@@ -523,7 +473,6 @@ function clearBuffer(stream, state) {
count += 1;
}
buffer.allBuffers = allBuffers;
-
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
@@ -544,7 +493,6 @@ function clearBuffer(stream, state) {
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
-
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
@@ -556,23 +504,17 @@ function clearBuffer(stream, state) {
break;
}
}
-
if (entry === null) state.lastBufferedRequest = null;
}
-
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
-
Writable.prototype._write = function (chunk, encoding, cb) {
- cb(new Error('_write() is not implemented'));
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
-
Writable.prototype._writev = null;
-
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
-
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
@@ -581,7 +523,6 @@ Writable.prototype.end = function (chunk, encoding, cb) {
cb = encoding;
encoding = null;
}
-
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
@@ -592,8 +533,17 @@ Writable.prototype.end = function (chunk, encoding, cb) {
// ignore unnecessary end() calls.
if (!state.ending) endWritable(this, state, cb);
+ return this;
};
-
+Object.defineProperty(Writable.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+});
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
@@ -601,7 +551,7 @@ function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
- stream.emit('error', err);
+ errorOrDestroy(stream, err);
}
state.prefinished = true;
stream.emit('prefinish');
@@ -610,17 +560,16 @@ function callFinal(stream, state) {
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
- if (typeof stream._final === 'function') {
+ if (typeof stream._final === 'function' && !state.destroyed) {
state.pendingcb++;
state.finalCalled = true;
- pna.nextTick(callFinal, stream, state);
+ process.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
-
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
@@ -628,21 +577,27 @@ function finishMaybe(stream, state) {
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the readable side is ready for autoDestroy as well
+ var rState = stream._readableState;
+ if (!rState || rState.autoDestroy && rState.endEmitted) {
+ stream.destroy();
+ }
+ }
}
}
return need;
}
-
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
- if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
+ if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
-
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
@@ -656,15 +611,18 @@ function onCorkedFinish(corkReq, state, err) {
// reuse the free corkReq.
state.corkedRequestsFree.next = corkReq;
}
-
Object.defineProperty(Writable.prototype, 'destroyed', {
- get: function () {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
- set: function (value) {
+ set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
@@ -676,10 +634,8 @@ Object.defineProperty(Writable.prototype, 'destroyed', {
this._writableState.destroyed = value;
}
});
-
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
- this.end();
cb(err);
};
\ No newline at end of file
diff --git a/node_modules/readable-stream/lib/internal/streams/BufferList.js b/node_modules/readable-stream/lib/internal/streams/BufferList.js
deleted file mode 100644
index 5e08097..0000000
--- a/node_modules/readable-stream/lib/internal/streams/BufferList.js
+++ /dev/null
@@ -1,78 +0,0 @@
-'use strict';
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-var Buffer = require('safe-buffer').Buffer;
-var util = require('util');
-
-function copyBuffer(src, target, offset) {
- src.copy(target, offset);
-}
-
-module.exports = function () {
- function BufferList() {
- _classCallCheck(this, BufferList);
-
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
-
- BufferList.prototype.push = function push(v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
-
- BufferList.prototype.unshift = function unshift(v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
-
- BufferList.prototype.shift = function shift() {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
-
- BufferList.prototype.clear = function clear() {
- this.head = this.tail = null;
- this.length = 0;
- };
-
- BufferList.prototype.join = function join(s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
-
- BufferList.prototype.concat = function concat(n) {
- if (this.length === 0) return Buffer.alloc(0);
- var ret = Buffer.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- copyBuffer(p.data, ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
-
- return BufferList;
-}();
-
-if (util && util.inspect && util.inspect.custom) {
- module.exports.prototype[util.inspect.custom] = function () {
- var obj = util.inspect({ length: this.length });
- return this.constructor.name + ' ' + obj;
- };
-}
\ No newline at end of file
diff --git a/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/readable-stream/lib/internal/streams/destroy.js
index 85a8214..31a17c4 100644
--- a/node_modules/readable-stream/lib/internal/streams/destroy.js
+++ b/node_modules/readable-stream/lib/internal/streams/destroy.js
@@ -1,29 +1,21 @@
'use strict';
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
-
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
-
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err) {
if (!this._writableState) {
- pna.nextTick(emitErrorNT, this, err);
+ process.nextTick(emitErrorNT, this, err);
} else if (!this._writableState.errorEmitted) {
this._writableState.errorEmitted = true;
- pna.nextTick(emitErrorNT, this, err);
+ process.nextTick(emitErrorNT, this, err);
}
}
-
return this;
}
@@ -38,23 +30,34 @@ function destroy(err, cb) {
if (this._writableState) {
this._writableState.destroyed = true;
}
-
this._destroy(err || null, function (err) {
if (!cb && err) {
if (!_this._writableState) {
- pna.nextTick(emitErrorNT, _this, err);
+ process.nextTick(emitErrorAndCloseNT, _this, err);
} else if (!_this._writableState.errorEmitted) {
_this._writableState.errorEmitted = true;
- pna.nextTick(emitErrorNT, _this, err);
+ process.nextTick(emitErrorAndCloseNT, _this, err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
}
} else if (cb) {
+ process.nextTick(emitCloseNT, _this);
cb(err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
}
});
-
return this;
}
-
+function emitErrorAndCloseNT(self, err) {
+ emitErrorNT(self, err);
+ emitCloseNT(self);
+}
+function emitCloseNT(self) {
+ if (self._writableState && !self._writableState.emitClose) return;
+ if (self._readableState && !self._readableState.emitClose) return;
+ self.emit('close');
+}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
@@ -62,7 +65,6 @@ function undestroy() {
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
-
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
@@ -73,12 +75,22 @@ function undestroy() {
this._writableState.errorEmitted = false;
}
}
-
function emitErrorNT(self, err) {
self.emit('error', err);
}
+function errorOrDestroy(stream, err) {
+ // We have tests that rely on errors being emitted
+ // in the same tick, so changing this is semver major.
+ // For now when you opt-in to autoDestroy we allow
+ // the error to be emitted nextTick. In a future
+ // semver major update we should change the default to this.
+ var rState = stream._readableState;
+ var wState = stream._writableState;
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
+}
module.exports = {
destroy: destroy,
- undestroy: undestroy
+ undestroy: undestroy,
+ errorOrDestroy: errorOrDestroy
};
\ No newline at end of file
diff --git a/node_modules/readable-stream/node_modules/safe-buffer/LICENSE b/node_modules/readable-stream/node_modules/safe-buffer/LICENSE
deleted file mode 100644
index 0c068ce..0000000
--- a/node_modules/readable-stream/node_modules/safe-buffer/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) Feross Aboukhadijeh
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/node_modules/readable-stream/node_modules/safe-buffer/README.md b/node_modules/readable-stream/node_modules/safe-buffer/README.md
deleted file mode 100644
index e9a81af..0000000
--- a/node_modules/readable-stream/node_modules/safe-buffer/README.md
+++ /dev/null
@@ -1,584 +0,0 @@
-# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
-
-[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
-[travis-url]: https://travis-ci.org/feross/safe-buffer
-[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
-[npm-url]: https://npmjs.org/package/safe-buffer
-[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
-[downloads-url]: https://npmjs.org/package/safe-buffer
-[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
-[standard-url]: https://standardjs.com
-
-#### Safer Node.js Buffer API
-
-**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
-`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
-
-**Uses the built-in implementation when available.**
-
-## install
-
-```
-npm install safe-buffer
-```
-
-## usage
-
-The goal of this package is to provide a safe replacement for the node.js `Buffer`.
-
-It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
-the top of your node.js modules:
-
-```js
-var Buffer = require('safe-buffer').Buffer
-
-// Existing buffer code will continue to work without issues:
-
-new Buffer('hey', 'utf8')
-new Buffer([1, 2, 3], 'utf8')
-new Buffer(obj)
-new Buffer(16) // create an uninitialized buffer (potentially unsafe)
-
-// But you can use these new explicit APIs to make clear what you want:
-
-Buffer.from('hey', 'utf8') // convert from many types to a Buffer
-Buffer.alloc(16) // create a zero-filled buffer (safe)
-Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
-```
-
-## api
-
-### Class Method: Buffer.from(array)
-
-
-* `array` {Array}
-
-Allocates a new `Buffer` using an `array` of octets.
-
-```js
-const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
- // creates a new Buffer containing ASCII bytes
- // ['b','u','f','f','e','r']
-```
-
-A `TypeError` will be thrown if `array` is not an `Array`.
-
-### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
-
-
-* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
- a `new ArrayBuffer()`
-* `byteOffset` {Number} Default: `0`
-* `length` {Number} Default: `arrayBuffer.length - byteOffset`
-
-When passed a reference to the `.buffer` property of a `TypedArray` instance,
-the newly created `Buffer` will share the same allocated memory as the
-TypedArray.
-
-```js
-const arr = new Uint16Array(2);
-arr[0] = 5000;
-arr[1] = 4000;
-
-const buf = Buffer.from(arr.buffer); // shares the memory with arr;
-
-console.log(buf);
- // Prints:
-
-// changing the TypedArray changes the Buffer also
-arr[1] = 6000;
-
-console.log(buf);
- // Prints:
-```
-
-The optional `byteOffset` and `length` arguments specify a memory range within
-the `arrayBuffer` that will be shared by the `Buffer`.
-
-```js
-const ab = new ArrayBuffer(10);
-const buf = Buffer.from(ab, 0, 2);
-console.log(buf.length);
- // Prints: 2
-```
-
-A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
-
-### Class Method: Buffer.from(buffer)
-
-
-* `buffer` {Buffer}
-
-Copies the passed `buffer` data onto a new `Buffer` instance.
-
-```js
-const buf1 = Buffer.from('buffer');
-const buf2 = Buffer.from(buf1);
-
-buf1[0] = 0x61;
-console.log(buf1.toString());
- // 'auffer'
-console.log(buf2.toString());
- // 'buffer' (copy is not changed)
-```
-
-A `TypeError` will be thrown if `buffer` is not a `Buffer`.
-
-### Class Method: Buffer.from(str[, encoding])
-
-
-* `str` {String} String to encode.
-* `encoding` {String} Encoding to use, Default: `'utf8'`
-
-Creates a new `Buffer` containing the given JavaScript string `str`. If
-provided, the `encoding` parameter identifies the character encoding.
-If not provided, `encoding` defaults to `'utf8'`.
-
-```js
-const buf1 = Buffer.from('this is a tést');
-console.log(buf1.toString());
- // prints: this is a tést
-console.log(buf1.toString('ascii'));
- // prints: this is a tC)st
-
-const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
-console.log(buf2.toString());
- // prints: this is a tést
-```
-
-A `TypeError` will be thrown if `str` is not a string.
-
-### Class Method: Buffer.alloc(size[, fill[, encoding]])
-
-
-* `size` {Number}
-* `fill` {Value} Default: `undefined`
-* `encoding` {String} Default: `utf8`
-
-Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
-`Buffer` will be *zero-filled*.
-
-```js
-const buf = Buffer.alloc(5);
-console.log(buf);
- //
-```
-
-The `size` must be less than or equal to the value of
-`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
-`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
-be created if a `size` less than or equal to 0 is specified.
-
-If `fill` is specified, the allocated `Buffer` will be initialized by calling
-`buf.fill(fill)`. See [`buf.fill()`][] for more information.
-
-```js
-const buf = Buffer.alloc(5, 'a');
-console.log(buf);
- //
-```
-
-If both `fill` and `encoding` are specified, the allocated `Buffer` will be
-initialized by calling `buf.fill(fill, encoding)`. For example:
-
-```js
-const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
-console.log(buf);
- //
-```
-
-Calling `Buffer.alloc(size)` can be significantly slower than the alternative
-`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
-contents will *never contain sensitive data*.
-
-A `TypeError` will be thrown if `size` is not a number.
-
-### Class Method: Buffer.allocUnsafe(size)
-
-
-* `size` {Number}
-
-Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
-be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
-architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
-thrown. A zero-length Buffer will be created if a `size` less than or equal to
-0 is specified.
-
-The underlying memory for `Buffer` instances created in this way is *not
-initialized*. The contents of the newly created `Buffer` are unknown and
-*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
-`Buffer` instances to zeroes.
-
-```js
-const buf = Buffer.allocUnsafe(5);
-console.log(buf);
- //
- // (octets will be different, every time)
-buf.fill(0);
-console.log(buf);
- //
-```
-
-A `TypeError` will be thrown if `size` is not a number.
-
-Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
-size `Buffer.poolSize` that is used as a pool for the fast allocation of new
-`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
-`new Buffer(size)` constructor) only when `size` is less than or equal to
-`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
-value of `Buffer.poolSize` is `8192` but can be modified.
-
-Use of this pre-allocated internal memory pool is a key difference between
-calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
-Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
-pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
-Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
-difference is subtle but can be important when an application requires the
-additional performance that `Buffer.allocUnsafe(size)` provides.
-
-### Class Method: Buffer.allocUnsafeSlow(size)
-
-
-* `size` {Number}
-
-Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
-`size` must be less than or equal to the value of
-`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
-`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
-be created if a `size` less than or equal to 0 is specified.
-
-The underlying memory for `Buffer` instances created in this way is *not
-initialized*. The contents of the newly created `Buffer` are unknown and
-*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
-`Buffer` instances to zeroes.
-
-When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
-allocations under 4KB are, by default, sliced from a single pre-allocated
-`Buffer`. This allows applications to avoid the garbage collection overhead of
-creating many individually allocated Buffers. This approach improves both
-performance and memory usage by eliminating the need to track and cleanup as
-many `Persistent` objects.
-
-However, in the case where a developer may need to retain a small chunk of
-memory from a pool for an indeterminate amount of time, it may be appropriate
-to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
-copy out the relevant bits.
-
-```js
-// need to keep around a few small chunks of memory
-const store = [];
-
-socket.on('readable', () => {
- const data = socket.read();
- // allocate for retained data
- const sb = Buffer.allocUnsafeSlow(10);
- // copy the data into the new allocation
- data.copy(sb, 0, 0, 10);
- store.push(sb);
-});
-```
-
-Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
-a developer has observed undue memory retention in their applications.
-
-A `TypeError` will be thrown if `size` is not a number.
-
-### All the Rest
-
-The rest of the `Buffer` API is exactly the same as in node.js.
-[See the docs](https://nodejs.org/api/buffer.html).
-
-
-## Related links
-
-- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
-- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
-
-## Why is `Buffer` unsafe?
-
-Today, the node.js `Buffer` constructor is overloaded to handle many different argument
-types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
-`ArrayBuffer`, and also `Number`.
-
-The API is optimized for convenience: you can throw any type at it, and it will try to do
-what you want.
-
-Because the Buffer constructor is so powerful, you often see code like this:
-
-```js
-// Convert UTF-8 strings to hex
-function toHex (str) {
- return new Buffer(str).toString('hex')
-}
-```
-
-***But what happens if `toHex` is called with a `Number` argument?***
-
-### Remote Memory Disclosure
-
-If an attacker can make your program call the `Buffer` constructor with a `Number`
-argument, then they can make it allocate uninitialized memory from the node.js process.
-This could potentially disclose TLS private keys, user data, or database passwords.
-
-When the `Buffer` constructor is passed a `Number` argument, it returns an
-**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
-this, you **MUST** overwrite the contents before returning it to the user.
-
-From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
-
-> `new Buffer(size)`
->
-> - `size` Number
->
-> The underlying memory for `Buffer` instances created in this way is not initialized.
-> **The contents of a newly created `Buffer` are unknown and could contain sensitive
-> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
-
-(Emphasis our own.)
-
-Whenever the programmer intended to create an uninitialized `Buffer` you often see code
-like this:
-
-```js
-var buf = new Buffer(16)
-
-// Immediately overwrite the uninitialized buffer with data from another buffer
-for (var i = 0; i < buf.length; i++) {
- buf[i] = otherBuf[i]
-}
-```
-
-
-### Would this ever be a problem in real code?
-
-Yes. It's surprisingly common to forget to check the type of your variables in a
-dynamically-typed language like JavaScript.
-
-Usually the consequences of assuming the wrong type is that your program crashes with an
-uncaught exception. But the failure mode for forgetting to check the type of arguments to
-the `Buffer` constructor is more catastrophic.
-
-Here's an example of a vulnerable service that takes a JSON payload and converts it to
-hex:
-
-```js
-// Take a JSON payload {str: "some string"} and convert it to hex
-var server = http.createServer(function (req, res) {
- var data = ''
- req.setEncoding('utf8')
- req.on('data', function (chunk) {
- data += chunk
- })
- req.on('end', function () {
- var body = JSON.parse(data)
- res.end(new Buffer(body.str).toString('hex'))
- })
-})
-
-server.listen(8080)
-```
-
-In this example, an http client just has to send:
-
-```json
-{
- "str": 1000
-}
-```
-
-and it will get back 1,000 bytes of uninitialized memory from the server.
-
-This is a very serious bug. It's similar in severity to the
-[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
-memory by remote attackers.
-
-
-### Which real-world packages were vulnerable?
-
-#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
-
-[Mathias Buus](https://github.com/mafintosh) and I
-([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
-[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
-anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
-them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
-
-Here's
-[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
-that fixed it. We released a new fixed version, created a
-[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
-vulnerable versions on npm so users will get a warning to upgrade to a newer version.
-
-#### [`ws`](https://www.npmjs.com/package/ws)
-
-That got us wondering if there were other vulnerable packages. Sure enough, within a short
-period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
-most popular WebSocket implementation in node.js.
-
-If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
-expected, then uninitialized server memory would be disclosed to the remote peer.
-
-These were the vulnerable methods:
-
-```js
-socket.send(number)
-socket.ping(number)
-socket.pong(number)
-```
-
-Here's a vulnerable socket server with some echo functionality:
-
-```js
-server.on('connection', function (socket) {
- socket.on('message', function (message) {
- message = JSON.parse(message)
- if (message.type === 'echo') {
- socket.send(message.data) // send back the user's message
- }
- })
-})
-```
-
-`socket.send(number)` called on the server, will disclose server memory.
-
-Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
-was fixed, with a more detailed explanation. Props to
-[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
-[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
-
-
-### What's the solution?
-
-It's important that node.js offers a fast way to get memory otherwise performance-critical
-applications would needlessly get a lot slower.
-
-But we need a better way to *signal our intent* as programmers. **When we want
-uninitialized memory, we should request it explicitly.**
-
-Sensitive functionality should not be packed into a developer-friendly API that loosely
-accepts many different types. This type of API encourages the lazy practice of passing
-variables in without checking the type very carefully.
-
-#### A new API: `Buffer.allocUnsafe(number)`
-
-The functionality of creating buffers with uninitialized memory should be part of another
-API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
-frequently gets user input of all sorts of different types passed into it.
-
-```js
-var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
-
-// Immediately overwrite the uninitialized buffer with data from another buffer
-for (var i = 0; i < buf.length; i++) {
- buf[i] = otherBuf[i]
-}
-```
-
-
-### How do we fix node.js core?
-
-We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
-`semver-major`) which defends against one case:
-
-```js
-var str = 16
-new Buffer(str, 'utf8')
-```
-
-In this situation, it's implied that the programmer intended the first argument to be a
-string, since they passed an encoding as a second argument. Today, node.js will allocate
-uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
-what the programmer intended.
-
-But this is only a partial solution, since if the programmer does `new Buffer(variable)`
-(without an `encoding` parameter) there's no way to know what they intended. If `variable`
-is sometimes a number, then uninitialized memory will sometimes be returned.
-
-### What's the real long-term fix?
-
-We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
-we need uninitialized memory. But that would break 1000s of packages.
-
-~~We believe the best solution is to:~~
-
-~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
-
-~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
-
-#### Update
-
-We now support adding three new APIs:
-
-- `Buffer.from(value)` - convert from any type to a buffer
-- `Buffer.alloc(size)` - create a zero-filled buffer
-- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
-
-This solves the core problem that affected `ws` and `bittorrent-dht` which is
-`Buffer(variable)` getting tricked into taking a number argument.
-
-This way, existing code continues working and the impact on the npm ecosystem will be
-minimal. Over time, npm maintainers can migrate performance-critical code to use
-`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
-
-
-### Conclusion
-
-We think there's a serious design issue with the `Buffer` API as it exists today. It
-promotes insecure software by putting high-risk functionality into a convenient API
-with friendly "developer ergonomics".
-
-This wasn't merely a theoretical exercise because we found the issue in some of the
-most popular npm packages.
-
-Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
-`buffer`.
-
-```js
-var Buffer = require('safe-buffer').Buffer
-```
-
-Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
-the impact on the ecosystem would be minimal since it's not a breaking change.
-Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
-older, insecure packages would magically become safe from this attack vector.
-
-
-## links
-
-- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
-- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
-- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
-
-
-## credit
-
-The original issues in `bittorrent-dht`
-([disclosure](https://nodesecurity.io/advisories/68)) and
-`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
-[Mathias Buus](https://github.com/mafintosh) and
-[Feross Aboukhadijeh](http://feross.org/).
-
-Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
-and for his work running the [Node Security Project](https://nodesecurity.io/).
-
-Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
-auditing the code.
-
-
-## license
-
-MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
diff --git a/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts b/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts
deleted file mode 100644
index e9fed80..0000000
--- a/node_modules/readable-stream/node_modules/safe-buffer/index.d.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-declare module "safe-buffer" {
- export class Buffer {
- length: number
- write(string: string, offset?: number, length?: number, encoding?: string): number;
- toString(encoding?: string, start?: number, end?: number): string;
- toJSON(): { type: 'Buffer', data: any[] };
- equals(otherBuffer: Buffer): boolean;
- compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
- copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
- slice(start?: number, end?: number): Buffer;
- writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
- writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
- writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
- writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
- readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
- readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
- readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
- readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
- readUInt8(offset: number, noAssert?: boolean): number;
- readUInt16LE(offset: number, noAssert?: boolean): number;
- readUInt16BE(offset: number, noAssert?: boolean): number;
- readUInt32LE(offset: number, noAssert?: boolean): number;
- readUInt32BE(offset: number, noAssert?: boolean): number;
- readInt8(offset: number, noAssert?: boolean): number;
- readInt16LE(offset: number, noAssert?: boolean): number;
- readInt16BE(offset: number, noAssert?: boolean): number;
- readInt32LE(offset: number, noAssert?: boolean): number;
- readInt32BE(offset: number, noAssert?: boolean): number;
- readFloatLE(offset: number, noAssert?: boolean): number;
- readFloatBE(offset: number, noAssert?: boolean): number;
- readDoubleLE(offset: number, noAssert?: boolean): number;
- readDoubleBE(offset: number, noAssert?: boolean): number;
- swap16(): Buffer;
- swap32(): Buffer;
- swap64(): Buffer;
- writeUInt8(value: number, offset: number, noAssert?: boolean): number;
- writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
- writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
- writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
- writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
- writeInt8(value: number, offset: number, noAssert?: boolean): number;
- writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
- writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
- writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
- writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
- writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
- writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
- writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
- writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
- fill(value: any, offset?: number, end?: number): this;
- indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
- lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
- includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
-
- /**
- * Allocates a new buffer containing the given {str}.
- *
- * @param str String to store in buffer.
- * @param encoding encoding to use, optional. Default is 'utf8'
- */
- constructor (str: string, encoding?: string);
- /**
- * Allocates a new buffer of {size} octets.
- *
- * @param size count of octets to allocate.
- */
- constructor (size: number);
- /**
- * Allocates a new buffer containing the given {array} of octets.
- *
- * @param array The octets to store.
- */
- constructor (array: Uint8Array);
- /**
- * Produces a Buffer backed by the same allocated memory as
- * the given {ArrayBuffer}.
- *
- *
- * @param arrayBuffer The ArrayBuffer with which to share memory.
- */
- constructor (arrayBuffer: ArrayBuffer);
- /**
- * Allocates a new buffer containing the given {array} of octets.
- *
- * @param array The octets to store.
- */
- constructor (array: any[]);
- /**
- * Copies the passed {buffer} data onto a new {Buffer} instance.
- *
- * @param buffer The buffer to copy.
- */
- constructor (buffer: Buffer);
- prototype: Buffer;
- /**
- * Allocates a new Buffer using an {array} of octets.
- *
- * @param array
- */
- static from(array: any[]): Buffer;
- /**
- * When passed a reference to the .buffer property of a TypedArray instance,
- * the newly created Buffer will share the same allocated memory as the TypedArray.
- * The optional {byteOffset} and {length} arguments specify a memory range
- * within the {arrayBuffer} that will be shared by the Buffer.
- *
- * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
- * @param byteOffset
- * @param length
- */
- static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
- /**
- * Copies the passed {buffer} data onto a new Buffer instance.
- *
- * @param buffer
- */
- static from(buffer: Buffer): Buffer;
- /**
- * Creates a new Buffer containing the given JavaScript string {str}.
- * If provided, the {encoding} parameter identifies the character encoding.
- * If not provided, {encoding} defaults to 'utf8'.
- *
- * @param str
- */
- static from(str: string, encoding?: string): Buffer;
- /**
- * Returns true if {obj} is a Buffer
- *
- * @param obj object to test.
- */
- static isBuffer(obj: any): obj is Buffer;
- /**
- * Returns true if {encoding} is a valid encoding argument.
- * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
- *
- * @param encoding string to test.
- */
- static isEncoding(encoding: string): boolean;
- /**
- * Gives the actual byte length of a string. encoding defaults to 'utf8'.
- * This is not the same as String.prototype.length since that returns the number of characters in a string.
- *
- * @param string string to test.
- * @param encoding encoding used to evaluate (defaults to 'utf8')
- */
- static byteLength(string: string, encoding?: string): number;
- /**
- * Returns a buffer which is the result of concatenating all the buffers in the list together.
- *
- * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
- * If the list has exactly one item, then the first item of the list is returned.
- * If the list has more than one item, then a new Buffer is created.
- *
- * @param list An array of Buffer objects to concatenate
- * @param totalLength Total length of the buffers when concatenated.
- * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
- */
- static concat(list: Buffer[], totalLength?: number): Buffer;
- /**
- * The same as buf1.compare(buf2).
- */
- static compare(buf1: Buffer, buf2: Buffer): number;
- /**
- * Allocates a new buffer of {size} octets.
- *
- * @param size count of octets to allocate.
- * @param fill if specified, buffer will be initialized by calling buf.fill(fill).
- * If parameter is omitted, buffer will be filled with zeros.
- * @param encoding encoding used for call to buf.fill while initalizing
- */
- static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
- /**
- * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
- * of the newly created Buffer are unknown and may contain sensitive data.
- *
- * @param size count of octets to allocate
- */
- static allocUnsafe(size: number): Buffer;
- /**
- * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
- * of the newly created Buffer are unknown and may contain sensitive data.
- *
- * @param size count of octets to allocate
- */
- static allocUnsafeSlow(size: number): Buffer;
- }
-}
\ No newline at end of file
diff --git a/node_modules/readable-stream/node_modules/safe-buffer/index.js b/node_modules/readable-stream/node_modules/safe-buffer/index.js
deleted file mode 100644
index 22438da..0000000
--- a/node_modules/readable-stream/node_modules/safe-buffer/index.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* eslint-disable node/no-deprecated-api */
-var buffer = require('buffer')
-var Buffer = buffer.Buffer
-
-// alternative to using Object.keys for old browsers
-function copyProps (src, dst) {
- for (var key in src) {
- dst[key] = src[key]
- }
-}
-if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
- module.exports = buffer
-} else {
- // Copy properties from require('buffer')
- copyProps(buffer, exports)
- exports.Buffer = SafeBuffer
-}
-
-function SafeBuffer (arg, encodingOrOffset, length) {
- return Buffer(arg, encodingOrOffset, length)
-}
-
-// Copy static methods from Buffer
-copyProps(Buffer, SafeBuffer)
-
-SafeBuffer.from = function (arg, encodingOrOffset, length) {
- if (typeof arg === 'number') {
- throw new TypeError('Argument must not be a number')
- }
- return Buffer(arg, encodingOrOffset, length)
-}
-
-SafeBuffer.alloc = function (size, fill, encoding) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- var buf = Buffer(size)
- if (fill !== undefined) {
- if (typeof encoding === 'string') {
- buf.fill(fill, encoding)
- } else {
- buf.fill(fill)
- }
- } else {
- buf.fill(0)
- }
- return buf
-}
-
-SafeBuffer.allocUnsafe = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return Buffer(size)
-}
-
-SafeBuffer.allocUnsafeSlow = function (size) {
- if (typeof size !== 'number') {
- throw new TypeError('Argument must be a number')
- }
- return buffer.SlowBuffer(size)
-}
diff --git a/node_modules/readable-stream/node_modules/safe-buffer/package.json b/node_modules/readable-stream/node_modules/safe-buffer/package.json
deleted file mode 100644
index 623fbc3..0000000
--- a/node_modules/readable-stream/node_modules/safe-buffer/package.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "name": "safe-buffer",
- "description": "Safer Node.js Buffer API",
- "version": "5.1.2",
- "author": {
- "name": "Feross Aboukhadijeh",
- "email": "feross@feross.org",
- "url": "http://feross.org"
- },
- "bugs": {
- "url": "https://github.com/feross/safe-buffer/issues"
- },
- "devDependencies": {
- "standard": "*",
- "tape": "^4.0.0"
- },
- "homepage": "https://github.com/feross/safe-buffer",
- "keywords": [
- "buffer",
- "buffer allocate",
- "node security",
- "safe",
- "safe-buffer",
- "security",
- "uninitialized"
- ],
- "license": "MIT",
- "main": "index.js",
- "types": "index.d.ts",
- "repository": {
- "type": "git",
- "url": "git://github.com/feross/safe-buffer.git"
- },
- "scripts": {
- "test": "standard && tape test/*.js"
- }
-}
diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json
index 514c178..ade59e7 100644
--- a/node_modules/readable-stream/package.json
+++ b/node_modules/readable-stream/package.json
@@ -1,31 +1,46 @@
{
"name": "readable-stream",
- "version": "2.3.8",
+ "version": "3.6.2",
"description": "Streams3, a user-land copy of the stream library from Node.js",
"main": "readable.js",
+ "engines": {
+ "node": ">= 6"
+ },
"dependencies": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
},
"devDependencies": {
+ "@babel/cli": "^7.2.0",
+ "@babel/core": "^7.2.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.2.0",
+ "airtap": "0.0.9",
"assert": "^1.4.0",
- "babel-polyfill": "^6.9.1",
- "buffer": "^4.9.0",
- "lolex": "^2.3.2",
- "nyc": "^6.4.0",
- "tap": "^0.7.0",
- "tape": "^4.8.0"
+ "bl": "^2.0.0",
+ "deep-strict-equal": "^0.2.0",
+ "events.once": "^2.0.2",
+ "glob": "^7.1.2",
+ "gunzip-maybe": "^1.4.1",
+ "hyperquest": "^2.1.3",
+ "lolex": "^2.6.0",
+ "nyc": "^11.0.0",
+ "pump": "^3.0.0",
+ "rimraf": "^2.6.2",
+ "tap": "^12.0.0",
+ "tape": "^4.9.0",
+ "tar-fs": "^1.16.2",
+ "util-promisify": "^2.1.0"
},
"scripts": {
- "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js",
- "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
+ "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
+ "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap",
+ "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
+ "test-browser-local": "airtap --open --local -- test/browser.js",
"cover": "nyc npm test",
- "report": "nyc report --reporter=lcov"
+ "report": "nyc report --reporter=lcov",
+ "update-browser-errors": "babel -o errors-browser.js errors.js"
},
"repository": {
"type": "git",
@@ -38,9 +53,10 @@
],
"browser": {
"util": false,
+ "worker_threads": false,
+ "./errors": "./errors-browser.js",
"./readable.js": "./readable-browser.js",
- "./writable.js": "./writable-browser.js",
- "./duplex.js": "./duplex-browser.js",
+ "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
"./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
},
"nyc": {
diff --git a/node_modules/readable-stream/passthrough.js b/node_modules/readable-stream/passthrough.js
deleted file mode 100644
index ffd791d..0000000
--- a/node_modules/readable-stream/passthrough.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./readable').PassThrough
diff --git a/node_modules/readable-stream/readable-browser.js b/node_modules/readable-stream/readable-browser.js
index e503725..adbf60d 100644
--- a/node_modules/readable-stream/readable-browser.js
+++ b/node_modules/readable-stream/readable-browser.js
@@ -5,3 +5,5 @@ exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
+exports.finished = require('./lib/internal/streams/end-of-stream.js');
+exports.pipeline = require('./lib/internal/streams/pipeline.js');
diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js
index ec89ec5..9e0ca12 100644
--- a/node_modules/readable-stream/readable.js
+++ b/node_modules/readable-stream/readable.js
@@ -1,13 +1,8 @@
var Stream = require('stream');
if (process.env.READABLE_STREAM === 'disable' && Stream) {
- module.exports = Stream;
- exports = module.exports = Stream.Readable;
- exports.Readable = Stream.Readable;
- exports.Writable = Stream.Writable;
- exports.Duplex = Stream.Duplex;
- exports.Transform = Stream.Transform;
- exports.PassThrough = Stream.PassThrough;
- exports.Stream = Stream;
+ module.exports = Stream.Readable;
+ Object.assign(module.exports, Stream);
+ module.exports.Stream = Stream;
} else {
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
@@ -16,4 +11,6 @@ if (process.env.READABLE_STREAM === 'disable' && Stream) {
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
+ exports.finished = require('./lib/internal/streams/end-of-stream.js');
+ exports.pipeline = require('./lib/internal/streams/pipeline.js');
}
diff --git a/node_modules/readable-stream/transform.js b/node_modules/readable-stream/transform.js
deleted file mode 100644
index b1baba2..0000000
--- a/node_modules/readable-stream/transform.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./readable').Transform
diff --git a/node_modules/readable-stream/writable-browser.js b/node_modules/readable-stream/writable-browser.js
deleted file mode 100644
index ebdde6a..0000000
--- a/node_modules/readable-stream/writable-browser.js
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = require('./lib/_stream_writable.js');
diff --git a/node_modules/readable-stream/writable.js b/node_modules/readable-stream/writable.js
deleted file mode 100644
index 3211a6f..0000000
--- a/node_modules/readable-stream/writable.js
+++ /dev/null
@@ -1,8 +0,0 @@
-var Stream = require("stream")
-var Writable = require("./lib/_stream_writable.js")
-
-if (process.env.READABLE_STREAM === 'disable') {
- module.exports = Stream && Stream.Writable || Writable
-} else {
- module.exports = Writable
-}
diff --git a/node_modules/simple-update-notifier/build/index.js b/node_modules/simple-update-notifier/build/index.js
index 090f9df..d7c3cde 100644
--- a/node_modules/simple-update-notifier/build/index.js
+++ b/node_modules/simple-update-notifier/build/index.js
@@ -7,59 +7,59 @@ var path = require('path');
var fs = require('fs');
var https = require('https');
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global Reflect, Promise */
-
-
-function __awaiter(thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-}
-
-function __generator(thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+
+function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
}
var packageJson = process$1.env.npm_package_json;
diff --git a/node_modules/streamsearch/LICENSE b/node_modules/streamsearch/LICENSE
index 290762e..9ea90e0 100644
--- a/node_modules/streamsearch/LICENSE
+++ b/node_modules/streamsearch/LICENSE
@@ -1,19 +1,19 @@
-Copyright Brian White. All rights reserved.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-sell copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+Copyright Brian White. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
\ No newline at end of file
diff --git a/package-lock.json b/package-lock.json
index 5215544..38f35b9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -17,12 +17,10 @@
"fs": "^0.0.1-security",
"https": "^1.0.0",
"jsonwebtoken": "^9.0.2",
- "multer": "^2.0.0",
-<<<<<<< HEAD
+ "multer": "^2.0.1",
"mysql": "^2.18.1",
"mysql2": "^3.14.1",
-=======
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
+ "nodemailer": "^7.0.3",
"ws": "^8.18.2"
},
"devDependencies": {
@@ -160,7 +158,8 @@
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
- "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="
+ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
+ "license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
@@ -250,16 +249,17 @@
"dev": true
},
"node_modules/concat-stream": {
- "version": "1.6.2",
- "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
- "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
- "node >= 0.8"
+ "node >= 6.0"
],
+ "license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
- "readable-stream": "^2.2.2",
+ "readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
@@ -933,7 +933,6 @@
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
"license": "MIT"
},
-<<<<<<< HEAD
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
@@ -964,8 +963,6 @@
"url": "https://github.com/sponsors/wellwelwel"
}
},
-=======
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -1049,17 +1046,18 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/multer": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.0.tgz",
- "integrity": "sha512-bS8rPZurbAuHGAnApbM9d4h1wSoYqrOqkE+6a64KLMK9yWU7gJXBDDVklKQ3TPi9DRb85cRs6yXaC0+cjxRtRg==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.1.tgz",
+ "integrity": "sha512-Ug8bXeTIUlxurg8xLTEskKShvcKDZALo1THEX5E41pYCD2sCVub5/kIRIGqWNoqV6szyLyQKV6mD4QUrWE5GCQ==",
+ "license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
- "busboy": "^1.0.0",
- "concat-stream": "^1.5.2",
- "mkdirp": "^0.5.4",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "mkdirp": "^0.5.6",
"object-assign": "^4.1.1",
- "type-is": "^1.6.4",
- "xtend": "^4.0.0"
+ "type-is": "^1.6.18",
+ "xtend": "^4.0.2"
},
"engines": {
"node": ">= 10.16.0"
@@ -1189,6 +1187,15 @@
"node": ">= 0.6"
}
},
+ "node_modules/nodemailer": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.3.tgz",
+ "integrity": "sha512-Ajq6Sz1x7cIK3pN6KesGTah+1gnwMnx5gKl3piQlQQE/PwyJ4Mbc8is2psWYxK3RJTVeqsDaCv8ZzXLCDHMTZw==",
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
"node_modules/nodemon": {
"version": "3.1.10",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
@@ -1357,24 +1364,19 @@
}
},
"node_modules/readable-stream": {
- "version": "2.3.8",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
- "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "license": "MIT",
"dependencies": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
}
},
- "node_modules/readable-stream/node_modules/safe-buffer": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
- },
"node_modules/readdirp": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@@ -1657,7 +1659,8 @@
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
- "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="
+ "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
+ "license": "MIT"
},
"node_modules/undefsafe": {
"version": "2.0.5",
@@ -1890,13 +1893,13 @@
"dev": true
},
"concat-stream": {
- "version": "1.6.2",
- "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
- "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
+ "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"requires": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
- "readable-stream": "^2.2.2",
+ "readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
@@ -2383,7 +2386,6 @@
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg=="
},
-<<<<<<< HEAD
"long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
@@ -2399,8 +2401,6 @@
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.2.tgz",
"integrity": "sha512-Nv9KddBcQSlQopmBHXSsZVY5xsdlZkdH/Iey0BlcBYggMd4two7cZnKOK9vmy3nY0O5RGH99z1PCeTpPqszUYg=="
},
-=======
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
"math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -2457,17 +2457,17 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"multer": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.0.tgz",
- "integrity": "sha512-bS8rPZurbAuHGAnApbM9d4h1wSoYqrOqkE+6a64KLMK9yWU7gJXBDDVklKQ3TPi9DRb85cRs6yXaC0+cjxRtRg==",
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/multer/-/multer-2.0.1.tgz",
+ "integrity": "sha512-Ug8bXeTIUlxurg8xLTEskKShvcKDZALo1THEX5E41pYCD2sCVub5/kIRIGqWNoqV6szyLyQKV6mD4QUrWE5GCQ==",
"requires": {
"append-field": "^1.0.0",
- "busboy": "^1.0.0",
- "concat-stream": "^1.5.2",
- "mkdirp": "^0.5.4",
+ "busboy": "^1.6.0",
+ "concat-stream": "^2.0.0",
+ "mkdirp": "^0.5.6",
"object-assign": "^4.1.1",
- "type-is": "^1.6.4",
- "xtend": "^4.0.0"
+ "type-is": "^1.6.18",
+ "xtend": "^4.0.2"
},
"dependencies": {
"media-typer": {
@@ -2567,6 +2567,11 @@
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
"integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="
},
+ "nodemailer": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.3.tgz",
+ "integrity": "sha512-Ajq6Sz1x7cIK3pN6KesGTah+1gnwMnx5gKl3piQlQQE/PwyJ4Mbc8is2psWYxK3RJTVeqsDaCv8ZzXLCDHMTZw=="
+ },
"nodemon": {
"version": "3.1.10",
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.10.tgz",
@@ -2683,24 +2688,13 @@
}
},
"readable-stream": {
- "version": "2.3.8",
- "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
- "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"requires": {
- "core-util-is": "~1.0.0",
- "inherits": "~2.0.3",
- "isarray": "~1.0.0",
- "process-nextick-args": "~2.0.0",
- "safe-buffer": "~5.1.1",
- "string_decoder": "~1.1.1",
- "util-deprecate": "~1.0.1"
- },
- "dependencies": {
- "safe-buffer": {
- "version": "5.1.2",
- "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
- "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
- }
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
}
},
"readdirp": {
diff --git a/package.json b/package.json
index 655e2f6..72667e8 100644
--- a/package.json
+++ b/package.json
@@ -20,12 +20,10 @@
"fs": "^0.0.1-security",
"https": "^1.0.0",
"jsonwebtoken": "^9.0.2",
- "multer": "^2.0.0",
-<<<<<<< HEAD
+ "multer": "^2.0.1",
"mysql": "^2.18.1",
"mysql2": "^3.14.1",
-=======
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
+ "nodemailer": "^7.0.3",
"ws": "^8.18.2"
},
"devDependencies": {
diff --git a/routes/apiRoutes.js b/routes/apiRoutes.js
index 905a15b..f075009 100644
--- a/routes/apiRoutes.js
+++ b/routes/apiRoutes.js
@@ -1,10 +1,10 @@
-const express = require('express');
-const { getContacts, getCallList } = require('../controllers/apiController');
-const router = express.Router();
-const multer = require('multer');
-const upload = multer();
-
-router.get('/contacts', getContacts);
-router.post('/calls',upload.none(), getCallList);
-
-module.exports = router;
+const express = require('express');
+const { getContacts, getCallList } = require('../controllers/apiController');
+const router = express.Router();
+const multer = require('multer');
+const upload = multer();
+
+router.get('/contacts', getContacts);
+router.post('/calls',upload.none(), getCallList);
+
+module.exports = router;
diff --git a/routes/authRoutes.js b/routes/authRoutes.js
new file mode 100644
index 0000000..4dde100
--- /dev/null
+++ b/routes/authRoutes.js
@@ -0,0 +1,12 @@
+const express = require('express');
+const router = express.Router();
+const multer = require('multer');
+const { signupUserRequest } = require('../controllers/authController');
+
+// Init multer memory storage (or just for form parsing)
+const upload = multer();
+
+// POST /signup - with multipart/form-data, no files
+router.post('/signup', upload.none(), signupUserRequest);
+
+module.exports = router;
diff --git a/routes/userRoutes.js b/routes/userRoutes.js
index e664151..94bc3ec 100644
--- a/routes/userRoutes.js
+++ b/routes/userRoutes.js
@@ -1,20 +1,13 @@
-const express = require('express');
-const router = express.Router();
-<<<<<<< HEAD
-const { getUserData, getNotifications,updateAlerts} = require('../controllers/userController');
-=======
-const { getUserData, getNotifications} = require('../controllers/userController');
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
-const multer = require('multer');
-const upload = multer(); // No disk storage, just for parsing fields
-
-
-router.post('/data', upload.none(), getUserData);
-router.post('/notifications',upload.none(),getNotifications)
-<<<<<<< HEAD
-router.post('/acknowledge',upload.none(),updateAlerts)
-
-=======
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
-
-module.exports = router;
+const express = require('express');
+const router = express.Router();
+const { getUserData, getNotifications,updateAlerts} = require('../controllers/userController');
+const multer = require('multer');
+const upload = multer(); // No disk storage, just for parsing fields
+
+
+router.post('/data', upload.none(), getUserData);
+router.post('/notifications',upload.none(),getNotifications)
+router.post('/acknowledge',upload.none(),updateAlerts)
+
+
+module.exports = router;
diff --git a/script/encrypt.js b/script/encrypt.js
index 718587b..ae7f9de 100644
--- a/script/encrypt.js
+++ b/script/encrypt.js
@@ -1,3 +1,3 @@
-// Run this as a one-time utility
-const { encrypt } = require('../services/encryptionService');
-console.log(encrypt('actual api key'));
+// Run this as a one-time utility
+const { encrypt } = require('../services/encryptionService');
+console.log(encrypt('actual api key'));
diff --git a/services/apiService.js b/services/apiService.js
index e9f4baa..697ea25 100644
--- a/services/apiService.js
+++ b/services/apiService.js
@@ -1,66 +1,66 @@
-const axios = require('axios');
-const config = require('../config/config.json');
-const { decrypt } = require('./encryptionService');
-const db = require('../config/database'); // import this at the top of your file
-
-async function fetchContacts() {
- try {
- const decryptedApiKey = decrypt(config.encryptedApiKey);
- const response = await axios.get('https://rest.gohighlevel.com/v1/contacts/', {
- headers: {
- Authorization: `Bearer ${decryptedApiKey}`
- }
- });
- return response.data;
- } catch (error) {
- throw new Error(`API Error: ${error.message}`);
- }
-}
-
-async function fetchCallList({ assignedTo, call_id }) {
-
- try {
- if (!assignedTo && !call_id) {
- throw new Error('Either assignedTo or call_id must be provided.');
- }
-
- const decryptedApiKey = decrypt(config.encryptedApiKey_callList);
-
- const axiosConfig = {
- method: 'post',
- maxBodyLength: Infinity,
- url: 'https://api.retellai.com/v2/list-calls',
- headers: {
- 'Authorization': `Bearer ${decryptedApiKey}`,
- 'Content-Type': 'application/json'
- },
- data: {} // Include any required data here
- };
-
- const response = await axios.request(axiosConfig);
-
- // Adjust the path to the data based on the actual response structure
- const calls = response.data.calls || response.data; // Replace 'calls' with the correct property if different
-
- let filteredCalls = [];
-
- if (assignedTo) {
- filteredCalls = calls.filter(call =>
- String(call.retell_llm_dynamic_variables?.assignedTo) === String(assignedTo)
- );
- } else if (call_id) {
- filteredCalls = calls.filter(call =>
- String(call.call_id) === String(call_id)
- );
- }
-
- return filteredCalls;
- } catch (error) {
- throw new Error(`API Error: ${error.message}`);
- }
-}
-
-
-
-
-module.exports = { fetchContacts, fetchCallList };
+const axios = require('axios');
+const config = require('../config/config.json');
+const { decrypt } = require('./encryptionService');
+const db = require('../config/database'); // import this at the top of your file
+
+async function fetchContacts() {
+ try {
+ const decryptedApiKey = decrypt(config.encryptedApiKey);
+ const response = await axios.get('https://rest.gohighlevel.com/v1/contacts/', {
+ headers: {
+ Authorization: `Bearer ${decryptedApiKey}`
+ }
+ });
+ return response.data;
+ } catch (error) {
+ throw new Error(`API Error: ${error.message}`);
+ }
+}
+
+async function fetchCallList({ assignedTo, call_id }) {
+
+ try {
+ if (!assignedTo && !call_id) {
+ throw new Error('Either assignedTo or call_id must be provided.');
+ }
+
+ const decryptedApiKey = decrypt(config.encryptedApiKey_callList);
+
+ const axiosConfig = {
+ method: 'post',
+ maxBodyLength: Infinity,
+ url: 'https://api.retellai.com/v2/list-calls',
+ headers: {
+ 'Authorization': `Bearer ${decryptedApiKey}`,
+ 'Content-Type': 'application/json'
+ },
+ data: {} // Include any required data here
+ };
+
+ const response = await axios.request(axiosConfig);
+
+ // Adjust the path to the data based on the actual response structure
+ const calls = response.data.calls || response.data; // Replace 'calls' with the correct property if different
+
+ let filteredCalls = [];
+
+ if (assignedTo) {
+ filteredCalls = calls.filter(call =>
+ String(call.retell_llm_dynamic_variables?.assignedTo) === String(assignedTo)
+ );
+ } else if (call_id) {
+ filteredCalls = calls.filter(call =>
+ String(call.call_id) === String(call_id)
+ );
+ }
+
+ return filteredCalls;
+ } catch (error) {
+ throw new Error(`API Error: ${error.message}`);
+ }
+}
+
+
+
+
+module.exports = { fetchContacts, fetchCallList };
diff --git a/services/encryptionService.js b/services/encryptionService.js
index 95d6f9f..a8e7af0 100644
--- a/services/encryptionService.js
+++ b/services/encryptionService.js
@@ -1,24 +1,24 @@
-const crypto = require('crypto');
-require('dotenv').config();
-
-const algorithm = 'aes-256-cbc';
-const key = crypto.createHash('sha256').update(process.env.ENCRYPTION_SECRET).digest();
-const ivLength = 16;
-
-function encrypt(text) {
- const iv = crypto.randomBytes(ivLength);
- const cipher = crypto.createCipheriv(algorithm, key, iv);
- const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
- return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
-}
-
-function decrypt(encryptedText) {
- const [ivHex, encryptedHex] = encryptedText.split(':');
- const iv = Buffer.from(ivHex, 'hex');
- const encrypted = Buffer.from(encryptedHex, 'hex');
- const decipher = crypto.createDecipheriv(algorithm, key, iv);
- const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
- return decrypted.toString('utf8');
-}
-
+const crypto = require('crypto');
+require('dotenv').config();
+
+const algorithm = 'aes-256-cbc';
+const key = crypto.createHash('sha256').update(process.env.ENCRYPTION_SECRET).digest();
+const ivLength = 16;
+
+function encrypt(text) {
+ const iv = crypto.randomBytes(ivLength);
+ const cipher = crypto.createCipheriv(algorithm, key, iv);
+ const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
+ return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
+}
+
+function decrypt(encryptedText) {
+ const [ivHex, encryptedHex] = encryptedText.split(':');
+ const iv = Buffer.from(ivHex, 'hex');
+ const encrypted = Buffer.from(encryptedHex, 'hex');
+ const decipher = crypto.createDecipheriv(algorithm, key, iv);
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
+ return decrypted.toString('utf8');
+}
+
module.exports = { encrypt, decrypt };
\ No newline at end of file
diff --git a/services/webSocket.js b/services/webSocket.js
index 6522eeb..1095cf9 100644
--- a/services/webSocket.js
+++ b/services/webSocket.js
@@ -1,4 +1,3 @@
-<<<<<<< HEAD
// const WebSocket = require('ws');
// const jwt = require('jsonwebtoken');
// const db = require('../config/database');
@@ -239,36 +238,15 @@ async function sendUserAlertHistory(ws, userId) {
/**
* Initializes the WebSocket server.
-=======
-const WebSocket = require('ws');
-const jwt = require('jsonwebtoken');
-
-// user_id -> websocket mapping
-const userSocketMap = new Map();
-
-// Keep track of connection attempts to prevent rapid reconnection loops
-const connectionAttempts = new WeakMap();
-
-/**
- * Initializes the WebSocket server.
- * @param {https.Server} server - The HTTP/HTTPS server instance from Express.
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
*/
function initWebSocket(server) {
const wss = new WebSocket.Server({
server,
clientTracking: true,
-<<<<<<< HEAD
-=======
- // Consider adding ping/pong for connection health
- // clientTracking: true,
- // maxPayload: 100 * 1024 * 1024, // 100MB
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
});
console.log('WebSocket server initialized');
-<<<<<<< HEAD
wss.on('connection', (ws, req) => {
const location = url.parse(req.url, true);
const token = location.query?.token;
@@ -323,39 +301,10 @@ function initWebSocket(server) {
}, 30000);
ws.on('pong', () => { ws.isAlive = true; });
-=======
- // Handle new connections
- wss.on('connection', (ws, req) => {
- const clientIp = req.socket.remoteAddress;
- // console.log(`New WebSocket connection from ${clientIp}`);
-
- // Set up ping/pong to detect dead connections
- let isAlive = true;
- ws.isAlive = true;
-
- const pingInterval = setInterval(() => {
- if (!isAlive) {
- console.log('Terminating dead connection');
- return ws.terminate();
- }
-
- isAlive = false;
- try {
- ws.ping(() => {});
- } catch (e) {
- console.error('Error sending ping:', e);
- }
- }, 30000);
-
- ws.on('pong', () => {
- isAlive = true;
- });
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
ws.on('message', (message) => {
try {
const data = JSON.parse(message);
-<<<<<<< HEAD
if (data.type === 'MESSAGE') {
ws.send(JSON.stringify({
type: 'MESSAGE_RECEIVED',
@@ -382,98 +331,10 @@ function initWebSocket(server) {
console.error('WebSocket error:', error);
if (ws.readyState === WebSocket.OPEN) {
ws.close(1011, 'Internal server error');
-=======
-
- // Handle different message types
- if (data.type === 'MESSAGE') {
- console.log(`Received message: ${data.content}`);
- ws.send(JSON.stringify({
- type: 'MESSAGE_RECEIVED',
- content: data.content,
- timestamp: new Date().toISOString()
- }));
- return;
- }
-
- // Handle authentication with token
- const { token } = data;
-
- if (!token) {
- ws.send(JSON.stringify({
- type: 'ERROR',
- error: 'No token provided',
- timestamp: new Date().toISOString()
- }));
- return;
- }
-
- const decoded = jwt.decode(token); // Use jwt.verify() in production
- const userId = decoded?.claims?.user_id;
-
- if (!userId) {
- ws.send(JSON.stringify({
- type: 'ERROR',
- error: 'Invalid token or missing user_id in claims',
- timestamp: new Date().toISOString()
- }));
- return;
- }
-
- console.log(`Authenticated user: ${userId}`);
-
- // Store the WebSocket connection with the user ID
- userSocketMap.set(userId, ws);
-
- // Store user ID in the WebSocket object for cleanup
- ws.userId = userId;
-
- ws.send(JSON.stringify({
- type: 'CONNECTED',
- message: `Connected as ${userId}`,
- timestamp: new Date().toISOString()
- }));
-
- } catch (err) {
- console.error('WebSocket message error:', err);
- try {
- ws.send(JSON.stringify({
- type: 'ERROR',
- error: 'Invalid message format or processing error',
- timestamp: new Date().toISOString()
- }));
- } catch (sendErr) {
- console.error('Failed to send error message:', sendErr);
- }
- }
- });
-
- // Handle connection close
- ws.on('close', () => {
- // console.log(`WebSocket closed for ${ws.userId || 'unknown user'}`);
- if (ws.userId) {
- userSocketMap.delete(ws.userId);
- }
- clearInterval(pingInterval);
- });
-
- // Handle errors
- ws.on('error', (error) => {
- console.error('WebSocket error:', error);
- if (ws.readyState === WebSocket.OPEN) {
- try {
- ws.close(1011, 'Internal server error');
- } catch (e) {
- // Ignore errors during close
- }
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
}
});
});
-<<<<<<< HEAD
-=======
- // Handle server errors
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
wss.on('error', (error) => {
console.error('WebSocket server error:', error);
});
@@ -482,7 +343,6 @@ function initWebSocket(server) {
}
/**
-<<<<<<< HEAD
* Send a real-time alert to a specific user via WebSocket.
*/
async function sendAlertToUser(userId, alert) {
@@ -507,15 +367,6 @@ async function sendAlertToUser(userId, alert) {
console.error("Database operation failed:", err);
}
-=======
- * Sends an alert to a user via WebSocket.
- * @param {string} userId - The target user ID.
- * @param {string|object} alert - The alert message or payload.
- * @returns {boolean} - Success/failure.
- */
-function sendAlertToUser(userId, alert) {
- console.log("socket -- invoked---")
->>>>>>> 3d47f2d539024e036b3db88eb1e020180e656065
const ws = userSocketMap.get(userId);
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'ALERT', payload: alert }));
diff --git a/utils/mailer.js b/utils/mailer.js
new file mode 100644
index 0000000..fa3762b
--- /dev/null
+++ b/utils/mailer.js
@@ -0,0 +1,150 @@
+const nodemailer = require('nodemailer');
+
+// Configure Gmail transporter
+const transporter = nodemailer.createTransport({
+ service: 'gmail',
+ auth: {
+ user: process.env.GMAIL_USER, // your Gmail
+ pass: process.env.GMAIL_PASS // Gmail App Password
+ }
+});
+
+// In-memory rate limit tracker: email → [timestamps]
+const emailSendLog = new Map();
+
+// Helper: Can we send this email?
+function canSendEmail(email) {
+ const now = Date.now();
+ const windowTime = 24 * 60 * 60 * 1000; // 24 hours in ms
+ const limit = 2;
+
+ const timestamps = emailSendLog.get(email) || [];
+ const recent = timestamps.filter(ts => now - ts < windowTime);
+
+ if (recent.length >= limit) return false;
+
+ recent.push(now);
+ emailSendLog.set(email, recent);
+ return true;
+}
+
+// Send acknowledgment email to the user
+async function sendAcknowledgementEmail(firstName, email) {
+ console.log('Sending acknowledgement email to user:', firstName, email);
+
+ const mailOptions = {
+ from: `"GuardianCall.ai" <${process.env.GMAIL_USER}>`,
+ to: email,
+ subject: 'Welcome to GuardianCall.ai!',
+ html: `
+
+
+
+ Welcome to GuardianCall.ai
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+ Welcome, ${firstName}!
+
+ Thank you for signing up with GuardianCall.ai. Your account registration request has been received and is currently under review.
+
+
+ Once your account is approved, you'll receive a confirmation email with next steps and login instructions.
+
+
+ In the meantime, feel free to explore more about what GuardianCall.ai can do for you.
+
+ Warm regards, The GuardianCall.ai Team
+ |
+
+
+ |
+ © 2025 GuardianCall.ai. All rights reserved.
+ |
+
+
+ |
+
+
+
+`
+ };
+
+ return transporter.sendMail(mailOptions);
+}
+
+// Send signup request to admin + acknowledgment to user
+async function sendSignupEmail(email, firstName, lastName, password) {
+ if (!canSendEmail(email)) {
+ const error = new Error(`Rate limit exceeded for ${email}. Please try again later.`);
+ error.status = 429; // Too Many Requests
+ throw error;
+ }
+
+ const mailOptions = {
+ from: `"GuardianCall.ai" <${process.env.GMAIL_USER}>`,
+ to: process.env.gmail_admin,
+ subject: 'Signup request',
+ html: `
+
+
+
+ New Signup Request - GuardianCall
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+ New Signup Request Received
+ Hi Admin,
+ A new user has requested signup on GuardianCall.ai.
+ User Details:
+
+ - First Name: ${firstName}
+ - Last Name: ${lastName}
+ - Email: ${email}
+ - Suggested Password: ${password}
+
+ Please verify the information and take appropriate action.
+ Cheers, The GuardianCall.ai Team
+ |
+
+
+ |
+ © 2025 GuardianCall.ai. All rights reserved.
+ |
+
+
+ |
+
+
+
+`
+ };
+
+ // Send both emails
+ await sendAcknowledgementEmail(firstName, email);
+ return transporter.sendMail(mailOptions);
+}
+
+
+
+module.exports = { sendSignupEmail };