diff --git a/README.md b/README.md index 28160f5..bf7f2fb 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ console.log(lamdenWallet) ``` ### Create a new BIP39 / BIP 32 compatible wallet -- **BIP39** = 24 seed phrase +- **BIP39** = 24 word mnemonic - **BIP32** = derivation path ```javascript @@ -49,26 +49,28 @@ console.log(lamdenWallet) sk: 'a6b72cb3d1160c26f9f39a8f1d4a3c7c0da2ac59d193b66ac5f919ec77f28915', vk: '53d016586ce35c5f6ea581cadf4693dd2850621dfad6a2261e8dd311c83e11d5', derivationIndex: 0, + seed: '3626c59ee5bce833a8bf5024645eb10415b39c6f9fd0ff0fb1b00b8ca9fd6ff4b8a0ed7077296cdaff1b955f03318f244dfd3fead404d93f11a3f301c0e3e1c6', mnemonic: 'evidence rifle behave normal duty mean junk chicken salute relief raw chunk region ocean guard swarm taste toy loop ozone spell crumble apart echo' } ``` ### Restore a BIP39 / BIP 32 compatible wallet -- **BIP39** = 24 seed phrase +- **BIP39** = 24 word mnemonic - **BIP32** = derivation path ```javascript -const mnemonic = 'evidence rifle behave normal duty mean junk chicken salute relief raw chunk region ocean guard swarm taste toy loop ozone spell crumble apart echo' +const seed = '3626c59ee5bce833a8bf5024645eb10415b39c6f9fd0ff0fb1b00b8ca9fd6ff4b8a0ed7077296cdaff1b955f03318f244dfd3fead404d93f11a3f301c0e3e1c6' const derivationIndex = 0; -let lamdenWallet = Lamden.wallet.new_wallet_bip39(mnemonic, derivationIndex) +let lamdenWallet = Lamden.wallet.new_wallet_bip39(seed, derivationIndex) console.log(lamdenWallet) >> { sk: 'a6b72cb3d1160c26f9f39a8f1d4a3c7c0da2ac59d193b66ac5f919ec77f28915', vk: '53d016586ce35c5f6ea581cadf4693dd2850621dfad6a2261e8dd311c83e11d5', derivationIndex: 0, - mnemonic: 'evidence rifle behave normal duty mean junk chicken salute relief raw chunk region ocean guard swarm taste toy loop ozone spell crumble apart echo' + seed: null, + mnemonic: null } ``` diff --git a/dist/cjs/lamden.js b/dist/cjs/lamden.js new file mode 100644 index 0000000..36a9b04 --- /dev/null +++ b/dist/cjs/lamden.js @@ -0,0 +1,8741 @@ +'use strict'; + +var nacl = require('tweetnacl'); +var bip39 = require('bip39'); +var bip32 = require('ed25519-hd-key'); +var Stream = require('stream'); +var http = require('http'); +var Url = require('url'); +var https = require('https'); +var zlib = require('zlib'); +var buffer = require('buffer'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var nacl__default = /*#__PURE__*/_interopDefaultLegacy(nacl); +var bip39__namespace = /*#__PURE__*/_interopNamespace(bip39); +var bip32__default = /*#__PURE__*/_interopDefaultLegacy(bip32); +var Stream__default = /*#__PURE__*/_interopDefaultLegacy(Stream); +var http__default = /*#__PURE__*/_interopDefaultLegacy(http); +var Url__default = /*#__PURE__*/_interopDefaultLegacy(Url); +var https__default = /*#__PURE__*/_interopDefaultLegacy(https); +var zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var dist = {exports: {}}; + +(function (module, exports) { +(function (global, factory) { + factory(exports) ; +}(commonjsGlobal, (function (exports) { + class ValidateTypes { + constructor() {} + + getType(value) { + return Object.prototype.toString.call(value); + } + + getClassName(value) { + try { + return value.constructor.name; + } catch (e) {} + + return this.getType(value); + } //Validation functions + + + isObject(value) { + if (this.getType(value) === "[object Object]") return true; + return false; + } + + isFunction(value) { + if (this.getType(value) === "[object Function]") return true; + return false; + } + + isString(value) { + if (this.getType(value) === "[object String]") return true; + return false; + } + + isBoolean(value) { + if (this.getType(value) === "[object Boolean]") return true; + return false; + } + + isArray(value) { + if (this.getType(value) === "[object Array]") return true; + return false; + } + + isNumber(value) { + if (this.getType(value) === "[object Number]") return true; + return false; + } + + isInteger(value) { + if (this.getType(value) === "[object Number]" && Number.isInteger(value)) return true; + return false; + } + + isRegEx(value) { + if (this.getType(value) === "[object RegExp]") return true; + return false; + } + + isStringHex(value) { + if (!this.isStringWithValue(value)) return false; + let hexRegEx = /([0-9]|[a-f])/gim; + return (value.match(hexRegEx) || []).length === value.length; + } + + hasKeys(value, keys) { + if (keys.map(key => key in value).includes(false)) return false; + return true; + } + + isStringWithValue(value) { + if (this.isString(value) && value !== '') return true; + return false; + } + + isObjectWithKeys(value) { + if (this.isObject(value) && Object.keys(value).length > 0) return true; + return false; + } + + isArrayWithValues(value) { + if (this.isArray(value) && value.length > 0) return true; + return false; + } + + isSpecificClass(value, className) { + if (!this.isObject(value)) return false; + if (this.getClassName(value) !== className) return false; + return true; + } + + } + + class AssertTypes { + constructor() { + this.validate = new ValidateTypes(); + } //Validation functions + + + isObject(value) { + if (!this.validate.isObject(value)) { + throw new TypeError(`Expected type [object Object] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isFunction(value) { + if (!this.validate.isFunction(value)) { + throw new TypeError(`Expected type [object Function] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isString(value) { + if (!this.validate.isString(value)) { + throw new TypeError(`Expected type [object String] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isBoolean(value) { + if (!this.validate.isBoolean(value)) { + throw new TypeError(`Expected type [object Boolean] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isArray(value) { + if (!this.validate.isArray(value)) { + throw new TypeError(`Expected type [object Array] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isNumber(value) { + if (!this.validate.isNumber(value)) { + throw new TypeError(`Expected type [object Number] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isInteger(value) { + if (!this.validate.isInteger(value)) { + throw new TypeError(`Expected "${value}" to be an integer but got non-integer value`); + } + + return true; + } + + isRegEx(value) { + if (!this.validate.isRegEx(value)) { + throw new TypeError(`Expected type [object RegExp] but got ${this.validate.getType(value)}`); + } + + return true; + } + + isStringHex(value) { + if (!this.validate.isStringHex(value)) { + throw new TypeError(`Expected "${value}" to be hex but got non-hex value`); + } + + return true; + } + + hasKeys(value, keys) { + if (!this.validate.hasKeys(value, keys)) { + throw new TypeError(`Provided object does not contain all keys ${JSON.stringify(keys)}`); + } + + return true; + } + + isStringWithValue(value) { + if (!this.validate.isStringWithValue(value)) { + throw new TypeError(`Expected "${value}" to be [object String] and not empty`); + } + + return true; + } + + isObjectWithKeys(value) { + if (!this.validate.isObjectWithKeys(value)) { + throw new TypeError(`Expected "${value}" to be [object Object] and have keys`); + } + + return true; + } + + isArrayWithValues(value) { + if (!this.validate.isArrayWithValues(value)) { + throw new TypeError(`Expected "${value}" to be [object Array] and not empty`); + } + + return true; + } + + isSpecificClass(value, className) { + if (!this.validate.isSpecificClass(value, className)) { + throw new TypeError(`Expected Object Class to be "${className}" but got ${this.validate.getClassName(value)}`); + } + + return true; + } + + } + + const validateTypes = new ValidateTypes(); + const assertTypes = new AssertTypes(); + + exports.assertTypes = assertTypes; + exports.validateTypes = validateTypes; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +}(dist, dist.exports)); + +var validators = /*@__PURE__*/getDefaultExportFromCjs(dist.exports); + +var cryptojs = {}; + +var core = {}; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ + +/** + * CryptoJS core components. + */ +var CryptoJS$8 = CryptoJS$8 || (function (Math, undefined$1) { + /** + * CryptoJS namespace. + */ + var C = {}; + + /** + * Library namespace. + */ + var C_lib = C.lib = {}; + + /** + * Base object for prototypal inheritance. + */ + var Base = C_lib.Base = (function () { + function F() {} + + return { + /** + * Creates a new object that inherits from this object. + * + * @param {Object} overrides Properties to copy into the new object. + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * field: 'value', + * + * method: function () { + * } + * }); + */ + extend: function (overrides) { + // Spawn + F.prototype = this; + var subtype = new F(); + + // Augment + if (overrides) { + subtype.mixIn(overrides); + } + + // Create default initializer + if (!subtype.hasOwnProperty('init')) { + subtype.init = function () { + subtype.$super.init.apply(this, arguments); + }; + } + + // Initializer's prototype is the subtype object + subtype.init.prototype = subtype; + + // Reference supertype + subtype.$super = this; + + return subtype; + }, + + /** + * Extends this object and runs the init method. + * Arguments to create() will be passed to init(). + * + * @return {Object} The new object. + * + * @static + * + * @example + * + * var instance = MyType.create(); + */ + create: function () { + var instance = this.extend(); + instance.init.apply(instance, arguments); + + return instance; + }, + + /** + * Initializes a newly created object. + * Override this method to add some logic when your objects are created. + * + * @example + * + * var MyType = CryptoJS.lib.Base.extend({ + * init: function () { + * // ... + * } + * }); + */ + init: function () { + }, + + /** + * Copies properties into this object. + * + * @param {Object} properties The properties to mix in. + * + * @example + * + * MyType.mixIn({ + * field: 'value' + * }); + */ + mixIn: function (properties) { + for (var propertyName in properties) { + if (properties.hasOwnProperty(propertyName)) { + this[propertyName] = properties[propertyName]; + } + } + + // IE won't copy toString using the loop above + if (properties.hasOwnProperty('toString')) { + this.toString = properties.toString; + } + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = instance.clone(); + */ + clone: function () { + return this.init.prototype.extend(this); + } + }; + }()); + + /** + * An array of 32-bit words. + * + * @property {Array} words The array of 32-bit words. + * @property {number} sigBytes The number of significant bytes in this word array. + */ + var WordArray = C_lib.WordArray = Base.extend({ + /** + * Initializes a newly created word array. + * + * @param {Array} words (Optional) An array of 32-bit words. + * @param {number} sigBytes (Optional) The number of significant bytes in the words. + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.create(); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); + * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); + */ + init: function (words, sigBytes) { + words = this.words = words || []; + + if (sigBytes != undefined$1) { + this.sigBytes = sigBytes; + } else { + this.sigBytes = words.length * 4; + } + }, + + /** + * Converts this word array to a string. + * + * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex + * + * @return {string} The stringified word array. + * + * @example + * + * var string = wordArray + ''; + * var string = wordArray.toString(); + * var string = wordArray.toString(CryptoJS.enc.Utf8); + */ + toString: function (encoder) { + return (encoder || Hex).stringify(this); + }, + + /** + * Concatenates a word array to this word array. + * + * @param {WordArray} wordArray The word array to append. + * + * @return {WordArray} This word array. + * + * @example + * + * wordArray1.concat(wordArray2); + */ + concat: function (wordArray) { + // Shortcuts + var thisWords = this.words; + var thatWords = wordArray.words; + var thisSigBytes = this.sigBytes; + var thatSigBytes = wordArray.sigBytes; + + // Clamp excess bits + this.clamp(); + + // Concat + if (thisSigBytes % 4) { + // Copy one byte at a time + for (var i = 0; i < thatSigBytes; i++) { + var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); + } + } else if (thatWords.length > 0xffff) { + // Copy one word at a time + for (var i = 0; i < thatSigBytes; i += 4) { + thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; + } + } else { + // Copy all words at once + thisWords.push.apply(thisWords, thatWords); + } + this.sigBytes += thatSigBytes; + + // Chainable + return this; + }, + + /** + * Removes insignificant bits. + * + * @example + * + * wordArray.clamp(); + */ + clamp: function () { + // Shortcuts + var words = this.words; + var sigBytes = this.sigBytes; + + // Clamp + words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); + words.length = Math.ceil(sigBytes / 4); + }, + + /** + * Creates a copy of this word array. + * + * @return {WordArray} The clone. + * + * @example + * + * var clone = wordArray.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone.words = this.words.slice(0); + + return clone; + }, + + /** + * Creates a word array filled with random bytes. + * + * @param {number} nBytes The number of random bytes to generate. + * + * @return {WordArray} The random word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.lib.WordArray.random(16); + */ + random: function (nBytes) { + var words = []; + for (var i = 0; i < nBytes; i += 4) { + words.push((Math.random() * 0x100000000) | 0); + } + + return new WordArray.init(words, nBytes); + } + }); + + /** + * Encoder namespace. + */ + var C_enc = C.enc = {}; + + /** + * Hex encoding strategy. + */ + var Hex = C_enc.Hex = { + /** + * Converts a word array to a hex string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The hex string. + * + * @static + * + * @example + * + * var hexString = CryptoJS.enc.Hex.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var hexChars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + hexChars.push((bite >>> 4).toString(16)); + hexChars.push((bite & 0x0f).toString(16)); + } + + return hexChars.join(''); + }, + + /** + * Converts a hex string to a word array. + * + * @param {string} hexStr The hex string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Hex.parse(hexString); + */ + parse: function (hexStr) { + // Shortcut + var hexStrLength = hexStr.length; + + // Convert + var words = []; + for (var i = 0; i < hexStrLength; i += 2) { + words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); + } + + return new WordArray.init(words, hexStrLength / 2); + } + }; + + /** + * Latin1 encoding strategy. + */ + var Latin1 = C_enc.Latin1 = { + /** + * Converts a word array to a Latin1 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Latin1 string. + * + * @static + * + * @example + * + * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + + // Convert + var latin1Chars = []; + for (var i = 0; i < sigBytes; i++) { + var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + latin1Chars.push(String.fromCharCode(bite)); + } + + return latin1Chars.join(''); + }, + + /** + * Converts a Latin1 string to a word array. + * + * @param {string} latin1Str The Latin1 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); + */ + parse: function (latin1Str) { + // Shortcut + var latin1StrLength = latin1Str.length; + + // Convert + var words = []; + for (var i = 0; i < latin1StrLength; i++) { + words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); + } + + return new WordArray.init(words, latin1StrLength); + } + }; + + /** + * UTF-8 encoding strategy. + */ + var Utf8 = C_enc.Utf8 = { + /** + * Converts a word array to a UTF-8 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The UTF-8 string. + * + * @static + * + * @example + * + * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); + */ + stringify: function (wordArray) { + try { + return decodeURIComponent(escape(Latin1.stringify(wordArray))); + } catch (e) { + throw new Error('Malformed UTF-8 data'); + } + }, + + /** + * Converts a UTF-8 string to a word array. + * + * @param {string} utf8Str The UTF-8 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); + */ + parse: function (utf8Str) { + return Latin1.parse(unescape(encodeURIComponent(utf8Str))); + } + }; + + /** + * Abstract buffered block algorithm template. + * + * The property blockSize must be implemented in a concrete subtype. + * + * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 + */ + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ + /** + * Resets this block algorithm's data buffer to its initial state. + * + * @example + * + * bufferedBlockAlgorithm.reset(); + */ + reset: function () { + // Initial values + this._data = new WordArray.init(); + this._nDataBytes = 0; + }, + + /** + * Adds new data to this block algorithm's buffer. + * + * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. + * + * @example + * + * bufferedBlockAlgorithm._append('data'); + * bufferedBlockAlgorithm._append(wordArray); + */ + _append: function (data) { + // Convert string to WordArray, else assume WordArray already + if (typeof data == 'string') { + data = Utf8.parse(data); + } + + // Append + this._data.concat(data); + this._nDataBytes += data.sigBytes; + }, + + /** + * Processes available data blocks. + * + * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. + * + * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. + * + * @return {WordArray} The processed data. + * + * @example + * + * var processedData = bufferedBlockAlgorithm._process(); + * var processedData = bufferedBlockAlgorithm._process(!!'flush'); + */ + _process: function (doFlush) { + // Shortcuts + var data = this._data; + var dataWords = data.words; + var dataSigBytes = data.sigBytes; + var blockSize = this.blockSize; + var blockSizeBytes = blockSize * 4; + + // Count blocks ready + var nBlocksReady = dataSigBytes / blockSizeBytes; + if (doFlush) { + // Round up to include partial blocks + nBlocksReady = Math.ceil(nBlocksReady); + } else { + // Round down to include only full blocks, + // less the number of blocks that must remain in the buffer + nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); + } + + // Count words ready + var nWordsReady = nBlocksReady * blockSize; + + // Count bytes ready + var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); + + // Process blocks + if (nWordsReady) { + for (var offset = 0; offset < nWordsReady; offset += blockSize) { + // Perform concrete-algorithm logic + this._doProcessBlock(dataWords, offset); + } + + // Remove processed words + var processedWords = dataWords.splice(0, nWordsReady); + data.sigBytes -= nBytesReady; + } + + // Return processed words + return new WordArray.init(processedWords, nBytesReady); + }, + + /** + * Creates a copy of this object. + * + * @return {Object} The clone. + * + * @example + * + * var clone = bufferedBlockAlgorithm.clone(); + */ + clone: function () { + var clone = Base.clone.call(this); + clone._data = this._data.clone(); + + return clone; + }, + + _minBufferSize: 0 + }); + + /** + * Abstract hasher template. + * + * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) + */ + C_lib.Hasher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + */ + cfg: Base.extend(), + + /** + * Initializes a newly created hasher. + * + * @param {Object} cfg (Optional) The configuration options to use for this hash computation. + * + * @example + * + * var hasher = CryptoJS.algo.SHA256.create(); + */ + init: function (cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Set initial values + this.reset(); + }, + + /** + * Resets this hasher to its initial state. + * + * @example + * + * hasher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-hasher logic + this._doReset(); + }, + + /** + * Updates this hasher with a message. + * + * @param {WordArray|string} messageUpdate The message to append. + * + * @return {Hasher} This hasher. + * + * @example + * + * hasher.update('message'); + * hasher.update(wordArray); + */ + update: function (messageUpdate) { + // Append + this._append(messageUpdate); + + // Update the hash + this._process(); + + // Chainable + return this; + }, + + /** + * Finalizes the hash computation. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} messageUpdate (Optional) A final message update. + * + * @return {WordArray} The hash. + * + * @example + * + * var hash = hasher.finalize(); + * var hash = hasher.finalize('message'); + * var hash = hasher.finalize(wordArray); + */ + finalize: function (messageUpdate) { + // Final message update + if (messageUpdate) { + this._append(messageUpdate); + } + + // Perform concrete-hasher logic + var hash = this._doFinalize(); + + return hash; + }, + + blockSize: 512/32, + + /** + * Creates a shortcut function to a hasher's object interface. + * + * @param {Hasher} hasher The hasher to create a helper for. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); + */ + _createHelper: function (hasher) { + return function (message, cfg) { + return new hasher.init(cfg).finalize(message); + }; + }, + + /** + * Creates a shortcut function to the HMAC's object interface. + * + * @param {Hasher} hasher The hasher to use in this HMAC helper. + * + * @return {Function} The shortcut function. + * + * @static + * + * @example + * + * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); + */ + _createHmacHelper: function (hasher) { + return function (message, key) { + return new C_algo.HMAC.init(hasher, key).finalize(message); + }; + } + }); + + /** + * Algorithm namespace. + */ + var C_algo = C.algo = {}; + + return C; +}(Math)); + +core.CryptoJS = CryptoJS$8; + +var CryptoJS$7 = core.CryptoJS; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + var C = CryptoJS$7; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var C_enc = C.enc; + + /** + * Base64 encoding strategy. + */ + C_enc.Base64 = { + /** + * Converts a word array to a Base64 string. + * + * @param {WordArray} wordArray The word array. + * + * @return {string} The Base64 string. + * + * @static + * + * @example + * + * var base64String = CryptoJS.enc.Base64.stringify(wordArray); + */ + stringify: function (wordArray) { + // Shortcuts + var words = wordArray.words; + var sigBytes = wordArray.sigBytes; + var map = this._map; + + // Clamp excess bits + wordArray.clamp(); + + // Convert + var base64Chars = []; + for (var i = 0; i < sigBytes; i += 3) { + var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; + var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; + + var triplet = (byte1 << 16) | (byte2 << 8) | byte3; + + for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { + base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); + } + } + + // Add padding + var paddingChar = map.charAt(64); + if (paddingChar) { + while (base64Chars.length % 4) { + base64Chars.push(paddingChar); + } + } + + return base64Chars.join(''); + }, + + /** + * Converts a Base64 string to a word array. + * + * @param {string} base64Str The Base64 string. + * + * @return {WordArray} The word array. + * + * @static + * + * @example + * + * var wordArray = CryptoJS.enc.Base64.parse(base64String); + */ + parse: function (base64Str) { + // Shortcuts + var base64StrLength = base64Str.length; + var map = this._map; + + // Ignore padding + var paddingChar = map.charAt(64); + if (paddingChar) { + var paddingIndex = base64Str.indexOf(paddingChar); + if (paddingIndex != -1) { + base64StrLength = paddingIndex; + } + } + + // Convert + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); + var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); + words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + + return WordArray.create(words, nBytes); + }, + + _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' + }; +}()); + +var CryptoJS$6 = core.CryptoJS; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function (Math) { + // Shortcuts + var C = CryptoJS$6; + var C_lib = C.lib; + var WordArray = C_lib.WordArray; + var Hasher = C_lib.Hasher; + var C_algo = C.algo; + + // Constants table + var T = []; + + // Compute constants + (function () { + for (var i = 0; i < 64; i++) { + T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; + } + }()); + + /** + * MD5 hash algorithm. + */ + var MD5 = C_algo.MD5 = Hasher.extend({ + _doReset: function () { + this._hash = new WordArray.init([ + 0x67452301, 0xefcdab89, + 0x98badcfe, 0x10325476 + ]); + }, + + _doProcessBlock: function (M, offset) { + // Swap endian + for (var i = 0; i < 16; i++) { + // Shortcuts + var offset_i = offset + i; + var M_offset_i = M[offset_i]; + + M[offset_i] = ( + (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | + (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) + ); + } + + // Shortcuts + var H = this._hash.words; + + var M_offset_0 = M[offset + 0]; + var M_offset_1 = M[offset + 1]; + var M_offset_2 = M[offset + 2]; + var M_offset_3 = M[offset + 3]; + var M_offset_4 = M[offset + 4]; + var M_offset_5 = M[offset + 5]; + var M_offset_6 = M[offset + 6]; + var M_offset_7 = M[offset + 7]; + var M_offset_8 = M[offset + 8]; + var M_offset_9 = M[offset + 9]; + var M_offset_10 = M[offset + 10]; + var M_offset_11 = M[offset + 11]; + var M_offset_12 = M[offset + 12]; + var M_offset_13 = M[offset + 13]; + var M_offset_14 = M[offset + 14]; + var M_offset_15 = M[offset + 15]; + + // Working varialbes + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + + // Computation + a = FF(a, b, c, d, M_offset_0, 7, T[0]); + d = FF(d, a, b, c, M_offset_1, 12, T[1]); + c = FF(c, d, a, b, M_offset_2, 17, T[2]); + b = FF(b, c, d, a, M_offset_3, 22, T[3]); + a = FF(a, b, c, d, M_offset_4, 7, T[4]); + d = FF(d, a, b, c, M_offset_5, 12, T[5]); + c = FF(c, d, a, b, M_offset_6, 17, T[6]); + b = FF(b, c, d, a, M_offset_7, 22, T[7]); + a = FF(a, b, c, d, M_offset_8, 7, T[8]); + d = FF(d, a, b, c, M_offset_9, 12, T[9]); + c = FF(c, d, a, b, M_offset_10, 17, T[10]); + b = FF(b, c, d, a, M_offset_11, 22, T[11]); + a = FF(a, b, c, d, M_offset_12, 7, T[12]); + d = FF(d, a, b, c, M_offset_13, 12, T[13]); + c = FF(c, d, a, b, M_offset_14, 17, T[14]); + b = FF(b, c, d, a, M_offset_15, 22, T[15]); + + a = GG(a, b, c, d, M_offset_1, 5, T[16]); + d = GG(d, a, b, c, M_offset_6, 9, T[17]); + c = GG(c, d, a, b, M_offset_11, 14, T[18]); + b = GG(b, c, d, a, M_offset_0, 20, T[19]); + a = GG(a, b, c, d, M_offset_5, 5, T[20]); + d = GG(d, a, b, c, M_offset_10, 9, T[21]); + c = GG(c, d, a, b, M_offset_15, 14, T[22]); + b = GG(b, c, d, a, M_offset_4, 20, T[23]); + a = GG(a, b, c, d, M_offset_9, 5, T[24]); + d = GG(d, a, b, c, M_offset_14, 9, T[25]); + c = GG(c, d, a, b, M_offset_3, 14, T[26]); + b = GG(b, c, d, a, M_offset_8, 20, T[27]); + a = GG(a, b, c, d, M_offset_13, 5, T[28]); + d = GG(d, a, b, c, M_offset_2, 9, T[29]); + c = GG(c, d, a, b, M_offset_7, 14, T[30]); + b = GG(b, c, d, a, M_offset_12, 20, T[31]); + + a = HH(a, b, c, d, M_offset_5, 4, T[32]); + d = HH(d, a, b, c, M_offset_8, 11, T[33]); + c = HH(c, d, a, b, M_offset_11, 16, T[34]); + b = HH(b, c, d, a, M_offset_14, 23, T[35]); + a = HH(a, b, c, d, M_offset_1, 4, T[36]); + d = HH(d, a, b, c, M_offset_4, 11, T[37]); + c = HH(c, d, a, b, M_offset_7, 16, T[38]); + b = HH(b, c, d, a, M_offset_10, 23, T[39]); + a = HH(a, b, c, d, M_offset_13, 4, T[40]); + d = HH(d, a, b, c, M_offset_0, 11, T[41]); + c = HH(c, d, a, b, M_offset_3, 16, T[42]); + b = HH(b, c, d, a, M_offset_6, 23, T[43]); + a = HH(a, b, c, d, M_offset_9, 4, T[44]); + d = HH(d, a, b, c, M_offset_12, 11, T[45]); + c = HH(c, d, a, b, M_offset_15, 16, T[46]); + b = HH(b, c, d, a, M_offset_2, 23, T[47]); + + a = II(a, b, c, d, M_offset_0, 6, T[48]); + d = II(d, a, b, c, M_offset_7, 10, T[49]); + c = II(c, d, a, b, M_offset_14, 15, T[50]); + b = II(b, c, d, a, M_offset_5, 21, T[51]); + a = II(a, b, c, d, M_offset_12, 6, T[52]); + d = II(d, a, b, c, M_offset_3, 10, T[53]); + c = II(c, d, a, b, M_offset_10, 15, T[54]); + b = II(b, c, d, a, M_offset_1, 21, T[55]); + a = II(a, b, c, d, M_offset_8, 6, T[56]); + d = II(d, a, b, c, M_offset_15, 10, T[57]); + c = II(c, d, a, b, M_offset_6, 15, T[58]); + b = II(b, c, d, a, M_offset_13, 21, T[59]); + a = II(a, b, c, d, M_offset_4, 6, T[60]); + d = II(d, a, b, c, M_offset_11, 10, T[61]); + c = II(c, d, a, b, M_offset_2, 15, T[62]); + b = II(b, c, d, a, M_offset_9, 21, T[63]); + + // Intermediate hash value + H[0] = (H[0] + a) | 0; + H[1] = (H[1] + b) | 0; + H[2] = (H[2] + c) | 0; + H[3] = (H[3] + d) | 0; + }, + + _doFinalize: function () { + // Shortcuts + var data = this._data; + var dataWords = data.words; + + var nBitsTotal = this._nDataBytes * 8; + var nBitsLeft = data.sigBytes * 8; + + // Add padding + dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); + + var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); + var nBitsTotalL = nBitsTotal; + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( + (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | + (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) + ); + dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( + (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | + (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) + ); + + data.sigBytes = (dataWords.length + 1) * 4; + + // Hash final blocks + this._process(); + + // Shortcuts + var hash = this._hash; + var H = hash.words; + + // Swap endian + for (var i = 0; i < 4; i++) { + // Shortcut + var H_i = H[i]; + + H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | + (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); + } + + // Return final computed hash + return hash; + }, + + clone: function () { + var clone = Hasher.clone.call(this); + clone._hash = this._hash.clone(); + + return clone; + } + }); + + function FF(a, b, c, d, x, s, t) { + var n = a + ((b & c) | (~b & d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function GG(a, b, c, d, x, s, t) { + var n = a + ((b & d) | (c & ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function HH(a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + function II(a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + x + t; + return ((n << s) | (n >>> (32 - s))) + b; + } + + /** + * Shortcut function to the hasher's object interface. + * + * @param {WordArray|string} message The message to hash. + * + * @return {WordArray} The hash. + * + * @static + * + * @example + * + * var hash = CryptoJS.MD5('message'); + * var hash = CryptoJS.MD5(wordArray); + */ + C.MD5 = Hasher._createHelper(MD5); + + /** + * Shortcut function to the HMAC's object interface. + * + * @param {WordArray|string} message The message to hash. + * @param {WordArray|string} key The secret key. + * + * @return {WordArray} The HMAC. + * + * @static + * + * @example + * + * var hmac = CryptoJS.HmacMD5(message, key); + */ + C.HmacMD5 = Hasher._createHmacHelper(MD5); +}(Math)); + +var CryptoJS$5 = core.CryptoJS; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + var C = CryptoJS$5; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var C_algo = C.algo; + var MD5 = C_algo.MD5; + + /** + * This key derivation function is meant to conform with EVP_BytesToKey. + * www.openssl.org/docs/crypto/EVP_BytesToKey.html + */ + var EvpKDF = C_algo.EvpKDF = Base.extend({ + /** + * Configuration options. + * + * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) + * @property {Hasher} hasher The hash algorithm to use. Default: MD5 + * @property {number} iterations The number of iterations to perform. Default: 1 + */ + cfg: Base.extend({ + keySize: 128/32, + hasher: MD5, + iterations: 1 + }), + + /** + * Initializes a newly created key derivation function. + * + * @param {Object} cfg (Optional) The configuration options to use for the derivation. + * + * @example + * + * var kdf = CryptoJS.algo.EvpKDF.create(); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); + * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); + */ + init: function (cfg) { + this.cfg = this.cfg.extend(cfg); + }, + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * + * @return {WordArray} The derived key. + * + * @example + * + * var key = kdf.compute(password, salt); + */ + compute: function (password, salt) { + // Shortcut + var cfg = this.cfg; + + // Init hasher + var hasher = cfg.hasher.create(); + + // Initial values + var derivedKey = WordArray.create(); + + // Shortcuts + var derivedKeyWords = derivedKey.words; + var keySize = cfg.keySize; + var iterations = cfg.iterations; + + // Generate key + while (derivedKeyWords.length < keySize) { + if (block) { + hasher.update(block); + } + var block = hasher.update(password).finalize(salt); + hasher.reset(); + + // Iterations + for (var i = 1; i < iterations; i++) { + block = hasher.finalize(block); + hasher.reset(); + } + + derivedKey.concat(block); + } + derivedKey.sigBytes = keySize * 4; + + return derivedKey; + } + }); + + /** + * Derives a key from a password. + * + * @param {WordArray|string} password The password. + * @param {WordArray|string} salt A salt. + * @param {Object} cfg (Optional) The configuration options to use for this computation. + * + * @return {WordArray} The derived key. + * + * @static + * + * @example + * + * var key = CryptoJS.EvpKDF(password, salt); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); + * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); + */ + C.EvpKDF = function (password, salt, cfg) { + return EvpKDF.create(cfg).compute(password, salt); + }; +}()); + +var CryptoJS$4 = core.CryptoJS; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** + * Cipher core components. + */ +CryptoJS$4.lib.Cipher || (function (undefined$1) { + // Shortcuts + var C = CryptoJS$4; + var C_lib = C.lib; + var Base = C_lib.Base; + var WordArray = C_lib.WordArray; + var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; + var C_enc = C.enc; + C_enc.Utf8; + var Base64 = C_enc.Base64; + var C_algo = C.algo; + var EvpKDF = C_algo.EvpKDF; + + /** + * Abstract base cipher template. + * + * @property {number} keySize This cipher's key size. Default: 4 (128 bits) + * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) + * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. + * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. + */ + var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ + /** + * Configuration options. + * + * @property {WordArray} iv The IV to use for this operation. + */ + cfg: Base.extend(), + + /** + * Creates this cipher in encryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); + */ + createEncryptor: function (key, cfg) { + return this.create(this._ENC_XFORM_MODE, key, cfg); + }, + + /** + * Creates this cipher in decryption mode. + * + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {Cipher} A cipher instance. + * + * @static + * + * @example + * + * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); + */ + createDecryptor: function (key, cfg) { + return this.create(this._DEC_XFORM_MODE, key, cfg); + }, + + /** + * Initializes a newly created cipher. + * + * @param {number} xformMode Either the encryption or decryption transormation mode constant. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @example + * + * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); + */ + init: function (xformMode, key, cfg) { + // Apply config defaults + this.cfg = this.cfg.extend(cfg); + + // Store transform mode and key + this._xformMode = xformMode; + this._key = key; + + // Set initial values + this.reset(); + }, + + /** + * Resets this cipher to its initial state. + * + * @example + * + * cipher.reset(); + */ + reset: function () { + // Reset data buffer + BufferedBlockAlgorithm.reset.call(this); + + // Perform concrete-cipher logic + this._doReset(); + }, + + /** + * Adds data to be encrypted or decrypted. + * + * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. + * + * @return {WordArray} The data after processing. + * + * @example + * + * var encrypted = cipher.process('data'); + * var encrypted = cipher.process(wordArray); + */ + process: function (dataUpdate) { + // Append + this._append(dataUpdate); + + // Process available blocks + return this._process(); + }, + + /** + * Finalizes the encryption or decryption process. + * Note that the finalize operation is effectively a destructive, read-once operation. + * + * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. + * + * @return {WordArray} The data after final processing. + * + * @example + * + * var encrypted = cipher.finalize(); + * var encrypted = cipher.finalize('data'); + * var encrypted = cipher.finalize(wordArray); + */ + finalize: function (dataUpdate) { + // Final data update + if (dataUpdate) { + this._append(dataUpdate); + } + + // Perform concrete-cipher logic + var finalProcessedData = this._doFinalize(); + + return finalProcessedData; + }, + + keySize: 128/32, + + ivSize: 128/32, + + _ENC_XFORM_MODE: 1, + + _DEC_XFORM_MODE: 2, + + /** + * Creates shortcut functions to a cipher's object interface. + * + * @param {Cipher} cipher The cipher to create a helper for. + * + * @return {Object} An object with encrypt and decrypt shortcut functions. + * + * @static + * + * @example + * + * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); + */ + _createHelper: (function () { + function selectCipherStrategy(key) { + if (typeof key == 'string') { + return PasswordBasedCipher; + } else { + return SerializableCipher; + } + } + + return function (cipher) { + return { + encrypt: function (message, key, cfg) { + return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); + }, + + decrypt: function (ciphertext, key, cfg) { + return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); + } + }; + }; + }()) + }); + + /** + * Abstract base stream cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) + */ + C_lib.StreamCipher = Cipher.extend({ + _doFinalize: function () { + // Process partial blocks + var finalProcessedBlocks = this._process(!!'flush'); + + return finalProcessedBlocks; + }, + + blockSize: 1 + }); + + /** + * Mode namespace. + */ + var C_mode = C.mode = {}; + + /** + * Abstract base block cipher mode template. + */ + var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ + /** + * Creates this mode for encryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); + */ + createEncryptor: function (cipher, iv) { + return this.Encryptor.create(cipher, iv); + }, + + /** + * Creates this mode for decryption. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @static + * + * @example + * + * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); + */ + createDecryptor: function (cipher, iv) { + return this.Decryptor.create(cipher, iv); + }, + + /** + * Initializes a newly created mode. + * + * @param {Cipher} cipher A block cipher instance. + * @param {Array} iv The IV words. + * + * @example + * + * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); + */ + init: function (cipher, iv) { + this._cipher = cipher; + this._iv = iv; + } + }); + + /** + * Cipher Block Chaining mode. + */ + var CBC = C_mode.CBC = (function () { + /** + * Abstract base CBC mode. + */ + var CBC = BlockCipherMode.extend(); + + /** + * CBC encryptor. + */ + CBC.Encryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // XOR and encrypt + xorBlock.call(this, words, offset, blockSize); + cipher.encryptBlock(words, offset); + + // Remember this block to use with next block + this._prevBlock = words.slice(offset, offset + blockSize); + } + }); + + /** + * CBC decryptor. + */ + CBC.Decryptor = CBC.extend({ + /** + * Processes the data block at offset. + * + * @param {Array} words The data words to operate on. + * @param {number} offset The offset where the block starts. + * + * @example + * + * mode.processBlock(data.words, offset); + */ + processBlock: function (words, offset) { + // Shortcuts + var cipher = this._cipher; + var blockSize = cipher.blockSize; + + // Remember this block to use with next block + var thisBlock = words.slice(offset, offset + blockSize); + + // Decrypt and XOR + cipher.decryptBlock(words, offset); + xorBlock.call(this, words, offset, blockSize); + + // This block becomes the previous block + this._prevBlock = thisBlock; + } + }); + + function xorBlock(words, offset, blockSize) { + // Shortcut + var iv = this._iv; + + // Choose mixing block + if (iv) { + var block = iv; + + // Remove IV for subsequent blocks + this._iv = undefined$1; + } else { + var block = this._prevBlock; + } + + // XOR blocks + for (var i = 0; i < blockSize; i++) { + words[offset + i] ^= block[i]; + } + } + + return CBC; + }()); + + /** + * Padding namespace. + */ + var C_pad = C.pad = {}; + + /** + * PKCS #5/7 padding strategy. + */ + var Pkcs7 = C_pad.Pkcs7 = { + /** + * Pads data using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to pad. + * @param {number} blockSize The multiple that the data should be padded to. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.pad(wordArray, 4); + */ + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Count padding bytes + var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; + + // Create padding word + var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; + + // Create padding + var paddingWords = []; + for (var i = 0; i < nPaddingBytes; i += 4) { + paddingWords.push(paddingWord); + } + var padding = WordArray.create(paddingWords, nPaddingBytes); + + // Add padding + data.concat(padding); + }, + + /** + * Unpads data that had been padded using the algorithm defined in PKCS #5/7. + * + * @param {WordArray} data The data to unpad. + * + * @static + * + * @example + * + * CryptoJS.pad.Pkcs7.unpad(wordArray); + */ + unpad: function (data) { + // Get number of padding bytes from last byte + var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; + + // Remove padding + data.sigBytes -= nPaddingBytes; + } + }; + + /** + * Abstract base block cipher template. + * + * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) + */ + C_lib.BlockCipher = Cipher.extend({ + /** + * Configuration options. + * + * @property {Mode} mode The block mode to use. Default: CBC + * @property {Padding} padding The padding strategy to use. Default: Pkcs7 + */ + cfg: Cipher.cfg.extend({ + mode: CBC, + padding: Pkcs7 + }), + + reset: function () { + // Reset cipher + Cipher.reset.call(this); + + // Shortcuts + var cfg = this.cfg; + var iv = cfg.iv; + var mode = cfg.mode; + + // Reset block mode + if (this._xformMode == this._ENC_XFORM_MODE) { + var modeCreator = mode.createEncryptor; + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + var modeCreator = mode.createDecryptor; + + // Keep at least one block in the buffer for unpadding + this._minBufferSize = 1; + } + this._mode = modeCreator.call(mode, this, iv && iv.words); + }, + + _doProcessBlock: function (words, offset) { + this._mode.processBlock(words, offset); + }, + + _doFinalize: function () { + // Shortcut + var padding = this.cfg.padding; + + // Finalize + if (this._xformMode == this._ENC_XFORM_MODE) { + // Pad data + padding.pad(this._data, this.blockSize); + + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { + // Process final blocks + var finalProcessedBlocks = this._process(!!'flush'); + + // Unpad data + padding.unpad(finalProcessedBlocks); + } + + return finalProcessedBlocks; + }, + + blockSize: 128/32 + }); + + /** + * A collection of cipher parameters. + * + * @property {WordArray} ciphertext The raw ciphertext. + * @property {WordArray} key The key to this ciphertext. + * @property {WordArray} iv The IV used in the ciphering operation. + * @property {WordArray} salt The salt used with a key derivation function. + * @property {Cipher} algorithm The cipher algorithm. + * @property {Mode} mode The block mode used in the ciphering operation. + * @property {Padding} padding The padding scheme used in the ciphering operation. + * @property {number} blockSize The block size of the cipher. + * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. + */ + var CipherParams = C_lib.CipherParams = Base.extend({ + /** + * Initializes a newly created cipher params object. + * + * @param {Object} cipherParams An object with any of the possible cipher parameters. + * + * @example + * + * var cipherParams = CryptoJS.lib.CipherParams.create({ + * ciphertext: ciphertextWordArray, + * key: keyWordArray, + * iv: ivWordArray, + * salt: saltWordArray, + * algorithm: CryptoJS.algo.AES, + * mode: CryptoJS.mode.CBC, + * padding: CryptoJS.pad.PKCS7, + * blockSize: 4, + * formatter: CryptoJS.format.OpenSSL + * }); + */ + init: function (cipherParams) { + this.mixIn(cipherParams); + }, + + /** + * Converts this cipher params object to a string. + * + * @param {Format} formatter (Optional) The formatting strategy to use. + * + * @return {string} The stringified cipher params. + * + * @throws Error If neither the formatter nor the default formatter is set. + * + * @example + * + * var string = cipherParams + ''; + * var string = cipherParams.toString(); + * var string = cipherParams.toString(CryptoJS.format.OpenSSL); + */ + toString: function (formatter) { + return (formatter || this.formatter).stringify(this); + } + }); + + /** + * Format namespace. + */ + var C_format = C.format = {}; + + /** + * OpenSSL formatting strategy. + */ + var OpenSSLFormatter = C_format.OpenSSL = { + /** + * Converts a cipher params object to an OpenSSL-compatible string. + * + * @param {CipherParams} cipherParams The cipher params object. + * + * @return {string} The OpenSSL-compatible string. + * + * @static + * + * @example + * + * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); + */ + stringify: function (cipherParams) { + // Shortcuts + var ciphertext = cipherParams.ciphertext; + var salt = cipherParams.salt; + + // Format + if (salt) { + var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); + } else { + var wordArray = ciphertext; + } + + return wordArray.toString(Base64); + }, + + /** + * Converts an OpenSSL-compatible string to a cipher params object. + * + * @param {string} openSSLStr The OpenSSL-compatible string. + * + * @return {CipherParams} The cipher params object. + * + * @static + * + * @example + * + * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); + */ + parse: function (openSSLStr) { + // Parse base64 + var ciphertext = Base64.parse(openSSLStr); + + // Shortcut + var ciphertextWords = ciphertext.words; + + // Test for salt + if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { + // Extract salt + var salt = WordArray.create(ciphertextWords.slice(2, 4)); + + // Remove salt from ciphertext + ciphertextWords.splice(0, 4); + ciphertext.sigBytes -= 16; + } + + return CipherParams.create({ ciphertext: ciphertext, salt: salt }); + } + }; + + /** + * A cipher wrapper that returns ciphertext as a serializable cipher params object. + */ + var SerializableCipher = C_lib.SerializableCipher = Base.extend({ + /** + * Configuration options. + * + * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL + */ + cfg: Base.extend({ + format: OpenSSLFormatter + }), + + /** + * Encrypts a message. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); + * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Encrypt + var encryptor = cipher.createEncryptor(key, cfg); + var ciphertext = encryptor.finalize(message); + + // Shortcut + var cipherCfg = encryptor.cfg; + + // Create and return serializable cipher params + return CipherParams.create({ + ciphertext: ciphertext, + key: key, + iv: cipherCfg.iv, + algorithm: cipher, + mode: cipherCfg.mode, + padding: cipherCfg.padding, + blockSize: cipher.blockSize, + formatter: cfg.format + }); + }, + + /** + * Decrypts serialized ciphertext. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {WordArray} key The key. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, key, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Decrypt + var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); + + return plaintext; + }, + + /** + * Converts serialized ciphertext to CipherParams, + * else assumed CipherParams already and returns ciphertext unchanged. + * + * @param {CipherParams|string} ciphertext The ciphertext. + * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. + * + * @return {CipherParams} The unserialized ciphertext. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); + */ + _parse: function (ciphertext, format) { + if (typeof ciphertext == 'string') { + return format.parse(ciphertext, this); + } else { + return ciphertext; + } + } + }); + + /** + * Key derivation function namespace. + */ + var C_kdf = C.kdf = {}; + + /** + * OpenSSL key derivation function. + */ + var OpenSSLKdf = C_kdf.OpenSSL = { + /** + * Derives a key and IV from a password. + * + * @param {string} password The password to derive from. + * @param {number} keySize The size in words of the key to generate. + * @param {number} ivSize The size in words of the IV to generate. + * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. + * + * @return {CipherParams} A cipher params object with the key, IV, and salt. + * + * @static + * + * @example + * + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); + * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); + */ + execute: function (password, keySize, ivSize, salt) { + // Generate random salt + if (!salt) { + salt = WordArray.random(64/8); + } + + // Derive key and IV + var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); + + // Separate key and IV + var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); + key.sigBytes = keySize * 4; + + // Return params + return CipherParams.create({ key: key, iv: iv, salt: salt }); + } + }; + + /** + * A serializable cipher wrapper that derives the key from a password, + * and returns ciphertext as a serializable cipher params object. + */ + var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ + /** + * Configuration options. + * + * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL + */ + cfg: SerializableCipher.cfg.extend({ + kdf: OpenSSLKdf + }), + + /** + * Encrypts a message using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {WordArray|string} message The message to encrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {CipherParams} A cipher params object. + * + * @static + * + * @example + * + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); + * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); + */ + encrypt: function (cipher, message, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Encrypt + var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); + + // Mix in derived params + ciphertext.mixIn(derivedParams); + + return ciphertext; + }, + + /** + * Decrypts serialized ciphertext using a password. + * + * @param {Cipher} cipher The cipher algorithm to use. + * @param {CipherParams|string} ciphertext The ciphertext to decrypt. + * @param {string} password The password. + * @param {Object} cfg (Optional) The configuration options to use for this operation. + * + * @return {WordArray} The plaintext. + * + * @static + * + * @example + * + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); + * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); + */ + decrypt: function (cipher, ciphertext, password, cfg) { + // Apply config defaults + cfg = this.cfg.extend(cfg); + + // Convert string to CipherParams + ciphertext = this._parse(ciphertext, cfg.format); + + // Derive key and other params + var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); + + // Add IV to config + cfg.iv = derivedParams.iv; + + // Decrypt + var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); + + return plaintext; + } + }); +}()); + +var CryptoJS$3 = core.CryptoJS; + +/* +CryptoJS v3.1.2 +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function () { + // Shortcuts + var C = CryptoJS$3; + var C_lib = C.lib; + var BlockCipher = C_lib.BlockCipher; + var C_algo = C.algo; + + // Lookup tables + var SBOX = []; + var INV_SBOX = []; + var SUB_MIX_0 = []; + var SUB_MIX_1 = []; + var SUB_MIX_2 = []; + var SUB_MIX_3 = []; + var INV_SUB_MIX_0 = []; + var INV_SUB_MIX_1 = []; + var INV_SUB_MIX_2 = []; + var INV_SUB_MIX_3 = []; + + // Compute lookup tables + (function () { + // Compute double table + var d = []; + for (var i = 0; i < 256; i++) { + if (i < 128) { + d[i] = i << 1; + } else { + d[i] = (i << 1) ^ 0x11b; + } + } + + // Walk GF(2^8) + var x = 0; + var xi = 0; + for (var i = 0; i < 256; i++) { + // Compute sbox + var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); + sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; + SBOX[x] = sx; + INV_SBOX[sx] = x; + + // Compute multiplication + var x2 = d[x]; + var x4 = d[x2]; + var x8 = d[x4]; + + // Compute sub bytes, mix columns tables + var t = (d[sx] * 0x101) ^ (sx * 0x1010100); + SUB_MIX_0[x] = (t << 24) | (t >>> 8); + SUB_MIX_1[x] = (t << 16) | (t >>> 16); + SUB_MIX_2[x] = (t << 8) | (t >>> 24); + SUB_MIX_3[x] = t; + + // Compute inv sub bytes, inv mix columns tables + var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); + INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); + INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); + INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); + INV_SUB_MIX_3[sx] = t; + + // Compute next counter + if (!x) { + x = xi = 1; + } else { + x = x2 ^ d[d[d[x8 ^ x2]]]; + xi ^= d[d[xi]]; + } + } + }()); + + // Precomputed Rcon lookup + var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; + + /** + * AES block cipher algorithm. + */ + var AES = C_algo.AES = BlockCipher.extend({ + _doReset: function () { + // Shortcuts + var key = this._key; + var keyWords = key.words; + var keySize = key.sigBytes / 4; + + // Compute number of rounds + var nRounds = this._nRounds = keySize + 6; + + // Compute number of key schedule rows + var ksRows = (nRounds + 1) * 4; + + // Compute key schedule + var keySchedule = this._keySchedule = []; + for (var ksRow = 0; ksRow < ksRows; ksRow++) { + if (ksRow < keySize) { + keySchedule[ksRow] = keyWords[ksRow]; + } else { + var t = keySchedule[ksRow - 1]; + + if (!(ksRow % keySize)) { + // Rot word + t = (t << 8) | (t >>> 24); + + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + + // Mix Rcon + t ^= RCON[(ksRow / keySize) | 0] << 24; + } else if (keySize > 6 && ksRow % keySize == 4) { + // Sub word + t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; + } + + keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; + } + } + + // Compute inv key schedule + var invKeySchedule = this._invKeySchedule = []; + for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { + var ksRow = ksRows - invKsRow; + + if (invKsRow % 4) { + var t = keySchedule[ksRow]; + } else { + var t = keySchedule[ksRow - 4]; + } + + if (invKsRow < 4 || ksRow <= 4) { + invKeySchedule[invKsRow] = t; + } else { + invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ + INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; + } + } + }, + + encryptBlock: function (M, offset) { + this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); + }, + + decryptBlock: function (M, offset) { + // Swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + + this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); + + // Inv swap 2nd and 4th rows + var t = M[offset + 1]; + M[offset + 1] = M[offset + 3]; + M[offset + 3] = t; + }, + + _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { + // Shortcut + var nRounds = this._nRounds; + + // Get input, add round key + var s0 = M[offset] ^ keySchedule[0]; + var s1 = M[offset + 1] ^ keySchedule[1]; + var s2 = M[offset + 2] ^ keySchedule[2]; + var s3 = M[offset + 3] ^ keySchedule[3]; + + // Key schedule row counter + var ksRow = 4; + + // Rounds + for (var round = 1; round < nRounds; round++) { + // Shift rows, sub bytes, mix columns, add round key + var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; + var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; + var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; + var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; + + // Update state + s0 = t0; + s1 = t1; + s2 = t2; + s3 = t3; + } + + // Shift rows, sub bytes, add round key + var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; + var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; + var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; + var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; + + // Set output + M[offset] = t0; + M[offset + 1] = t1; + M[offset + 2] = t2; + M[offset + 3] = t3; + }, + + keySize: 256/32 + }); + + /** + * Shortcut functions to the cipher's object interface. + * + * @example + * + * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); + * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); + */ + C.AES = BlockCipher._createHelper(AES); +}()); + +var jsonformatter = {}; + +var CryptoJS$2 = core.CryptoJS; + +// create custom json serialization format +var JsonFormatter$2 = { + stringify: function (cipherParams) { + // create json object with ciphertext + var jsonObj = { + ct: cipherParams.ciphertext.toString(CryptoJS$2.enc.Base64) + }; + + // optionally add iv and salt + if (cipherParams.iv) { + jsonObj.iv = cipherParams.iv.toString(); + } + + if (cipherParams.salt) { + jsonObj.s = cipherParams.salt.toString(); + } + + // stringify json object + return JSON.stringify(jsonObj) + }, + + parse: function (jsonStr) { + // parse json string + var jsonObj = JSON.parse(jsonStr); + + // extract ciphertext from json object, and create cipher params object + var cipherParams = CryptoJS$2.lib.CipherParams.create({ + ciphertext: CryptoJS$2.enc.Base64.parse(jsonObj.ct) + }); + + // optionally extract iv and salt + if (jsonObj.iv) { + cipherParams.iv = CryptoJS$2.enc.Hex.parse(jsonObj.iv); + } + + if (jsonObj.s) { + cipherParams.salt = CryptoJS$2.enc.Hex.parse(jsonObj.s); + } + + return cipherParams; + } +}; + +jsonformatter.JsonFormatter = JsonFormatter$2; + +var CryptoJS$1 = core.CryptoJS; + + + + + +var JsonFormatter$1 = jsonformatter.JsonFormatter; + +cryptojs.CryptoJS = CryptoJS$1; +cryptojs.JsonFormatter = JsonFormatter$1; + +const { CryptoJS, JsonFormatter } = cryptojs; +const { validateTypes: validateTypes$5, assertTypes: assertTypes$1 } = validators; + +/** + * Encrypt a Javascript object with a string password + * The object passed must pass JSON.stringify or the method will fail. + * + * @param {string} password A password to encrypt the object with + * @param {Object} obj A javascript object (must be JSON compatible) + * @return {string} Encrypted string + */ +function encryptObject(password, obj) { + assertTypes$1.isStringWithValue(password); + assertTypes$1.isObject(obj); + + const encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), password, { + format: JsonFormatter, + }).toString(); + return encrypted; +} + +/** + * Decrypt an Object using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} objString A javascript object as JSON string + * @return {string} Encrypted string + */ +function decryptObject(password, objString) { + assertTypes$1.isStringWithValue(password); + assertTypes$1.isStringWithValue(objString); + + try { + const decrypt = CryptoJS.AES.decrypt(objString, password, { format: JsonFormatter }); + return JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt)); + } catch (e) { + return false; + } +} + +/** + * Encrypt a string using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} string A string to be password encrypted + * @return {string} Encrypted string + */ +function encryptStrHash(password, string) { + assertTypes$1.isStringWithValue(password); + assertTypes$1.isString(string); + + const encrypt = CryptoJS.AES.encrypt(string, password).toString(); + return encrypt; +} + +/** + * Decrypt a string using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} encryptedString A string to decrypt + * @return {string} Decrypted string + */ +function decryptStrHash(password, encryptedString) { + assertTypes$1.isStringWithValue(password); + assertTypes$1.isStringWithValue(encryptedString); + + try { + const decrypted = CryptoJS.AES.decrypt(encryptedString, password); + return CryptoJS.enc.Utf8.stringify(decrypted) === "" + ? false + : CryptoJS.enc.Utf8.stringify(decrypted); + } catch (e) { + return false; + } +} + +function buf2hex(buffer) { + return Array.prototype.map + .call(new Uint8Array(buffer), (x) => ("00" + x.toString(16)).slice(-2)) + .join(""); +} +function hex2buf(hexString) { + var bytes = new Uint8Array(Math.ceil(hexString.length / 2)); + for (var i = 0; i < bytes.length; i++) bytes[i] = parseInt(hexString.substr(i * 2, 2), 16); + return bytes; +} +function str2buf(string) { + var buf = new Buffer.from(string); + return new Uint8Array(buf); +} +function concatUint8Arrays(array1, array2) { + var arr = new Uint8Array(array1.length + array2.length); + arr.set(array1); + arr.set(array2, array1.length); + return arr; +} +function ab2str(buf) { + return String.fromCharCode.apply(null, new Uint8Array(buf)); +} +function str2ab(str) { + var buf = new ArrayBuffer(str.length); + var bufView = new Uint8Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; +} +function str2hex(str) { + var hex = ""; + for (var i = 0; i < str.length; i++) { + hex += "" + str.charCodeAt(i).toString(16); + } + return hex; +} +function hex2str(hexx) { + var hex = hexx.toString(); //force conversion + var str = ""; + for (var i = 0; i < hex.length && hex.substr(i, 2) !== "00"; i += 2) + str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + return str; +} +function randomString(length) { + var text = ""; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; +} +function isStringHex(string = "") { + let hexRegEx = /([0-9]|[a-f])/gim; + return typeof string === "string" && (string.match(hexRegEx) || []).length === string.length; +} + +function isLamdenKey(string) { + if (validateTypes$5.isStringHex(string) && string.length === 64) return true; + return false; +} + +var utils = /*#__PURE__*/Object.freeze({ + __proto__: null, + encryptObject: encryptObject, + decryptObject: decryptObject, + encryptStrHash: encryptStrHash, + decryptStrHash: decryptStrHash, + buf2hex: buf2hex, + hex2buf: hex2buf, + str2buf: str2buf, + concatUint8Arrays: concatUint8Arrays, + ab2str: ab2str, + str2ab: str2ab, + str2hex: str2hex, + hex2str: hex2str, + randomString: randomString, + isStringHex: isStringHex, + isLamdenKey: isLamdenKey +}); + +/** + * Create a wallet object for signing and verifying messages + * + * @param {Object} [args={}] Args Object + * @param {string} [args.sk=undefined] A 32 character long hex representation of a signing key (private key) to create wallet from + * @param {Uint8Array(length: 32)} [args.seed=null] A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be avoided by everyday users + * @param {boolean} [args.keepPrivate=false] No direct access to the sk. Will still allow the wallet to sign messages + * @return {Object} Wallet Object with sign and verify methods + */ +let create_wallet = (args = {}) => { + let { sk = undefined, keepPrivate = false, seed = null } = args; + + let vk; + + if (sk) { + vk = get_vk(sk); + } else { + let keyPair = new_wallet(seed); + vk = keyPair.vk; + sk = keyPair.sk; + } + + const wallet = () => { + return { + sign: (msg) => sign(sk, msg), + verify: (msg, sig) => verify(vk, msg, sig), + vk, + sk: !keepPrivate ? sk : undefined, + }; + }; + + return wallet(); +}; + +/** + * @param Uint8Array(length: 32) seed + * seed: A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be + * avoided by everyday users + * + * @return {Uint8Array(length: 32), Uint8Array(length: 32)} { vk, sk } + * sk: Signing Key (SK) represents 32 byte signing key + * vk: Verify Key (VK) represents a 32 byte verify key + */ +function generate_keys(seed = null) { + var kp = null; + if (seed == null) { + kp = nacl__default["default"].sign.keyPair(); + } else { + kp = nacl__default["default"].sign.keyPair.fromSeed(seed); + } + // In the JS implementation of the NaCL library the sk is the first 32 bytes of the secretKey + // and the vk is the last 32 bytes of the secretKey as well as the publicKey + // { + // 'publicKey': , + // 'secretKey': + // } + return { + sk: new Uint8Array(kp["secretKey"].slice(0, 32)), + vk: new Uint8Array(kp["secretKey"].slice(32, 64)), + }; +} +/** + * @param String sk + * sk: A 64 character long hex representation of a signing key (private key) + * + * @return String vk + * vk: A 64 character long hex representation of a verify key (public key) + */ +function get_vk(sk) { + var kp = format_to_keys(sk); + var kpf = keys_to_format(kp); + return kpf.vk; +} +/** + * @param String sk + * sk: A 64 character long hex representation of a signing key (private key) + * + * @return {Uint8Array(length: 32), Uint8Array(length: 32)} { vk, sk } + * sk: Signing Key (SK) represents 32 byte signing key + * vk: Verify Key (VK) represents a 32 byte verify key + */ +function format_to_keys(sk) { + var skf = hex2buf(sk); + var kp = generate_keys(skf); + return kp; +} +/** + * @param Object kp + * kp: Object containing the properties sk and vk + * sk: Signing Key (SK) represents 32 byte signing key + * vk: Verify Key (VK) represents a 32 byte verify key + * + * @return {string, string} { sk, vk } + * sk: Signing Key (SK) represented as a 64 character hex string + * vk: Verify Key (VK) represented as a 64 character hex string + */ +function keys_to_format(kp) { + return { + vk: buf2hex(kp.vk), + sk: buf2hex(kp.sk), + }; +} +/** + * @param Uint8Array(length: 32) seed + * seed: A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be + * avoided by everyday users + * + * @return {string, string} { sk, vk } + * sk: Signing Key (SK) represented as a 64 character hex string + * vk: Verify Key (VK) represented as a 64 character hex string + */ +function new_wallet(seed = null) { + const keys = generate_keys(seed); + return keys_to_format(keys); +} + +/** + * + * @param seed Bip39 seed phrase (128 characters in hex) + * @param derivationIndex bip32 derivation key index + * @returns {{derivationIndex: number, vk: string, sk: string, mnemonic: string}} + * derivationIndex: bip32 derivation key index + * vk: Verify Key (VK) represented as a 64 character hex string + * sk: Signing Key (SK) represented as a 64 character hex string + * seed: Bip39 seed phrase (128 characters in hex) + * mnemonic: Bip39 24 words mnemonic + */ +function generate_keys_bip39(seed = undefined, derivationIndex = 0) { + let finalSeed; + let finalMnemonic; + + if (seed !== undefined){ + finalSeed = seed; + }else { + finalMnemonic = bip39__namespace.generateMnemonic(256); + finalSeed = bip39__namespace.mnemonicToSeedSync(finalMnemonic).toString('hex'); + } + + const derivationPath = "m/44'/789'/" + derivationIndex + "'/0'/0'"; + const { key, chainCode } = bip32__default["default"].derivePath(derivationPath, finalSeed, 0x80000000); + + const privateKey = key.toString("hex"); + const publicKey = bip32__default["default"].getPublicKey(key, false).toString("hex"); + + if (publicKey !== get_vk(privateKey)) { + throw Error("Bip32 public key does not match with Lamden public key!"); + } + + return { + sk: privateKey, + vk: publicKey, + derivationIndex: derivationIndex, + seed: seed !== undefined ? null : finalSeed, + mnemonic: seed !== undefined ? null : finalMnemonic, + } +} + +/** + * @param seed Bip39 seed phrase (128 characters in hex) + * @param derivationIndex bip32 derivation key index + * + * @return {{derivationIndex: number, vk: string, sk: string, mnemonic: (string|undefined)}} { sk, vk, derivationIndex, mnemonic } + * sk: Signing Key (SK) represented as a 64 character hex string + * vk: Verify Key (VK) represented as a 64 character hex string + * derivationIndex: Bip32 derivation index + * seed: Bip39 seed phrase (128 characters in hex) + * mnemonic: Bip39 24 words mnemonic + */ +function new_wallet_bip39(seed = undefined, derivationIndex = 0) { + return generate_keys_bip39(seed, derivationIndex); +} + +/** + * @param String sk + * @param Uint8Array msg + * sk: A 64 character long hex representation of a signing key (private key) + * msg: A Uint8Array of bytes representing the message you would like to sign + * + * @return String sig + * sig: A 128 character long hex string representing the message's signature + */ +function sign(sk, msg) { + var kp = format_to_keys(sk); + // This is required due to the secretKey required to sign a transaction + // in the js implementation of NaCL being the combination of the sk and + // vk for some stupid reason. That being said, we still want the sk and + // vk objects to exist in 32-byte string format (same as cilantro's + // python implementation) when presented to the user. + var jsnacl_sk = concatUint8Arrays(kp.sk, kp.vk); + return buf2hex(nacl__default["default"].sign.detached(msg, jsnacl_sk)); +} +/** + * @param String vk + * @param Uint8Array msg + * @param String sig + * vk: A 64 character long hex representation of a verify key (public key) + * msg: A Uint8Array (bytes) representation of a message that has been signed + * sig: A 128 character long hex representation of a nacl signature + * + * @return Bool result + * result: true if verify checked out, false if not + */ +function verify(vk, msg, sig) { + var vkb = hex2buf(vk); + var sigb = hex2buf(sig); + try { + return nacl__default["default"].sign.detached.verify(msg, sigb, vkb); + } catch (_a) { + return false; + } +} + +var wallet = /*#__PURE__*/Object.freeze({ + __proto__: null, + create_wallet: create_wallet, + generate_keys: generate_keys, + get_vk: get_vk, + format_to_keys: format_to_keys, + keys_to_format: keys_to_format, + new_wallet: new_wallet, + new_wallet_bip39: new_wallet_bip39, + sign: sign, + verify: verify +}); + +class EventEmitter { + constructor() { + this._events = {}; + } + + on(name, listener) { + if (!this._events[name]) { + this._events[name] = []; + } + + this._events[name].push(listener); + } + + removeListener(name, listenerToRemove) { + if (!this._events[name]) { + throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`); + } + + const filterListeners = (listener) => listener !== listenerToRemove; + this._events[name] = this._events[name].filter(filterListeners); + } + + emit(name, data) { + if (!this._events[name]) return + + const fireCallbacks = (callback) => { + callback(data); + }; + + this._events[name].forEach(fireCallbacks); + } + } + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream__default["default"].Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream__default["default"].PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream__default["default"]) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream__default["default"]) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream__default["default"])) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http__default["default"].STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone$1(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url__default["default"].parse; +const format_url = Url__default["default"].format; + +const streamDestructionSupported = 'destroy' in Stream__default["default"].Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parse_url(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parse_url(`${input}`); + } + input = {}; + } else { + parsedURL = parse_url(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone$1(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream__default["default"].Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + if (!headers.has('Connection') && !agent) { + headers.set('Connection', 'close'); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream__default["default"].PassThrough; +const resolve_url = Url__default["default"].resolve; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https__default["default"] : http__default["default"]).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream__default["default"].Readable) { + request.body.destroy(error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + finalize(); + }); + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + const locationURL = location === null ? null : resolve_url(request.url, location); + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib__default["default"].Z_SYNC_FLUSH, + finishFlush: zlib__default["default"].Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib__default["default"].createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib__default["default"].createInflate()); + } else { + body = body.pipe(zlib__default["default"].createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib__default["default"].createBrotliDecompress === 'function') { + body = body.pipe(zlib__default["default"].createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +/* + * bignumber.js v9.0.0 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2019 Michael Mclaughlin + * 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 + + +var BigNumber = clone(); + +BigNumber.config({ RANGE: [-30, 30], EXPONENTIAL_AT: 1e9 }); +BigNumber.set({ DECIMAL_PLACES: 30, ROUNDING_MODE: BigNumber.ROUND_DOWN }); // equivalent + +function Encoder(type, value) { + const throwError = (val) => { + throw new Error(`Error encoding ${val} to ${type}`); + }; + const countDecimals = (n) => { + if (Math.floor(n) === n) return 0; + try { + return n.toString().split(".")[1].length; + } catch (e) { + return 0; + } + }; + const isString = (val) => typeof val === "string" || val instanceof String; + const isArray = (val) => val && typeof val === "object" && val.constructor === Array; + const isObject = (val) => val && typeof val === "object" && val.constructor === Object; + const isDate = (val) => val instanceof Date; + const isBoolean = (val) => typeof val === "boolean"; + + const isNumber = (val) => { + if (isArray(val)) return false; + return !isNaN(encodeBigNumber(val).toNumber()); + }; + + const isInteger = (val) => { + if (!isNumber(val)) return false; + if (countDecimals(val) === 0) return true; + return false; + }; + const encodeInt = (val) => { + if (!isNumber(val)) throwError(val); + else return parseInt(val); + }; + const isFloat = (val) => { + if (!isNumber(val)) return false; + if (countDecimals(val) === 0) return false; + return true; + }; + const encodeFloat = (val) => { + if (!isNumber(val)) throwError(val); + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + + return { __fixed__: val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, "$1$2") }; + }; + const encodeNumber = (val) => { + if (!isNumber(val)) throwError(val); + if (isFloat(val)) { + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + return { __fixed__: val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, "$1$2") }; + } + if (isInteger(val)) return parseInt(val); + }; + const encodeBigNumber = (val) => { + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + return val; + }; + + const encodeBool = (val) => { + if (isBoolean(val)) return val; + if (val === "true" || val === 1) return true; + if (val === "false" || val === 0) return false; + throwError(val); + }; + const encodeStr = (val) => { + if (isString(val)) return val; + if (isDate(val)) return val.toISOString(); + return JSON.stringify(val); + }; + const encodeDateTime = (val) => { + val = !isDate(val) ? new Date(val) : val; + if (!isDate(val)) throwError(val); + return { + __time__: [ + val.getUTCFullYear(), + val.getUTCMonth(), + val.getUTCDate(), + val.getUTCHours(), + val.getUTCMinutes(), + val.getUTCSeconds(), + val.getUTCMilliseconds(), + ], + }; + }; + const encodeTimeDelta = (val) => { + const time = isDate(val) ? val.getTime() : new Date(val).getTime(); + const days = parseInt(time / 1000 / 60 / 60 / 24); + const seconds = (time - days * 24 * 60 * 60 * 1000) / 1000; + return { __delta__: [days, seconds] }; + }; + + const encodeList = (val) => { + if (isArray(val)) return parseObject(val); + try { + val = JSON.parse(val); + } catch (e) { + throwError(val); + } + if (isArray(val)) return parseObject(val); + throwError(val); + }; + + const encodeDict = (val) => { + if (isObject(val)) return parseObject(val); + try { + val = JSON.parse(val); + } catch (e) { + throwError(val); + } + if (isObject(val)) return parseObject(val); + throwError(val); + }; + + const encodeObject = (val) => { + try { + return encodeList(val); + } catch (e) { + return encodeDict(val); + } + }; + + function parseObject(obj) { + const encode = (k, v) => { + if (k === "datetime" || k === "datetime.datetime") return Encoder("datetime.datetime", v); + if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v); + if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v); + return v; + }; + + const fixDatetime = (k, v) => { + const isDatetimeObject = (val) => { + let datetimeTypes = ["datetime.datetime", "datetime", "datetime.timedelta", "timedelta"]; + return ( + Object.keys(val).length === 1 && + datetimeTypes.filter((f) => f === Object.keys(val)[0]).length > 0 + ); + }; + + if (v.constructor === Array) { + v.map((val) => { + if (Object.keys(val).length === 1 && isDatetimeObject(v)) return val[Object.keys(val)[0]]; + //if (isFloat(val)) return encodeFloat(val) + return val; + }); + } + if (v.constructor === Object) { + if (Object.keys(v).length === 1 && isDatetimeObject(v)) return v[Object.keys(v)[0]]; + } + + //if (isFloat(v)) return encodeFloat(v) + + return v; + }; + + let encodeValues = JSON.stringify(obj, encode); + return JSON.parse(encodeValues, fixDatetime); + } + + const encoder = { + str: encodeStr, + string: encodeStr, + float: encodeFloat, + int: encodeInt, + bool: encodeBool, + boolean: encodeBool, + dict: encodeDict, + list: encodeList, + Any: () => value, + "datetime.timedelta": encodeTimeDelta, + "datetime.datetime": encodeDateTime, + timedelta: encodeTimeDelta, + datetime: encodeDateTime, + number: encodeNumber, + object: encodeObject, + bigNumber: encodeBigNumber, + }; + + if (Object.keys(encoder).includes(type)) return encoder[type](value); + else throw new Error(`Error: ${type} is not a valid encoder type.`); +} + +Encoder.BigNumber = BigNumber; + +const { validateTypes: validateTypes$4 } = validators; + +class LamdenMasterNode_API { + constructor(networkInfoObj) { + if (!validateTypes$4.isObjectWithKeys(networkInfoObj)) + throw new Error(`Expected Object and got Type: ${typeof networkInfoObj}`); + if (!validateTypes$4.isArrayWithValues(networkInfoObj.hosts)) + throw new Error(`HOSTS Required (Type: Array)`); + + this.hosts = this.validateHosts(networkInfoObj.hosts); + } + //This will throw an error if the protocol wasn't included in the host string + vaidateProtocol(host) { + let protocols = ["https://", "http://"]; + if (protocols.map((protocol) => host.includes(protocol)).includes(true)) return host; + throw new Error("Host String must include http:// or https://"); + } + validateHosts(hosts) { + return hosts.map((host) => this.vaidateProtocol(host.toLowerCase())); + } + + get host() { + return this.hosts[Math.floor(Math.random() * this.hosts.length)]; + } + get url() { + return this.host; + } + + send(method, path, data, overrideURL, callback) { + let parms = ""; + if (Object.keys(data).includes("parms")) { + parms = this.createParms(data.parms); + } + + let options = {}; + if (method === "POST") { + let headers = { "Content-Type": "application/json" }; + options.method = method; + options.headers = headers; + options.body = data; + } + + return fetch(`${overrideURL ? overrideURL : this.url}${path}${parms}`, options) + .then(async (res) => { + if (res.status === 200) { + let json = await res.json(); + callback(json, undefined); + return json; + } else { + let error = validateTypes$4.isStringWithValue(res.statusText) ? res.statusText : false; + callback(undefined, error); + return error; + } + }) + .catch((err) => { + return callback(undefined, err.toString()); + }); + } + + createParms(parms) { + if (Object.keys(parms).length === 0) return ""; + let parmString = "?"; + Object.keys(parms).forEach((key) => { + parmString = `${parmString}${key}=${parms[key]}&`; + }); + return parmString.slice(0, -1); + } + + async getContractInfo(contractName) { + const returnInfo = (res) => { + try { + if (res.name) return res; + } catch (e) {} + return null; + }; + let path = `/contracts/${contractName}`; + return this.send("GET", path, {}, undefined, (res, err) => returnInfo(res)).then((res) => + returnInfo(res) + ); + } + + async getVariable(contract, variable, key = "") { + let parms = {}; + if (validateTypes$4.isStringWithValue(key)) parms.key = key; + + let path = `/contracts/${contract}/${variable}/`; + + const returnValue = (res) => { + try { + if (res.value) return res.value; + } catch (e) {} + return null; + }; + return this.send("GET", path, { parms }, undefined, (res, err) => returnValue(res)).then( + (res) => returnValue(res) + ); + } + + async getContractMethods(contract) { + const getMethods = (res) => { + try { + if (res.methods) return res.methods; + } catch (e) {} + return []; + }; + let path = `/contracts/${contract}/methods`; + return this.send("GET", path, {}, undefined, (res, err) => getMethods(res)).then((res) => + getMethods(res) + ); + } + + async getContractVariables(contract) { + const getVariables = (res) => { + try { + if (res.variables) return res; + } catch (e) {} + return {}; + }; + let path = `/contracts/${contract}/variables`; + return this.send("GET", path, {}, undefined, (res, err) => getVariables(res)).then((res) => + getVariables(res) + ); + } + + async pingServer() { + const getStatus = (res) => { + try { + if (res.status) return true; + } catch (e) {} + return false; + }; + let response = await this.send("GET", "/ping", {}, undefined, (res, err) => getStatus(res)); + return getStatus(response); + } + + async getCurrencyBalance(vk) { + let balanceRes = await this.getVariable("currency", "balances", vk); + if (!balanceRes) return Encoder("bigNumber", 0); + if (balanceRes.__fixed__) return Encoder("bigNumber", balanceRes.__fixed__); + return Encoder("bigNumber", balanceRes.toString()); + } + + async contractExists(contractName) { + const exists = (res) => { + try { + if (res.name) return true; + } catch (e) {} + return false; + }; + let path = `/contracts/${contractName}`; + return this.send("GET", path, {}, undefined, (res, err) => exists(res)).then((res) => + exists(res) + ); + } + + async sendTransaction(data, url = undefined, callback) { + return this.send("POST", "/", JSON.stringify(data), url, (res, err) => { + if (err) { + if (callback) { + callback(undefined, err); + return; + } else return err; + } + if (callback) { + callback(res, undefined); + return; + } + return res; + }); + } + + async getNonce(sender, callback) { + if (!validateTypes$4.isStringHex(sender)) return `${sender} is not a hex string.`; + let path = `/nonce/${sender}`; + let url = this.host; + return this.send("GET", path, {}, url, (res, err) => { + if (err) { + if (callback) { + callback(undefined, `Unable to get nonce for ${sender} on network ${url}`); + return; + } + return `Unable to get nonce for ${sender} on network ${url}`; + } + res.masternode = url; + if (callback) { + callback(res, undefined); + return; + } else return res; + }); + } + + checkTransaction(hash, callback) { + const parms = { hash }; + return this.send("GET", "/tx", { parms }, undefined, (res, err) => { + if (err) { + if (callback) { + callback(undefined, err); + return; + } else return err; + } + if (callback) { + callback(res, undefined); + return; + } + return res; + }); + } +} + +const { validateTypes: validateTypes$3 } = validators; + +class Network { + // Constructor needs an Object with the following information to build Class. + // + // networkInfo: { + // hosts: list of masternode hostname/ip urls, + // type: "testnet", "mainnet" or "custom" + // }, + constructor(networkInfoObj) { + //Reject undefined or missing info + if (!validateTypes$3.isObjectWithKeys(networkInfoObj)) + throw new Error(`Expected Network Info Object and got Type: ${typeof networkInfoObj}`); + if (!validateTypes$3.isArrayWithValues(networkInfoObj.hosts)) + throw new Error(`HOSTS Required (Type: Array)`); + + this.type = validateTypes$3.isStringWithValue(networkInfoObj.type) + ? networkInfoObj.type.toLowerCase() + : "custom"; + this.events = new EventEmitter(); + this.hosts = this.validateHosts(networkInfoObj.hosts); + this.currencySymbol = validateTypes$3.isStringWithValue(networkInfoObj.currencySymbol) + ? networkInfoObj.currencySymbol + : "TAU"; + this.name = validateTypes$3.isStringWithValue(networkInfoObj.name) + ? networkInfoObj.name + : "lamden network"; + this.lamden = validateTypes$3.isBoolean(networkInfoObj.lamden) ? networkInfoObj.lamden : false; + this.blockExplorer = validateTypes$3.isStringWithValue(networkInfoObj.blockExplorer) + ? networkInfoObj.blockExplorer + : undefined; + + this.online = false; + try { + this.API = new LamdenMasterNode_API(networkInfoObj); + } catch (e) { + throw new Error(e); + } + } + //This will throw an error if the protocol wasn't included in the host string + vaidateProtocol(host) { + let protocols = ["https://", "http://"]; + if (protocols.map((protocol) => host.includes(protocol)).includes(true)) return host; + throw new Error("Host String must include http:// or https://"); + } + validateHosts(hosts) { + return hosts.map((host) => this.vaidateProtocol(host.toLowerCase())); + } + //Check if the network is online + //Emits boolean as 'online' event + //Also returns status as well as passes status to a callback + async ping(callback = undefined) { + this.online = await this.API.pingServer(); + this.events.emit("online", this.online); + if (validateTypes$3.isFunction(callback)) callback(this.online); + return this.online; + } + get host() { + return this.hosts[Math.floor(Math.random() * this.hosts.length)]; + } + get url() { + return this.host; + } + getNetworkInfo() { + return { + name: this.name, + lamden: this.lamden, + type: this.type, + hosts: this.hosts, + url: this.url, + online: this.online, + }; + } +} + +const { validateTypes: validateTypes$2 } = validators; + +class TransactionBuilder extends Network { + // Constructor needs an Object with the following information to build Class. + // + // arg[0] (networkInfo): { //Can also accpet a Lamden "Network Class" + // host: masternode webserver hostname/ip, + // type: "testnet", "mainnet" or "mockchain" + // } + // arg[1] (txInfo): { + // uid: [Optional] unique ID for tracking purposes, + // senderVk: public key of the transaction sender, + // contractName: name of lamden smart contract, + // methodName: name of method to call in contractName, + // kwargs: key/values of args to pass to methodName + // example: kwargs.to = "270add00fc708791c97aeb5255107c770434bd2ab71c2e103fbee75e202aa15e" + // kwargs.amount = 1000 + // stampLimit: the max amount of stamps the tx should use. tx could use less. if tx needs more the tx will fail. + // nonce: [Optional] send() will attempt to retrieve this info automatically + // processor [Optional] send() will attempt to retrieve this info automatically + // } + // arg[2] (txData): [Optional] state hydrating data + constructor(networkInfo, txInfo, txData) { + if (validateTypes$2.isSpecificClass(networkInfo, "Network")) super(networkInfo.getNetworkInfo()); + else super(networkInfo); + + //Validate arguments + if (!validateTypes$2.isObjectWithKeys(txInfo)) throw new Error(`txInfo object not found`); + if (!validateTypes$2.isStringHex(txInfo.senderVk)) + throw new Error(`Sender Public Key Required (Type: Hex String)`); + if (!validateTypes$2.isStringWithValue(txInfo.contractName)) + throw new Error(`Contract Name Required (Type: String)`); + if (!validateTypes$2.isStringWithValue(txInfo.methodName)) + throw new Error(`Method Required (Type: String)`); + if (!validateTypes$2.isInteger(txInfo.stampLimit)) + throw new Error(`Stamps Limit Required (Type: Integer)`); + + //Store variables in self for reference + this.uid = validateTypes$2.isStringWithValue(txInfo.uid) ? txInfo.uid : undefined; + this.sender = txInfo.senderVk; + this.contract = txInfo.contractName; + this.method = txInfo.methodName; + this.kwargs = {}; + if (validateTypes$2.isObject(txInfo.kwargs)) this.kwargs = txInfo.kwargs; + this.stampLimit = txInfo.stampLimit; + + //validate and set nonce and processor if user provided them + if (typeof txInfo.nonce !== "undefined") { + if (!validateTypes$2.isInteger(txInfo.nonce)) + throw new Error( + `arg[6] Nonce is required to be an Integer, type ${typeof txInfo.none} was given` + ); + this.nonce = txInfo.nonce; + } + if (typeof txInfo.processor !== "undefined") { + if (!validateTypes$2.isStringWithValue(txInfo.processor)) + throw new Error( + `arg[7] Processor is required to be a String, type ${typeof txInfo.processor} was given` + ); + this.processor = txInfo.processor; + } + + this.signature; + this.transactionSigned = false; + + //Transaction result information + this.nonceResult = {}; + this.txSendResult = { errors: [] }; + this.txBlockResult = {}; + this.txHash; + this.txCheckResult = {}; + this.txCheckAttempts = 0; + this.txCheckLimit = 10; + + //Hydrate other items if passed + if (txData) { + if (txData.uid) this.uid = txData.uid; + if (validateTypes$2.isObjectWithKeys(txData.txSendResult)) + this.txSendResult = txData.txSendResult; + if (validateTypes$2.isObjectWithKeys(txData.nonceResult)) { + this.nonceResult = txData.nonceResult; + if (validateTypes$2.isInteger(this.nonceResult.nonce)) this.nonce = this.nonceResult.nonce; + if (validateTypes$2.isStringWithValue(this.nonceResult.processor)) + this.processor = this.nonceResult.processor; + } + if (validateTypes$2.isObjectWithKeys(txData.txSendResult)) { + this.txSendResult = txData.txSendResult; + if (this.txSendResult.hash) this.txHash = this.txSendResult.hash; + } + if (validateTypes$2.isObjectWithKeys(txData.txBlockResult)) + this.txBlockResult = txData.txBlockResult; + if (validateTypes$2.isObjectWithKeys(txData.resultInfo)) this.resultInfo = txData.resultInfo; + } + //Create Capnp messages and transactionMessages + this.makePayload(); + } + makePayload() { + this.payload = { + contract: this.contract, + function: this.method, + kwargs: this.kwargs, + nonce: this.nonce, + processor: this.processor, + sender: this.sender, + stamps_supplied: this.stampLimit, + }; + this.sortedPayload = this.sortObject(this.payload); + } + makeTransaction() { + this.tx = { + metadata: { + signature: this.signature, + timestamp: parseInt(+new Date() / 1000), + }, + payload: this.sortedPayload.orderedObj, + }; + } + verifySignature() { + //Verify the signature is correct + if (!this.transactionSigned) + throw new Error( + "Transaction has not be been signed. Use the sign() method first." + ); + const stringBuffer = Buffer.from(this.sortedPayload.json); + const stringArray = new Uint8Array(stringBuffer); + return verify(this.sender, stringArray, this.signature); + } + sign(sk = undefined, userWallet = undefined) { + const stringBuffer = Buffer.from(this.sortedPayload.json); + const stringArray = new Uint8Array(stringBuffer); + if (userWallet) this.signature = userWallet.sign(stringArray); + else this.signature = sign(sk, stringArray); + this.transactionSigned = true; + } + sortObject(object) { + const processObj = (obj) => { + const getType = (value) => { + return Object.prototype.toString.call(value); + }; + const isArray = (value) => { + if (getType(value) === "[object Array]") return true; + return false; + }; + const isObject = (value) => { + if (getType(value) === "[object Object]") return true; + return false; + }; + + const sortObjKeys = (unsorted) => { + const sorted = {}; + Object.keys(unsorted) + .sort() + .forEach((key) => (sorted[key] = unsorted[key])); + return sorted; + }; + + const formatKeys = (unformatted) => { + Object.keys(unformatted).forEach((key) => { + if (isArray(unformatted[key])) + unformatted[key] = unformatted[key].map((item) => { + if (isObject(item)) return formatKeys(item); + return item; + }); + if (isObject(unformatted[key])) unformatted[key] = formatKeys(unformatted[key]); + }); + return sortObjKeys(unformatted); + }; + + if (!isObject(obj)) throw new TypeError("Not a valid Object"); + try { + obj = JSON.parse(JSON.stringify(obj)); + } catch (e) { + throw new TypeError("Not a valid JSON Object"); + } + return formatKeys(obj); + }; + const orderedObj = processObj(object); + return { + orderedObj, + json: JSON.stringify(orderedObj), + }; + } + async getNonce(callback = undefined) { + let timestamp = new Date().toUTCString(); + this.nonceResult = await this.API.getNonce(this.sender); + if (typeof this.nonceResult.nonce === "undefined") { + throw new Error(this.nonceResult); + } + this.nonceResult.timestamp = timestamp; + this.nonce = this.nonceResult.nonce; + this.processor = this.nonceResult.processor; + this.nonceMasternode = this.nonceResult.masternode; + //Create payload object + this.makePayload(); + + if (!callback) return this.nonceResult; + return callback(this.nonceResult); + } + async send(sk = undefined, callback = undefined, masternode = undefined) { + //Error if transaction is not signed and no sk provided to the send method to sign it before sending + if (!validateTypes$2.isStringWithValue(sk) && !this.transactionSigned) { + throw new Error( + `Transation Not Signed: Private key needed or call sign() first` + ); + } + + let timestamp = new Date().toUTCString(); + + try { + //If the nonce isn't set attempt to get it + if (isNaN(this.nonce) || !validateTypes$2.isStringWithValue(this.processor)) + await this.getNonce(); + //if the sk is provided then sign the transaction + if (validateTypes$2.isStringWithValue(sk)) this.sign(sk); + //Serialize transaction + this.makeTransaction(); + //Send transaction to the masternode + let masternodeURL = masternode; + if (!masternodeURL && this.nonceMasternode) masternodeURL = this.nonceMasternode; + let response = await this.API.sendTransaction(this.tx, masternodeURL); + //Set error if txSendResult doesn't exist + if (!response || validateTypes$2.isStringWithValue(response)) { + this.txSendResult.errors = [response || "Unknown Transaction Error"]; + } else { + if (response.error) this.txSendResult.errors = [response.error]; + else this.txSendResult = response; + } + } catch (e) { + this.txSendResult.errors = [e.message]; + } + this.txSendResult.timestamp = timestamp; + return this.handleMasterNodeResponse(this.txSendResult, callback); + } + checkForTransactionResult(callback = undefined) { + return new Promise((resolve) => { + let timerId = setTimeout( + async function checkTx() { + this.txCheckAttempts = this.txCheckAttempts + 1; + let res = await this.API.checkTransaction(this.txHash); + let checkAgain = false; + let timestamp = new Date().toUTCString(); + if (typeof res === "string" || !res) { + if (this.txCheckAttempts < this.txCheckLimit) { + checkAgain = true; + } else { + this.txCheckResult.errors = [ + `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, + res, + ]; + } + } else { + if (res.error) { + if (res.error === "Transaction not found.") { + if (this.txCheckAttempts < this.txCheckLimit) { + checkAgain = true; + } else { + this.txCheckResult.errors = [ + res.error, + `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, + ]; + } + } else { + this.txCheckResult.errors = [res.error]; + } + } else { + this.txCheckResult = res; + } + } + if (checkAgain) timerId = setTimeout(checkTx.bind(this), 1000); + else { + if (validateTypes$2.isNumber(this.txCheckResult.status)) { + if (this.txCheckResult.status > 0) { + if (!validateTypes$2.isArray(this.txCheckResult.errors)) + this.txCheckResult.errors = []; + this.txCheckResult.errors.push("This transaction returned a non-zero status code"); + } + } + this.txCheckResult.timestamp = timestamp; + clearTimeout(timerId); + resolve(this.handleMasterNodeResponse(this.txCheckResult, callback)); + } + }.bind(this), + 1000 + ); + }); + } + handleMasterNodeResponse(result, callback = undefined) { + //Check to see if this is a successful transacation submission + if ( + validateTypes$2.isStringWithValue(result.hash) && + validateTypes$2.isStringWithValue(result.success) + ) { + this.txHash = result.hash; + this.setPendingBlockInfo(); + } else { + this.setBlockResultInfo(result); + this.txBlockResult = result; + } + this.events.emit("response", result, this.resultInfo.subtitle); + if (validateTypes$2.isFunction(callback)) callback(result); + return result; + } + setPendingBlockInfo() { + this.resultInfo = { + title: "Transaction Pending", + subtitle: "Your transaction was submitted and is being processed", + message: `Tx Hash: ${this.txHash}`, + type: "success", + }; + return this.resultInfo; + } + setBlockResultInfo(result) { + let erroredTx = false; + let errorText = `returned an error and `; + let statusCode = validateTypes$2.isNumber(result.status) ? result.status : undefined; + let stamps = result.stampsUsed || result.stamps_used || 0; + let message = ""; + if (validateTypes$2.isArrayWithValues(result.errors)) { + erroredTx = true; + message = `This transaction returned ${result.errors.length} errors.`; + if (result.result) { + if (result.result.includes("AssertionError")) result.errors.push(result.result); + } + } + if (statusCode && erroredTx) errorText = `returned status code ${statusCode} and `; + + this.resultInfo = { + title: `Transaction ${erroredTx ? "Failed" : "Successful"}`, + subtitle: `Your transaction ${erroredTx ? `${errorText} ` : ""}used ${stamps} stamps`, + message, + type: `${erroredTx ? "error" : "success"}`, + errorInfo: erroredTx ? result.errors : undefined, + returnResult: result.result || "", + stampsUsed: stamps, + statusCode, + }; + return this.resultInfo; + } + getResultInfo() { + return this.resultInfo; + } + getTxInfo() { + return { + senderVk: this.sender, + contractName: this.contract, + methodName: this.method, + kwargs: this.kwargs, + stampLimit: this.stampLimit, + }; + } + getAllInfo() { + return { + uid: this.uid, + txHash: this.txHash, + signed: this.transactionSigned, + tx: this.tx, + signature: this.signature, + networkInfo: this.getNetworkInfo(), + txInfo: this.getTxInfo(), + txSendResult: this.txSendResult, + txBlockResult: this.txBlockResult, + resultInfo: this.getResultInfo(), + nonceResult: this.nonceResult, + }; + } +} + +const { validateTypes: validateTypes$1 } = validators; + +class TransactionBatcher extends Network { + constructor(networkInfo) { + if (validateTypes$1.isSpecificClass(networkInfo, 'Network')) + super(networkInfo.getNetworkInfo()); + else super(networkInfo); + + this.txBatches = {}; + this.overflow = []; + this.nonceResults = {}; + this.running = false; + } + addTransaction(txInfo){ + if (this.running) { + this.overflow.push(txInfo); + return + } + this.validateTransactionInfo(txInfo); + if (!this.txBatches[txInfo.senderVk]) this.txBatches[txInfo.senderVk] = []; + this.txBatches[txInfo.senderVk].push(txInfo); + } + addTransactionList(txList){ + txList.forEach(txInfo => this.addTransaction(txInfo)); + } + processOverflow(){ + const overflow = this.overflow; + this.overflow = []; + overflow.forEach(txInfo => this.addTransaction(txInfo)); + } + hasTransactions(){ + let test = Object.keys(this.txBatches).map(senderVk => this.txBatches[senderVk].length); + test.filter(f => f === 0); + if (test.length > 0 ) return true + return false + } + validateTransactionInfo(txInfo){ + try{ + new TransactionBuilder(txInfo); + }catch(e){ + return false + } + return true + } + async getStartingNonce(senderVk, callback = undefined){ + let timestamp = new Date().toUTCString(); + let response = await this.API.getNonce(senderVk); + if (typeof response.nonce === 'undefined'){ + throw new Error(response) + } + response.timestamp = timestamp; + this.nonceResults[senderVk] = response; + + if (callback) callback(response); + return response; + } + async sendAllBatches(keyDict){ + if (this.running) return + let sentTransactions = []; + this.running = true; + + await Promise.all(Object.keys(this.txBatches).map((senderVk) => { + const senderBatch = this.txBatches[senderVk].splice(0,15); + if (senderBatch.length <= 15) delete this.txBatches[senderVk]; + + return new Promise(async (resolver) => { + if (senderBatch.length === 0 ) resolver(); + + if (!keyDict[senderVk]) throw new Error(`Cannot sign batch for ${senderVk}. No signing key provided.`) + let nonceResponse = await this.getStartingNonce(senderVk); + let txBatch = this.setBatchNonces(nonceResponse, senderBatch); + this.signBatch(txBatch, keyDict[senderVk]); + this.sendBatch(txBatch).then(sentList => { + sentTransactions = [...sentTransactions, ...sentList]; + resolver(); + }); + }) + })); + + try{ + return Promise.all(sentTransactions) + }catch (e){} + finally{ + this.running = false; + this.processOverflow(); + } + } + setBatchNonces(nonceResult, txList){ + return txList.map((txInfo, index) => { + txInfo.nonce = nonceResult.nonce + index; + txInfo.processor = nonceResult.processor; + return new TransactionBuilder({hosts: [nonceResult.masternode]}, txInfo) + }).sort((a, b) => a.nonce - b.nonce) + } + signBatch(txBatch, key){ + txBatch.forEach(txBuilder => txBuilder.sign(key)); + } + sendBatch(txBatch){ + let resolvedTransactions = []; + return new Promise(resolver => { + const resolve = (index) => { + if ((index + 1) === txBatch.length) resolver(resolvedTransactions); + }; + txBatch.forEach((txBuilder, index) => { + const delayedSend = () => { + resolvedTransactions[index] = txBuilder.send().then(() => {return txBuilder}); + resolve(index); + }; + setTimeout(delayedSend, 1200 * index); + }); + }) + } +} + +const { validateTypes, assertTypes } = validators; + +class Keystore { + /** + * Lamden Keystores + * + * This Class will create a lamden keystore instance + * + * @param {Object|undefined} arg constructor argument + * @param {String|undefined} arg.key Create an instance and load it with one private key + * @param {String|undefined} arg.keyList Create an instance and load it with an array of private keys + * @param {String|undefined} arg.keystoreData Create an instance from an existing keystore file data + * @return {Keystore} + */ + constructor(arg = undefined) { + this.KEYSTORE_VERSION = "1.0"; + this.password = null; + this.encryptedData = null; + + this.keyList = (() => { + let keyList = []; + let outerClass = this; + let wallets = []; + + const addKey = (key) => { + keyList.push(key); + createWallets(); + }; + const deleteKey = (position) => { + keyList.splice(position, 1); + createWallets(); + }; + const clearKeys = () => { + keyList = []; + createWallets(); + }; + const numOfKeys = () => keyList.length; + const createWallets = () => { + wallets = []; + keyList.forEach(keyInfo => { + let newWallet = create_wallet({sk: keyInfo.sk, keepPrivate: true}); + newWallet = {...newWallet, ...keyInfo}; + delete newWallet.sk; + wallets.push(newWallet); + }); + }; + const createKeystore = (password, hint = undefined) => { + return JSON.stringify({ + data: encryptObject(password, {version: outerClass.KEYSTORE_VERSION, keyList}), + w: !hint ? "" : encryptStrHash('n1ahcKc0lb', hint), + }); + }; + const decryptKeystore = (password, data) => { + let decrypted = decryptObject(password, data); + if (decrypted) { + assertTypes.isArray(decrypted.keyList); + decrypted.keyList.forEach(keyInfo => assertTypes.isStringWithValue(keyInfo.sk)); + decrypted.keyList.forEach(keyInfo => addKey(keyInfo)); + outerClass.version = decrypted.version; + } else { + throw new Error("Incorrect Keystore Password.") + } + }; + + return { + getWallets: () => wallets, + getWallet: (vk) => wallets.find(wallet => wallet.vk === vk), + addKey, + clearKeys, + numOfKeys, + deleteKey, + createKeystore, + decryptKeystore + } + })(); + + if (arg){ + if (arg.key) this.addKey(arg.key); + if (arg.keyList) this.addKeys(arg.keyList); + if (arg.keystoreData) this.addKeystoreData(arg.keystoreData); + } + } + /** + * Add a list of keys to add to the keystore + * @typedef {Object} keyinfo + * @property {string} sk - The private key. + * @property {string} nickname - The key nickname. + * @property {string} name - The key name. + * @property {string} network - Network name. + * @property {string} symbol - The token symbol. + * @param {Array.} keyList An array of keyinfo Object + */ + addKeys(keyList){ + assertTypes.isArray(keyList); + keyList.forEach(key => this.addKey(key)); + } + /** + * Add a key to the keystore + * @typedef {Object} keyinfo + * @property {string} sk - The private key. + * @property {string} nickname - The key nickname. + * @property {string} name - The key name. + * @property {string} network - Network name. + * @property {string} symbol - The token symbol. + * @param {keyinfo} keyInfo A keyinfo Object + */ + addKey(keyInfo){ + assertTypes.isObjectWithKeys(keyInfo); + assertTypes.isStringWithValue(keyInfo.sk); + if (validateTypes.isStringWithValue(keyInfo.vk)) delete keyInfo.vk; + this.keyList.addKey(keyInfo); + } + /** + * Load the keystore with the data from an existing keystore + * @param {string} keystoreData The contents of an existing encrypted keystore file + */ + addKeystoreData(keystoreData){ + if (validateTypes.isString(keystoreData)) keystoreData = JSON.parse(keystoreData); + if(this.validateKeyStore(keystoreData)){ + this.encryptedData = keystoreData; + } + } + /** + * Returns the password hint in a keystore file + * @param {String|undefined} keystoreData The contents of an existing encrypted keystore file if one wasn't supplied to the constructor + */ + getPasswordHint(keystoreData = undefined){ + if (!this.encryptedData && !keystoreData) throw new Error("No keystore data found.") + + if (keystoreData) { + if (validateTypes.isString(keystoreData)) keystoreData = JSON.parse(keystoreData); + } + else keystoreData = this.encryptedData; + + if (keystoreData.w) return decryptStrHash('n1ahcKc0lb', keystoreData.w); + else return "" + } + /** + * Removes a specific key from the keyList + * @param {Number} keyIndex The index of the key you want to remove + */ + deleteKey(keyIndex){ + assertTypes.isInteger(keyIndex); + if (this.keyList.numOfKeys() === 0) return + if (keyIndex < 0 || keyIndex >= this.keyList.numOfKeys()) throw new Error("Key index out of range.") + this.keyList.deleteKey(keyIndex); + } + /** + * Clears all keys from the keystore + */ + clearKeys(){ + this.keyList.clearKeys(); + } + /** + * Clears all keys from the keystore + * @return {Array.} An array of wallet objects + */ + get wallets() { + return this.keyList.getWallets() + } + /** + * Load the keystore with the data from an existing keystore + * @param {String} vk A 32 character long Lamden public key + * @return {Object} A wallet object + */ + getWallet(vk) { + return this.keyList.getWallet(vk) + } + /** + * Used to validate that a keystore is the proper Lamden Format (does not decrypt data) + * @param {String} keystoreData The contents of an existing encrypted keystore file + * @return {Boolean} valid + * @throws {Error} This is not a valid keystore file. + */ + validateKeyStore(keystoreData){ + assertTypes.isObjectWithKeys(keystoreData); + try{ + let encryptedData = JSON.parse(keystoreData.data); + if (!encryptedData.ct || !encryptedData.iv || !encryptedData.s){ + throw new Error("This is not a valid keystore file.") + } + } catch (e) { + throw new Error("This is not a valid keystore file.") + } + return true; + } + /** + * Create a Keystore text string from the keys contained in the Keystore instance + * @param {String} password A password to encrypt the data + * @param {String|undefined} hint An optional password hint. Not stored in clear text (obsured) but not encrypted with the password. + * @return {String} A JSON stringified object containing the encrypted data + * @throws {Error} Any errors from the encyption process + */ + createKeystore(password, hint = undefined) { + assertTypes.isStringWithValue(password); + if (hint){ + assertTypes.isStringWithValue(hint); + } + return this.keyList.createKeystore(password, hint) + } + /** + * Decrypt a keystore into a useable array of wallets. Any decrypted keys will be added to existing keys in the keystore. + * @param {String} password A password to encrypt the data + * @param {String|undefined} keystoreData The encrypted contents from a keystore file if not passed into the constructor. + * @throws {Error} Any errors from the encyption process + */ + decryptKeystore(password, keystoreData = undefined){ + if (keystoreData) this.addKeystoreData(keystoreData); + if (!this.encryptedData) throw new Error ("No keystoreData to decrypt.") + try{ + this.keyList.decryptKeystore(password, this.encryptedData.data); + }catch (e){ + throw new Error("Incorrect Keystore Password.") + } + } +} + +globalThis.Buffer = buffer.Buffer; + +var index = { + TransactionBuilder, + TransactionBatcher, + Masternode_API: LamdenMasterNode_API, + Network, + wallet, + Keystore, + Encoder, + utils, +}; + +module.exports = index; diff --git a/dist/esm/lamden.js b/dist/esm/lamden.js new file mode 100644 index 0000000..7569dcd --- /dev/null +++ b/dist/esm/lamden.js @@ -0,0 +1,22 @@ +var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function r(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})})),t}function n(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var i={exports:{}};!function(e){class t{constructor(){}getType(e){return Object.prototype.toString.call(e)}getClassName(e){try{return e.constructor.name}catch(e){}return this.getType(e)}isObject(e){return"[object Object]"===this.getType(e)}isFunction(e){return"[object Function]"===this.getType(e)}isString(e){return"[object String]"===this.getType(e)}isBoolean(e){return"[object Boolean]"===this.getType(e)}isArray(e){return"[object Array]"===this.getType(e)}isNumber(e){return"[object Number]"===this.getType(e)}isInteger(e){return!("[object Number]"!==this.getType(e)||!Number.isInteger(e))}isRegEx(e){return"[object RegExp]"===this.getType(e)}isStringHex(e){if(!this.isStringWithValue(e))return!1;let t=/([0-9]|[a-f])/gim;return(e.match(t)||[]).length===e.length}hasKeys(e,t){return!t.map((t=>t in e)).includes(!1)}isStringWithValue(e){return!(!this.isString(e)||""===e)}isObjectWithKeys(e){return!!(this.isObject(e)&&Object.keys(e).length>0)}isArrayWithValues(e){return!!(this.isArray(e)&&e.length>0)}isSpecificClass(e,t){return!!this.isObject(e)&&this.getClassName(e)===t}}class r{constructor(){this.validate=new t}isObject(e){if(!this.validate.isObject(e))throw new TypeError(`Expected type [object Object] but got ${this.validate.getType(e)}`);return!0}isFunction(e){if(!this.validate.isFunction(e))throw new TypeError(`Expected type [object Function] but got ${this.validate.getType(e)}`);return!0}isString(e){if(!this.validate.isString(e))throw new TypeError(`Expected type [object String] but got ${this.validate.getType(e)}`);return!0}isBoolean(e){if(!this.validate.isBoolean(e))throw new TypeError(`Expected type [object Boolean] but got ${this.validate.getType(e)}`);return!0}isArray(e){if(!this.validate.isArray(e))throw new TypeError(`Expected type [object Array] but got ${this.validate.getType(e)}`);return!0}isNumber(e){if(!this.validate.isNumber(e))throw new TypeError(`Expected type [object Number] but got ${this.validate.getType(e)}`);return!0}isInteger(e){if(!this.validate.isInteger(e))throw new TypeError(`Expected "${e}" to be an integer but got non-integer value`);return!0}isRegEx(e){if(!this.validate.isRegEx(e))throw new TypeError(`Expected type [object RegExp] but got ${this.validate.getType(e)}`);return!0}isStringHex(e){if(!this.validate.isStringHex(e))throw new TypeError(`Expected "${e}" to be hex but got non-hex value`);return!0}hasKeys(e,t){if(!this.validate.hasKeys(e,t))throw new TypeError(`Provided object does not contain all keys ${JSON.stringify(t)}`);return!0}isStringWithValue(e){if(!this.validate.isStringWithValue(e))throw new TypeError(`Expected "${e}" to be [object String] and not empty`);return!0}isObjectWithKeys(e){if(!this.validate.isObjectWithKeys(e))throw new TypeError(`Expected "${e}" to be [object Object] and have keys`);return!0}isArrayWithValues(e){if(!this.validate.isArrayWithValues(e))throw new TypeError(`Expected "${e}" to be [object Array] and not empty`);return!0}isSpecificClass(e,t){if(!this.validate.isSpecificClass(e,t))throw new TypeError(`Expected Object Class to be "${t}" but got ${this.validate.getClassName(e)}`);return!0}}const n=new t,i=new r;e.assertTypes=i,e.validateTypes=n,Object.defineProperty(e,"__esModule",{value:!0})}(i.exports);var o=t(i.exports),a={},s={},u=u||function(e,t){var r={},n=r.lib={},i=n.Base=function(){function e(){}return{extend:function(t){e.prototype=this;var r=new e;return t&&r.mixIn(t),r.hasOwnProperty("init")||(r.init=function(){r.$super.init.apply(this,arguments)}),r.init.prototype=r,r.$super=this,r},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),o=n.WordArray=i.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||s).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,i=e.sigBytes;if(this.clamp(),n%4)for(var o=0;o>>2]>>>24-o%4*8&255;t[n+o>>>2]|=a<<24-(n+o)%4*8}else if(r.length>65535)for(o=0;o>>2]=r[o>>>2];else t.push.apply(t,r);return this.sigBytes+=i,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var r=[],n=0;n>>2]>>>24-i%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new o.init(r,t/2)}},u=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],i=0;i>>2]>>>24-i%4*8&255;n.push(String.fromCharCode(o))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new o.init(r,t)}},h=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},l=n.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=h.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r=this._data,n=r.words,i=r.sigBytes,a=this.blockSize,s=i/(4*a),u=(s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0))*a,h=e.min(4*u,i);if(u){for(var l=0;l>>2]>>>24-o%4*8&255)<<16|(t[o+1>>>2]>>>24-(o+1)%4*8&255)<<8|t[o+2>>>2]>>>24-(o+2)%4*8&255,s=0;s<4&&o+.75*s>>6*(3-s)&63));var u=n.charAt(64);if(u)for(;i.length%4;)i.push(u);return i.join("")},parse:function(e){var t=e.length,r=this._map,n=r.charAt(64);if(n){var i=e.indexOf(n);-1!=i&&(t=i)}for(var o=[],a=0,s=0;s>>6-s%4*2;o[a>>>2]|=(u|h)<<24-a%4*8,a++}return l.create(o,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};var c=s.CryptoJS;!function(e){var t=c,r=t.lib,n=r.WordArray,i=r.Hasher,o=t.algo,a=[];!function(){for(var t=0;t<64;t++)a[t]=4294967296*e.abs(e.sin(t+1))|0}();var s=o.MD5=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,i=e[n];e[n]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var o=this._hash.words,s=e[t+0],c=e[t+1],d=e[t+2],p=e[t+3],g=e[t+4],y=e[t+5],b=e[t+6],m=e[t+7],v=e[t+8],w=e[t+9],_=e[t+10],E=e[t+11],S=e[t+12],k=e[t+13],x=e[t+14],R=e[t+15],A=o[0],T=o[1],B=o[2],O=o[3];A=u(A,T,B,O,s,7,a[0]),O=u(O,A,T,B,c,12,a[1]),B=u(B,O,A,T,d,17,a[2]),T=u(T,B,O,A,p,22,a[3]),A=u(A,T,B,O,g,7,a[4]),O=u(O,A,T,B,y,12,a[5]),B=u(B,O,A,T,b,17,a[6]),T=u(T,B,O,A,m,22,a[7]),A=u(A,T,B,O,v,7,a[8]),O=u(O,A,T,B,w,12,a[9]),B=u(B,O,A,T,_,17,a[10]),T=u(T,B,O,A,E,22,a[11]),A=u(A,T,B,O,S,7,a[12]),O=u(O,A,T,B,k,12,a[13]),B=u(B,O,A,T,x,17,a[14]),A=h(A,T=u(T,B,O,A,R,22,a[15]),B,O,c,5,a[16]),O=h(O,A,T,B,b,9,a[17]),B=h(B,O,A,T,E,14,a[18]),T=h(T,B,O,A,s,20,a[19]),A=h(A,T,B,O,y,5,a[20]),O=h(O,A,T,B,_,9,a[21]),B=h(B,O,A,T,R,14,a[22]),T=h(T,B,O,A,g,20,a[23]),A=h(A,T,B,O,w,5,a[24]),O=h(O,A,T,B,x,9,a[25]),B=h(B,O,A,T,p,14,a[26]),T=h(T,B,O,A,v,20,a[27]),A=h(A,T,B,O,k,5,a[28]),O=h(O,A,T,B,d,9,a[29]),B=h(B,O,A,T,m,14,a[30]),A=l(A,T=h(T,B,O,A,S,20,a[31]),B,O,y,4,a[32]),O=l(O,A,T,B,v,11,a[33]),B=l(B,O,A,T,E,16,a[34]),T=l(T,B,O,A,x,23,a[35]),A=l(A,T,B,O,c,4,a[36]),O=l(O,A,T,B,g,11,a[37]),B=l(B,O,A,T,m,16,a[38]),T=l(T,B,O,A,_,23,a[39]),A=l(A,T,B,O,k,4,a[40]),O=l(O,A,T,B,s,11,a[41]),B=l(B,O,A,T,p,16,a[42]),T=l(T,B,O,A,b,23,a[43]),A=l(A,T,B,O,w,4,a[44]),O=l(O,A,T,B,S,11,a[45]),B=l(B,O,A,T,R,16,a[46]),A=f(A,T=l(T,B,O,A,d,23,a[47]),B,O,s,6,a[48]),O=f(O,A,T,B,m,10,a[49]),B=f(B,O,A,T,x,15,a[50]),T=f(T,B,O,A,y,21,a[51]),A=f(A,T,B,O,S,6,a[52]),O=f(O,A,T,B,p,10,a[53]),B=f(B,O,A,T,_,15,a[54]),T=f(T,B,O,A,c,21,a[55]),A=f(A,T,B,O,v,6,a[56]),O=f(O,A,T,B,R,10,a[57]),B=f(B,O,A,T,b,15,a[58]),T=f(T,B,O,A,k,21,a[59]),A=f(A,T,B,O,g,6,a[60]),O=f(O,A,T,B,E,10,a[61]),B=f(B,O,A,T,d,15,a[62]),T=f(T,B,O,A,w,21,a[63]),o[0]=o[0]+A|0,o[1]=o[1]+T|0,o[2]=o[2]+B|0,o[3]=o[3]+O|0},_doFinalize:function(){var t=this._data,r=t.words,n=8*this._nDataBytes,i=8*t.sigBytes;r[i>>>5]|=128<<24-i%32;var o=e.floor(n/4294967296),a=n;r[15+(i+64>>>9<<4)]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8),r[14+(i+64>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),t.sigBytes=4*(r.length+1),this._process();for(var s=this._hash,u=s.words,h=0;h<4;h++){var l=u[h];u[h]=16711935&(l<<8|l>>>24)|4278255360&(l<<24|l>>>8)}return s},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});function u(e,t,r,n,i,o,a){var s=e+(t&r|~t&n)+i+a;return(s<>>32-o)+t}function h(e,t,r,n,i,o,a){var s=e+(t&n|r&~n)+i+a;return(s<>>32-o)+t}function l(e,t,r,n,i,o,a){var s=e+(t^r^n)+i+a;return(s<>>32-o)+t}function f(e,t,r,n,i,o,a){var s=e+(r^(t|~n))+i+a;return(s<>>32-o)+t}t.MD5=i._createHelper(s),t.HmacMD5=i._createHmacHelper(s)}(Math);var d=s.CryptoJS;!function(){var e=d,t=e.lib,r=t.Base,n=t.WordArray,i=e.algo,o=i.MD5,a=i.EvpKDF=r.extend({cfg:r.extend({keySize:4,hasher:o,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r=this.cfg,i=r.hasher.create(),o=n.create(),a=o.words,s=r.keySize,u=r.iterations;a.length>>2];e.sigBytes-=t}};r.BlockCipher=h.extend({cfg:h.cfg.extend({mode:c,padding:d}),reset:function(){h.reset.call(this);var e=this.cfg,t=e.iv,r=e.mode;if(this._xformMode==this._ENC_XFORM_MODE)var n=r.createEncryptor;else{n=r.createDecryptor;this._minBufferSize=1}this._mode=n.call(r,this,t&&t.words)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){e.pad(this._data,this.blockSize);var t=this._process(!0)}else{t=this._process(!0);e.unpad(t)}return t},blockSize:4});var g=r.CipherParams=n.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),y=(t.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;if(r)var n=i.create([1398893684,1701076831]).concat(r).concat(t);else n=t;return n.toString(s)},parse:function(e){var t=s.parse(e),r=t.words;if(1398893684==r[0]&&1701076831==r[1]){var n=i.create(r.slice(2,4));r.splice(0,4),t.sigBytes-=16}return g.create({ciphertext:t,salt:n})}},b=r.SerializableCipher=n.extend({cfg:n.extend({format:y}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var i=e.createEncryptor(r,n),o=i.finalize(t),a=i.cfg;return g.create({ciphertext:o,key:r,iv:a.iv,algorithm:e,mode:a.mode,padding:a.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(r,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),m=(t.kdf={}).OpenSSL={execute:function(e,t,r,n){n||(n=i.random(8));var o=u.create({keySize:t+r}).compute(e,n),a=i.create(o.words.slice(t),4*r);return o.sigBytes=4*t,g.create({key:o,iv:a,salt:n})}},v=r.PasswordBasedCipher=b.extend({cfg:b.cfg.extend({kdf:m}),encrypt:function(e,t,r,n){var i=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize);n.iv=i.iv;var o=b.encrypt.call(this,e,t,i.key,n);return o.mixIn(i),o},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);var i=n.kdf.execute(r,e.keySize,e.ivSize,t.salt);return n.iv=i.iv,b.decrypt.call(this,e,t,i.key,n)}})}();var g=s.CryptoJS;!function(){var e=g,t=e.lib.BlockCipher,r=e.algo,n=[],i=[],o=[],a=[],s=[],u=[],h=[],l=[],f=[],c=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,d=0;for(t=0;t<256;t++){var p=d^d<<1^d<<2^d<<3^d<<4;p=p>>>8^255&p^99,n[r]=p,i[p]=r;var g=e[r],y=e[g],b=e[y],m=257*e[p]^16843008*p;o[r]=m<<24|m>>>8,a[r]=m<<16|m>>>16,s[r]=m<<8|m>>>24,u[r]=m;m=16843009*b^65537*y^257*g^16843008*r;h[p]=m<<24|m>>>8,l[p]=m<<16|m>>>16,f[p]=m<<8|m>>>24,c[p]=m,r?(r=g^e[e[e[b^g]]],d^=e[e[d]]):r=d=1}}();var d=[0,1,2,4,8,16,32,64,128,27,54],p=r.AES=t.extend({_doReset:function(){for(var e=this._key,t=e.words,r=e.sigBytes/4,i=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],a=0;a6&&a%r==4&&(s=n[s>>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s]):(s=n[(s=s<<8|s>>>24)>>>24]<<24|n[s>>>16&255]<<16|n[s>>>8&255]<<8|n[255&s],s^=d[a/r|0]<<24),o[a]=o[a-r]^s}for(var u=this._invKeySchedule=[],p=0;p>>24]]^l[n[s>>>16&255]]^f[n[s>>>8&255]]^c[n[255&s]]}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,o,a,s,u,n)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,h,l,f,c,i);r=e[t+1];e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,i,o,a,s){for(var u=this._nRounds,h=e[t]^r[0],l=e[t+1]^r[1],f=e[t+2]^r[2],c=e[t+3]^r[3],d=4,p=1;p>>24]^i[l>>>16&255]^o[f>>>8&255]^a[255&c]^r[d++],y=n[l>>>24]^i[f>>>16&255]^o[c>>>8&255]^a[255&h]^r[d++],b=n[f>>>24]^i[c>>>16&255]^o[h>>>8&255]^a[255&l]^r[d++],m=n[c>>>24]^i[h>>>16&255]^o[l>>>8&255]^a[255&f]^r[d++];h=g,l=y,f=b,c=m}g=(s[h>>>24]<<24|s[l>>>16&255]<<16|s[f>>>8&255]<<8|s[255&c])^r[d++],y=(s[l>>>24]<<24|s[f>>>16&255]<<16|s[c>>>8&255]<<8|s[255&h])^r[d++],b=(s[f>>>24]<<24|s[c>>>16&255]<<16|s[h>>>8&255]<<8|s[255&l])^r[d++],m=(s[c>>>24]<<24|s[h>>>16&255]<<16|s[l>>>8&255]<<8|s[255&f])^r[d++];e[t]=g,e[t+1]=y,e[t+2]=b,e[t+3]=m},keySize:8});e.AES=t._createHelper(p)}();var y={},b=s.CryptoJS,m={stringify:function(e){var t={ct:e.ciphertext.toString(b.enc.Base64)};return e.iv&&(t.iv=e.iv.toString()),e.salt&&(t.s=e.salt.toString()),JSON.stringify(t)},parse:function(e){var t=JSON.parse(e),r=b.lib.CipherParams.create({ciphertext:b.enc.Base64.parse(t.ct)});return t.iv&&(r.iv=b.enc.Hex.parse(t.iv)),t.s&&(r.salt=b.enc.Hex.parse(t.s)),r}};y.JsonFormatter=m;var v=s.CryptoJS,w=y.JsonFormatter;a.CryptoJS=v,a.JsonFormatter=w;const{CryptoJS:_,JsonFormatter:E}=a,{validateTypes:S,assertTypes:k}=o;function x(e,t){k.isStringWithValue(e),k.isObject(t);return _.AES.encrypt(JSON.stringify(t),e,{format:E}).toString()}function R(e,t){k.isStringWithValue(e),k.isStringWithValue(t);try{const r=_.AES.decrypt(t,e,{format:E});return JSON.parse(_.enc.Utf8.stringify(r))}catch(e){return!1}}function A(e,t){k.isStringWithValue(e),k.isString(t);return _.AES.encrypt(t,e).toString()}function T(e,t){k.isStringWithValue(e),k.isStringWithValue(t);try{const r=_.AES.decrypt(t,e);return""!==_.enc.Utf8.stringify(r)&&_.enc.Utf8.stringify(r)}catch(e){return!1}}function B(e){return Array.prototype.map.call(new Uint8Array(e),(e=>("00"+e.toString(16)).slice(-2))).join("")}function O(e){for(var t=new Uint8Array(Math.ceil(e.length/2)),r=0;r>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function p(e,t,r,n,i){var o,a=0;for(o=0;o>>8)-1}function g(e,t,r,n){return p(e,t,r,n,16)}function y(e,t,r,n){return p(e,t,r,n,32)}function b(e,t,r,n){!function(e,t,r,n){for(var i,o=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,c=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,y=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,b=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,m=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,v=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,_=o,E=a,S=s,k=u,x=h,R=l,A=f,T=c,B=d,O=p,M=g,L=y,j=b,U=m,I=v,C=w,N=0;N<20;N+=2)_^=(i=(j^=(i=(B^=(i=(x^=(i=_+j|0)<<7|i>>>25)+_|0)<<9|i>>>23)+x|0)<<13|i>>>19)+B|0)<<18|i>>>14,R^=(i=(E^=(i=(U^=(i=(O^=(i=R+E|0)<<7|i>>>25)+R|0)<<9|i>>>23)+O|0)<<13|i>>>19)+U|0)<<18|i>>>14,M^=(i=(A^=(i=(S^=(i=(I^=(i=M+A|0)<<7|i>>>25)+M|0)<<9|i>>>23)+I|0)<<13|i>>>19)+S|0)<<18|i>>>14,C^=(i=(L^=(i=(T^=(i=(k^=(i=C+L|0)<<7|i>>>25)+C|0)<<9|i>>>23)+k|0)<<13|i>>>19)+T|0)<<18|i>>>14,_^=(i=(k^=(i=(S^=(i=(E^=(i=_+k|0)<<7|i>>>25)+_|0)<<9|i>>>23)+E|0)<<13|i>>>19)+S|0)<<18|i>>>14,R^=(i=(x^=(i=(T^=(i=(A^=(i=R+x|0)<<7|i>>>25)+R|0)<<9|i>>>23)+A|0)<<13|i>>>19)+T|0)<<18|i>>>14,M^=(i=(O^=(i=(B^=(i=(L^=(i=M+O|0)<<7|i>>>25)+M|0)<<9|i>>>23)+L|0)<<13|i>>>19)+B|0)<<18|i>>>14,C^=(i=(I^=(i=(U^=(i=(j^=(i=C+I|0)<<7|i>>>25)+C|0)<<9|i>>>23)+j|0)<<13|i>>>19)+U|0)<<18|i>>>14;_=_+o|0,E=E+a|0,S=S+s|0,k=k+u|0,x=x+h|0,R=R+l|0,A=A+f|0,T=T+c|0,B=B+d|0,O=O+p|0,M=M+g|0,L=L+y|0,j=j+b|0,U=U+m|0,I=I+v|0,C=C+w|0,e[0]=_>>>0&255,e[1]=_>>>8&255,e[2]=_>>>16&255,e[3]=_>>>24&255,e[4]=E>>>0&255,e[5]=E>>>8&255,e[6]=E>>>16&255,e[7]=E>>>24&255,e[8]=S>>>0&255,e[9]=S>>>8&255,e[10]=S>>>16&255,e[11]=S>>>24&255,e[12]=k>>>0&255,e[13]=k>>>8&255,e[14]=k>>>16&255,e[15]=k>>>24&255,e[16]=x>>>0&255,e[17]=x>>>8&255,e[18]=x>>>16&255,e[19]=x>>>24&255,e[20]=R>>>0&255,e[21]=R>>>8&255,e[22]=R>>>16&255,e[23]=R>>>24&255,e[24]=A>>>0&255,e[25]=A>>>8&255,e[26]=A>>>16&255,e[27]=A>>>24&255,e[28]=T>>>0&255,e[29]=T>>>8&255,e[30]=T>>>16&255,e[31]=T>>>24&255,e[32]=B>>>0&255,e[33]=B>>>8&255,e[34]=B>>>16&255,e[35]=B>>>24&255,e[36]=O>>>0&255,e[37]=O>>>8&255,e[38]=O>>>16&255,e[39]=O>>>24&255,e[40]=M>>>0&255,e[41]=M>>>8&255,e[42]=M>>>16&255,e[43]=M>>>24&255,e[44]=L>>>0&255,e[45]=L>>>8&255,e[46]=L>>>16&255,e[47]=L>>>24&255,e[48]=j>>>0&255,e[49]=j>>>8&255,e[50]=j>>>16&255,e[51]=j>>>24&255,e[52]=U>>>0&255,e[53]=U>>>8&255,e[54]=U>>>16&255,e[55]=U>>>24&255,e[56]=I>>>0&255,e[57]=I>>>8&255,e[58]=I>>>16&255,e[59]=I>>>24&255,e[60]=C>>>0&255,e[61]=C>>>8&255,e[62]=C>>>16&255,e[63]=C>>>24&255}(e,t,r,n)}function m(e,t,r,n){!function(e,t,r,n){for(var i,o=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,c=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,y=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,b=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,m=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,v=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,_=0;_<20;_+=2)o^=(i=(b^=(i=(d^=(i=(h^=(i=o+b|0)<<7|i>>>25)+o|0)<<9|i>>>23)+h|0)<<13|i>>>19)+d|0)<<18|i>>>14,l^=(i=(a^=(i=(m^=(i=(p^=(i=l+a|0)<<7|i>>>25)+l|0)<<9|i>>>23)+p|0)<<13|i>>>19)+m|0)<<18|i>>>14,g^=(i=(f^=(i=(s^=(i=(v^=(i=g+f|0)<<7|i>>>25)+g|0)<<9|i>>>23)+v|0)<<13|i>>>19)+s|0)<<18|i>>>14,w^=(i=(y^=(i=(c^=(i=(u^=(i=w+y|0)<<7|i>>>25)+w|0)<<9|i>>>23)+u|0)<<13|i>>>19)+c|0)<<18|i>>>14,o^=(i=(u^=(i=(s^=(i=(a^=(i=o+u|0)<<7|i>>>25)+o|0)<<9|i>>>23)+a|0)<<13|i>>>19)+s|0)<<18|i>>>14,l^=(i=(h^=(i=(c^=(i=(f^=(i=l+h|0)<<7|i>>>25)+l|0)<<9|i>>>23)+f|0)<<13|i>>>19)+c|0)<<18|i>>>14,g^=(i=(p^=(i=(d^=(i=(y^=(i=g+p|0)<<7|i>>>25)+g|0)<<9|i>>>23)+y|0)<<13|i>>>19)+d|0)<<18|i>>>14,w^=(i=(v^=(i=(m^=(i=(b^=(i=w+v|0)<<7|i>>>25)+w|0)<<9|i>>>23)+b|0)<<13|i>>>19)+m|0)<<18|i>>>14;e[0]=o>>>0&255,e[1]=o>>>8&255,e[2]=o>>>16&255,e[3]=o>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=g>>>0&255,e[9]=g>>>8&255,e[10]=g>>>16&255,e[11]=g>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=c>>>0&255,e[21]=c>>>8&255,e[22]=c>>>16&255,e[23]=c>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,t,r,n)}var v=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function w(e,t,r,n,i,o,a){var s,u,h=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)h[u]=0;for(u=0;u<8;u++)h[u]=o[u];for(;i>=64;){for(b(l,h,a,v),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&h[u])|0,h[u]=255&s,s>>>=8;i-=64,t+=64,n+=64}if(i>0)for(b(l,h,a,v),u=0;u=64;){for(b(u,s,i,v),a=0;a<64;a++)e[t+a]=u[a];for(o=1,a=8;a<16;a++)o=o+(255&s[a])|0,s[a]=255&o,o>>>=8;r-=64,t+=64}if(r>0)for(b(u,s,i,v),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),i=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|i<<9),o=255&e[8]|(255&e[9])<<8,this.r[4]=255&(i>>>4|o<<12),this.r[5]=o>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(o>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function x(e,t,r,n,i,o){var a=new k(o);return a.update(r,n,i),a.finish(e,t),0}function R(e,t,r,n,i,o){var a=new Uint8Array(16);return x(a,0,r,n,i,o),g(e,t,a,0)}function A(e,t,r,n,i){var o;if(r<32)return-1;for(S(e,0,t,0,r,n,i),x(e,16,e,32,r-32,e),o=0;o<16;o++)e[o]=0;return 0}function T(e,t,r,n,i){var o,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,i),0!==R(t,16,t,32,r-32,a))return-1;for(S(e,0,t,0,r,n,i),o=0;o<32;o++)e[o]=0;return 0}function B(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function O(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function M(e,t,r){for(var n,i=~(r-1),o=0;o<16;o++)n=i&(e[o]^t[o]),e[o]^=n,t[o]^=n}function L(e,r){var n,i,o,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(O(s),O(s),O(s),i=0;i<2;i++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),o=a[15]>>16&1,a[14]&=65535,M(s,a,1-o)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function j(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return L(r,e),L(n,t),y(r,0,n,0)}function I(e){var t=new Uint8Array(32);return L(t,e),1&t[0]}function C(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function N(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function P(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function D(e,t,r){var n,i,o=0,a=0,s=0,u=0,h=0,l=0,f=0,c=0,d=0,p=0,g=0,y=0,b=0,m=0,v=0,w=0,_=0,E=0,S=0,k=0,x=0,R=0,A=0,T=0,B=0,O=0,M=0,L=0,j=0,U=0,I=0,C=r[0],N=r[1],P=r[2],D=r[3],z=r[4],q=r[5],W=r[6],F=r[7],K=r[8],Y=r[9],H=r[10],$=r[11],V=r[12],G=r[13],J=r[14],X=r[15];o+=(n=t[0])*C,a+=n*N,s+=n*P,u+=n*D,h+=n*z,l+=n*q,f+=n*W,c+=n*F,d+=n*K,p+=n*Y,g+=n*H,y+=n*$,b+=n*V,m+=n*G,v+=n*J,w+=n*X,a+=(n=t[1])*C,s+=n*N,u+=n*P,h+=n*D,l+=n*z,f+=n*q,c+=n*W,d+=n*F,p+=n*K,g+=n*Y,y+=n*H,b+=n*$,m+=n*V,v+=n*G,w+=n*J,_+=n*X,s+=(n=t[2])*C,u+=n*N,h+=n*P,l+=n*D,f+=n*z,c+=n*q,d+=n*W,p+=n*F,g+=n*K,y+=n*Y,b+=n*H,m+=n*$,v+=n*V,w+=n*G,_+=n*J,E+=n*X,u+=(n=t[3])*C,h+=n*N,l+=n*P,f+=n*D,c+=n*z,d+=n*q,p+=n*W,g+=n*F,y+=n*K,b+=n*Y,m+=n*H,v+=n*$,w+=n*V,_+=n*G,E+=n*J,S+=n*X,h+=(n=t[4])*C,l+=n*N,f+=n*P,c+=n*D,d+=n*z,p+=n*q,g+=n*W,y+=n*F,b+=n*K,m+=n*Y,v+=n*H,w+=n*$,_+=n*V,E+=n*G,S+=n*J,k+=n*X,l+=(n=t[5])*C,f+=n*N,c+=n*P,d+=n*D,p+=n*z,g+=n*q,y+=n*W,b+=n*F,m+=n*K,v+=n*Y,w+=n*H,_+=n*$,E+=n*V,S+=n*G,k+=n*J,x+=n*X,f+=(n=t[6])*C,c+=n*N,d+=n*P,p+=n*D,g+=n*z,y+=n*q,b+=n*W,m+=n*F,v+=n*K,w+=n*Y,_+=n*H,E+=n*$,S+=n*V,k+=n*G,x+=n*J,R+=n*X,c+=(n=t[7])*C,d+=n*N,p+=n*P,g+=n*D,y+=n*z,b+=n*q,m+=n*W,v+=n*F,w+=n*K,_+=n*Y,E+=n*H,S+=n*$,k+=n*V,x+=n*G,R+=n*J,A+=n*X,d+=(n=t[8])*C,p+=n*N,g+=n*P,y+=n*D,b+=n*z,m+=n*q,v+=n*W,w+=n*F,_+=n*K,E+=n*Y,S+=n*H,k+=n*$,x+=n*V,R+=n*G,A+=n*J,T+=n*X,p+=(n=t[9])*C,g+=n*N,y+=n*P,b+=n*D,m+=n*z,v+=n*q,w+=n*W,_+=n*F,E+=n*K,S+=n*Y,k+=n*H,x+=n*$,R+=n*V,A+=n*G,T+=n*J,B+=n*X,g+=(n=t[10])*C,y+=n*N,b+=n*P,m+=n*D,v+=n*z,w+=n*q,_+=n*W,E+=n*F,S+=n*K,k+=n*Y,x+=n*H,R+=n*$,A+=n*V,T+=n*G,B+=n*J,O+=n*X,y+=(n=t[11])*C,b+=n*N,m+=n*P,v+=n*D,w+=n*z,_+=n*q,E+=n*W,S+=n*F,k+=n*K,x+=n*Y,R+=n*H,A+=n*$,T+=n*V,B+=n*G,O+=n*J,M+=n*X,b+=(n=t[12])*C,m+=n*N,v+=n*P,w+=n*D,_+=n*z,E+=n*q,S+=n*W,k+=n*F,x+=n*K,R+=n*Y,A+=n*H,T+=n*$,B+=n*V,O+=n*G,M+=n*J,L+=n*X,m+=(n=t[13])*C,v+=n*N,w+=n*P,_+=n*D,E+=n*z,S+=n*q,k+=n*W,x+=n*F,R+=n*K,A+=n*Y,T+=n*H,B+=n*$,O+=n*V,M+=n*G,L+=n*J,j+=n*X,v+=(n=t[14])*C,w+=n*N,_+=n*P,E+=n*D,S+=n*z,k+=n*q,x+=n*W,R+=n*F,A+=n*K,T+=n*Y,B+=n*H,O+=n*$,M+=n*V,L+=n*G,j+=n*J,U+=n*X,w+=(n=t[15])*C,a+=38*(E+=n*P),s+=38*(S+=n*D),u+=38*(k+=n*z),h+=38*(x+=n*q),l+=38*(R+=n*W),f+=38*(A+=n*F),c+=38*(T+=n*K),d+=38*(B+=n*Y),p+=38*(O+=n*H),g+=38*(M+=n*$),y+=38*(L+=n*V),b+=38*(j+=n*G),m+=38*(U+=n*J),v+=38*(I+=n*X),o=(n=(o+=38*(_+=n*N))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=(o+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),o+=i-1+37*(i-1),e[0]=o,e[1]=a,e[2]=s,e[3]=u,e[4]=h,e[5]=l,e[6]=f,e[7]=c,e[8]=d,e[9]=p,e[10]=g,e[11]=y,e[12]=b,e[13]=m,e[14]=v,e[15]=w}function z(e,t){D(e,t,t)}function q(e,r){var n,i=t();for(n=0;n<16;n++)i[n]=r[n];for(n=253;n>=0;n--)z(i,i),2!==n&&4!==n&&D(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}function W(e,r,n){var i,o,a=new Uint8Array(32),u=new Float64Array(80),h=t(),l=t(),f=t(),c=t(),d=t(),p=t();for(o=0;o<31;o++)a[o]=r[o];for(a[31]=127&r[31]|64,a[0]&=248,C(u,n),o=0;o<16;o++)l[o]=u[o],c[o]=h[o]=f[o]=0;for(h[0]=c[0]=1,o=254;o>=0;--o)M(h,l,i=a[o>>>3]>>>(7&o)&1),M(f,c,i),N(d,h,f),P(h,h,f),N(f,l,c),P(l,l,c),z(c,d),z(p,h),D(h,f,h),D(f,l,d),N(d,h,f),P(h,h,f),z(l,h),P(f,c,p),D(h,f,s),N(h,h,c),D(f,f,h),D(h,c,p),D(c,l,u),z(l,d),M(h,l,i),M(f,c,i);for(o=0;o<16;o++)u[o+16]=h[o],u[o+32]=f[o],u[o+48]=l[o],u[o+64]=c[o];var g=u.subarray(32),y=u.subarray(16);return q(g,g),D(y,y,g),L(e,y),0}function F(e,t){return W(e,t,i)}function K(e,t){return r(t,32),F(e,t)}function Y(e,t,r){var i=new Uint8Array(32);return W(i,r,t),m(e,n,i,v)}k.prototype.blocks=function(e,t,r){for(var n,i,o,a,s,u,h,l,f,c,d,p,g,y,b,m,v,w,_,E=this.fin?0:2048,S=this.h[0],k=this.h[1],x=this.h[2],R=this.h[3],A=this.h[4],T=this.h[5],B=this.h[6],O=this.h[7],M=this.h[8],L=this.h[9],j=this.r[0],U=this.r[1],I=this.r[2],C=this.r[3],N=this.r[4],P=this.r[5],D=this.r[6],z=this.r[7],q=this.r[8],W=this.r[9];r>=16;)c=f=0,c+=(S+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*j,c+=(k+=8191&(n>>>13|(i=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*W),c+=(x+=8191&(i>>>10|(o=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*q),c+=(R+=8191&(o>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*z),f=(c+=(A+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*D))>>>13,c&=8191,c+=(T+=s>>>1&8191)*(5*P),c+=(B+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*N),c+=(O+=8191&(u>>>11|(h=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*C),c+=(M+=8191&(h>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*I),d=f+=(c+=(L+=l>>>5|E)*(5*U))>>>13,d+=S*U,d+=k*j,d+=x*(5*W),d+=R*(5*q),f=(d+=A*(5*z))>>>13,d&=8191,d+=T*(5*D),d+=B*(5*P),d+=O*(5*N),d+=M*(5*C),f+=(d+=L*(5*I))>>>13,d&=8191,p=f,p+=S*I,p+=k*U,p+=x*j,p+=R*(5*W),f=(p+=A*(5*q))>>>13,p&=8191,p+=T*(5*z),p+=B*(5*D),p+=O*(5*P),p+=M*(5*N),g=f+=(p+=L*(5*C))>>>13,g+=S*C,g+=k*I,g+=x*U,g+=R*j,f=(g+=A*(5*W))>>>13,g&=8191,g+=T*(5*q),g+=B*(5*z),g+=O*(5*D),g+=M*(5*P),y=f+=(g+=L*(5*N))>>>13,y+=S*N,y+=k*C,y+=x*I,y+=R*U,f=(y+=A*j)>>>13,y&=8191,y+=T*(5*W),y+=B*(5*q),y+=O*(5*z),y+=M*(5*D),b=f+=(y+=L*(5*P))>>>13,b+=S*P,b+=k*N,b+=x*C,b+=R*I,f=(b+=A*U)>>>13,b&=8191,b+=T*j,b+=B*(5*W),b+=O*(5*q),b+=M*(5*z),m=f+=(b+=L*(5*D))>>>13,m+=S*D,m+=k*P,m+=x*N,m+=R*C,f=(m+=A*I)>>>13,m&=8191,m+=T*U,m+=B*j,m+=O*(5*W),m+=M*(5*q),v=f+=(m+=L*(5*z))>>>13,v+=S*z,v+=k*D,v+=x*P,v+=R*N,f=(v+=A*C)>>>13,v&=8191,v+=T*I,v+=B*U,v+=O*j,v+=M*(5*W),w=f+=(v+=L*(5*q))>>>13,w+=S*q,w+=k*z,w+=x*D,w+=R*P,f=(w+=A*N)>>>13,w&=8191,w+=T*C,w+=B*I,w+=O*U,w+=M*j,_=f+=(w+=L*(5*W))>>>13,_+=S*W,_+=k*q,_+=x*z,_+=R*D,f=(_+=A*P)>>>13,_&=8191,_+=T*N,_+=B*C,_+=O*I,_+=M*U,S=c=8191&(f=(f=((f+=(_+=L*j)>>>13)<<2)+f|0)+(c&=8191)|0),k=d+=f>>>=13,x=p&=8191,R=g&=8191,A=y&=8191,T=b&=8191,B=m&=8191,O=v&=8191,M=w&=8191,L=_&=8191,t+=16,r-=16;this.h[0]=S,this.h[1]=k,this.h[2]=x,this.h[3]=R,this.h[4]=A,this.h[5]=T,this.h[6]=B,this.h[7]=O,this.h[8]=M,this.h[9]=L},k.prototype.finish=function(e,t){var r,n,i,o,a=new Uint16Array(10);if(this.leftover){for(o=this.leftover,this.buffer[o++]=1;o<16;o++)this.buffer[o]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,o=2;o<10;o++)this.h[o]+=r,r=this.h[o]>>>13,this.h[o]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,o=1;o<10;o++)a[o]=this.h[o]+r,r=a[o]>>>13,a[o]&=8191;for(a[9]-=8192,n=(1^r)-1,o=0;o<10;o++)a[o]&=n;for(n=~n,o=0;o<10;o++)this.h[o]=this.h[o]&n|a[o];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),i=this.h[0]+this.pad[0],this.h[0]=65535&i,o=1;o<8;o++)i=(this.h[o]+this.pad[o]|0)+(i>>>16)|0,this.h[o]=65535&i;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},k.prototype.update=function(e,t,r){var n,i;if(this.leftover){for((i=16-this.leftover)>r&&(i=r),n=0;n=16&&(i=r-r%16,this.blocks(e,t,i),t+=i,r-=i),r){for(n=0;n=128;){for(E=0;E<16;E++)S=8*E+G,O[E]=r[S+0]<<24|r[S+1]<<16|r[S+2]<<8|r[S+3],M[E]=r[S+4]<<24|r[S+5]<<16|r[S+6]<<8|r[S+7];for(E=0;E<80;E++)if(i=L,o=j,a=U,s=I,u=C,h=N,l=P,c=z,d=q,p=W,g=F,y=K,b=Y,m=H,R=65535&(x=$),A=x>>>16,T=65535&(k=D),B=k>>>16,R+=65535&(x=(K>>>14|C<<18)^(K>>>18|C<<14)^(C>>>9|K<<23)),A+=x>>>16,T+=65535&(k=(C>>>14|K<<18)^(C>>>18|K<<14)^(K>>>9|C<<23)),B+=k>>>16,R+=65535&(x=K&Y^~K&H),A+=x>>>16,T+=65535&(k=C&N^~C&P),B+=k>>>16,R+=65535&(x=V[2*E+1]),A+=x>>>16,T+=65535&(k=V[2*E]),B+=k>>>16,k=O[E%16],A+=(x=M[E%16])>>>16,T+=65535&k,B+=k>>>16,T+=(A+=(R+=65535&x)>>>16)>>>16,R=65535&(x=_=65535&R|A<<16),A=x>>>16,T=65535&(k=w=65535&T|(B+=T>>>16)<<16),B=k>>>16,R+=65535&(x=(z>>>28|L<<4)^(L>>>2|z<<30)^(L>>>7|z<<25)),A+=x>>>16,T+=65535&(k=(L>>>28|z<<4)^(z>>>2|L<<30)^(z>>>7|L<<25)),B+=k>>>16,A+=(x=z&q^z&W^q&W)>>>16,T+=65535&(k=L&j^L&U^j&U),B+=k>>>16,f=65535&(T+=(A+=(R+=65535&x)>>>16)>>>16)|(B+=T>>>16)<<16,v=65535&R|A<<16,R=65535&(x=g),A=x>>>16,T=65535&(k=s),B=k>>>16,A+=(x=_)>>>16,T+=65535&(k=w),B+=k>>>16,j=i,U=o,I=a,C=s=65535&(T+=(A+=(R+=65535&x)>>>16)>>>16)|(B+=T>>>16)<<16,N=u,P=h,D=l,L=f,q=c,W=d,F=p,K=g=65535&R|A<<16,Y=y,H=b,$=m,z=v,E%16==15)for(S=0;S<16;S++)k=O[S],R=65535&(x=M[S]),A=x>>>16,T=65535&k,B=k>>>16,k=O[(S+9)%16],R+=65535&(x=M[(S+9)%16]),A+=x>>>16,T+=65535&k,B+=k>>>16,w=O[(S+1)%16],R+=65535&(x=((_=M[(S+1)%16])>>>1|w<<31)^(_>>>8|w<<24)^(_>>>7|w<<25)),A+=x>>>16,T+=65535&(k=(w>>>1|_<<31)^(w>>>8|_<<24)^w>>>7),B+=k>>>16,w=O[(S+14)%16],A+=(x=((_=M[(S+14)%16])>>>19|w<<13)^(w>>>29|_<<3)^(_>>>6|w<<26))>>>16,T+=65535&(k=(w>>>19|_<<13)^(_>>>29|w<<3)^w>>>6),B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,O[S]=65535&T|B<<16,M[S]=65535&R|A<<16;R=65535&(x=z),A=x>>>16,T=65535&(k=L),B=k>>>16,k=e[0],A+=(x=t[0])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[0]=L=65535&T|B<<16,t[0]=z=65535&R|A<<16,R=65535&(x=q),A=x>>>16,T=65535&(k=j),B=k>>>16,k=e[1],A+=(x=t[1])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[1]=j=65535&T|B<<16,t[1]=q=65535&R|A<<16,R=65535&(x=W),A=x>>>16,T=65535&(k=U),B=k>>>16,k=e[2],A+=(x=t[2])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[2]=U=65535&T|B<<16,t[2]=W=65535&R|A<<16,R=65535&(x=F),A=x>>>16,T=65535&(k=I),B=k>>>16,k=e[3],A+=(x=t[3])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[3]=I=65535&T|B<<16,t[3]=F=65535&R|A<<16,R=65535&(x=K),A=x>>>16,T=65535&(k=C),B=k>>>16,k=e[4],A+=(x=t[4])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[4]=C=65535&T|B<<16,t[4]=K=65535&R|A<<16,R=65535&(x=Y),A=x>>>16,T=65535&(k=N),B=k>>>16,k=e[5],A+=(x=t[5])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[5]=N=65535&T|B<<16,t[5]=Y=65535&R|A<<16,R=65535&(x=H),A=x>>>16,T=65535&(k=P),B=k>>>16,k=e[6],A+=(x=t[6])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[6]=P=65535&T|B<<16,t[6]=H=65535&R|A<<16,R=65535&(x=$),A=x>>>16,T=65535&(k=D),B=k>>>16,k=e[7],A+=(x=t[7])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[7]=D=65535&T|B<<16,t[7]=$=65535&R|A<<16,G+=128,n-=128}return n}function J(e,t,r){var n,i=new Int32Array(8),o=new Int32Array(8),a=new Uint8Array(256),s=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,o[0]=4089235720,o[1]=2227873595,o[2]=4271175723,o[3]=1595750129,o[4]=2917565137,o[5]=725511199,o[6]=4215389547,o[7]=327033209,G(i,o,t,r),r%=128,n=0;n=0;--i)Z(e,t,n=r[i/8|0]>>(7&i)&1),X(t,e),X(e,e),Z(e,t,n)}function te(e,r){var n=[t(),t(),t(),t()];B(n[0],l),B(n[1],f),B(n[2],a),D(n[3],l,f),ee(e,n,r)}function re(e,n,i){var o,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(i||r(n,32),J(a,n,32),a[0]&=248,a[31]&=127,a[31]|=64,te(s,a),Q(e,s),o=0;o<32;o++)n[o+32]=e[o];return 0}var ne=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ie(e,t){var r,n,i,o;for(n=63;n>=32;--n){for(r=0,i=n-32,o=n-12;i>8,t[i]-=256*r;t[i]+=r,t[n]=0}for(r=0,i=0;i<32;i++)t[i]+=r-(t[31]>>4)*ne[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*ne[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function oe(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;ie(e,r)}function ae(e,r,n,i){var o,a,s=new Uint8Array(64),u=new Uint8Array(64),h=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];J(s,i,32),s[0]&=248,s[31]&=127,s[31]|=64;var c=n+64;for(o=0;o=0;n--)z(i,i),1!==n&&D(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}(n,n),D(n,n,s),D(n,n,h),D(n,n,h),D(e[0],n,h),z(i,e[0]),D(i,i,h),j(i,s)&&D(e[0],e[0],c),z(i,e[0]),D(i,i,h),j(i,s)?-1:(I(e[0])===r[31]>>7&&P(e[0],o,e[0]),D(e[3],e[0],e[1]),0)}function ue(e,r,n,i){var o,a=new Uint8Array(32),s=new Uint8Array(64),u=[t(),t(),t(),t()],h=[t(),t(),t(),t()];if(n<64)return-1;if(se(h,i))return-1;for(o=0;o=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(ce);return re(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(pe(e),e.length!==ce)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;r0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function l(e){var t=h(e),r=t[0],n=t[1];return 3*(r+n)/4-n}function f(e,t,r){return 3*(t+r)/4-r}function c(e){var t,r,n=h(e),a=n[0],s=n[1],u=new o(f(e,a,s)),l=0,c=s>0?a-4:a;for(r=0;r>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t),1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u}function d(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function p(e,t,r){for(var n,i=[],o=t;ou?u:s+a));return 1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),o.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],2:[function(e,t,r){},{}],3:[function(e,t,r){(function(t){(function(){var t=e("base64-js"),n=e("ieee754");r.Buffer=s,r.SlowBuffer=b,r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()}catch(e){return!1}}function a(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=s.prototype,t}function s(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return f(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return c(e,t);if(ArrayBuffer.isView(e))return d(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(J(e,ArrayBuffer)||e&&J(e.buffer,ArrayBuffer))return p(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return s.from(n,t,r);var i=g(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return s.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function h(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function l(e,t,r){return h(e),e<=0?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)}function f(e){return h(e),a(e<0?0:0|y(e))}function c(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!s.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|m(e,t),n=a(r),i=n.write(e,t);return i!==r&&(n=n.slice(0,i)),n}function d(e){for(var t=e.length<0?0:0|y(e.length),r=a(t),n=0;n=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function b(e){return+e!=e&&(e=0),s.alloc(+e)}function m(e,t){if(s.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||J(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Y(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return V(e).length;default:if(i)return n?-1:Y(e).length;t=(""+t).toLowerCase(),i=!0}}function v(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return I(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return j(this,t,r);case"latin1":case"binary":return U(this,t,r);case"base64":return B(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function w(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=s.from(t,n)),s.isBuffer(t))return 0===t.length?-1:E(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):E(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function E(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function h(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var l=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var f=!0,c=0;ci&&(n=i):n=i;var o=t.length;n>o/2&&(n=o/2);for(var a=0;a239?4:h>223?3:h>191?2:1;if(i+f<=r)switch(f){case 1:h<128&&(l=h);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&h)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&h)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&h)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=f}return L(n)}r.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=o(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&s[Symbol.species]===s&&Object.defineProperty(s,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),s.poolSize=8192,s.from=function(e,t,r){return u(e,t,r)},s.prototype.__proto__=Uint8Array.prototype,s.__proto__=Uint8Array,s.alloc=function(e,t,r){return l(e,t,r)},s.allocUnsafe=function(e){return f(e)},s.allocUnsafeSlow=function(e){return f(e)},s.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==s.prototype},s.compare=function(e,t){if(J(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),J(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(e)||!s.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);it&&(e+=" ... "),""},s.prototype.compare=function(e,t,r,n,i){if(J(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),u=Math.min(o,a),h=this.slice(n,i),l=e.slice(t,r),f=0;f>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return S(this,e,t,r);case"utf8":case"utf-8":return k(this,e,t,r);case"ascii":return x(this,e,t,r);case"latin1":case"binary":return R(this,e,t,r);case"base64":return A(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var M=4096;function L(e){var t=e.length;if(t<=M)return String.fromCharCode.apply(String,e);for(var r="",n=0;nn)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,r,n,i,o){if(!s.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function D(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function z(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,t,r,4),n.write(e,t,r,i,23,4),r+4}function q(e,t,r,i,o){return t=+t,r>>>=0,o||D(e,t,r,8),n.write(e,t,r,i,52,8),r+8}s.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||N(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||N(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},s.prototype.readUInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),this[e]},s.prototype.readUInt16LE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]|this[e+1]<<8},s.prototype.readUInt16BE=function(e,t){return e>>>=0,t||N(e,2,this.length),this[e]<<8|this[e+1]},s.prototype.readUInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},s.prototype.readUInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},s.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},s.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||N(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},s.prototype.readInt8=function(e,t){return e>>>=0,t||N(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},s.prototype.readInt16LE=function(e,t){e>>>=0,t||N(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(e,t){e>>>=0,t||N(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},s.prototype.readInt32BE=function(e,t){return e>>>=0,t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},s.prototype.readFloatLE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!0,23,4)},s.prototype.readFloatBE=function(e,t){return e>>>=0,t||N(e,4,this.length),n.read(this,e,!1,23,4)},s.prototype.readDoubleLE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!0,52,8)},s.prototype.readDoubleBE=function(e,t){return e>>>=0,t||N(e,8,this.length),n.read(this,e,!1,52,8)},s.prototype.writeUIntLE=function(e,t,r,n){e=+e,t>>>=0,r>>>=0,n||P(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n||P(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},s.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,255,0),this[t]=255&e,t+1},s.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},s.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},s.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},s.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},s.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},s.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},s.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},s.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},s.prototype.writeFloatLE=function(e,t,r){return z(this,e,t,!0,r)},s.prototype.writeFloatBE=function(e,t,r){return z(this,e,t,!1,r)},s.prototype.writeDoubleLE=function(e,t,r){return q(this,e,t,!0,r)},s.prototype.writeDoubleBE=function(e,t,r){return q(this,e,t,!1,r)},s.prototype.copy=function(e,t,r,n){if(!s.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return i},s.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var i=e.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(e=i)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function H(e){for(var t=[],r=0;r>8,i=r%256,o.push(i),o.push(n);return o}function V(e){return t.toByteArray(F(e))}function G(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function J(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":1,buffer:3,ieee754:5}],4:[function(e,t,r){var n,i="object"==typeof Reflect?Reflect:null,o=i&&"function"==typeof i.apply?i.apply:function(e,t,r){return Function.prototype.apply.call(e,t,r)};function a(e){console&&console.warn&&console.warn(e)}n=i&&"function"==typeof i.ownKeys?i.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function u(){u.init.call(this)}t.exports=u,t.exports.once=w,u.EventEmitter=u,u.prototype._events=void 0,u.prototype._eventsCount=0,u.prototype._maxListeners=void 0;var h=10;function l(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function f(e){return void 0===e._maxListeners?u.defaultMaxListeners:e._maxListeners}function c(e,t,r,n){var i,o,s;if(l(r),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]),void 0===s)s=o[t]=r,++e._eventsCount;else if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),(i=f(e))>0&&s.length>i&&!s.warned){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,a(u)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function p(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=d.bind(n);return i.listener=r,n.wrapFn=i,i}function g(e,t,r){var n=e._events;if(void 0===n)return[];var i=n[t];return void 0===i?[]:"function"==typeof i?r?[i.listener||i]:[i]:r?v(i):b(i,i.length)}function y(e){var t=this._events;if(void 0!==t){var r=t[e];if("function"==typeof r)return 1;if(void 0!==r)return r.length}return 0}function b(e,t){for(var r=new Array(t),n=0;n0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var u=i[e];if(void 0===u)return!1;if("function"==typeof u)o(u,this,t);else{var h=u.length,l=b(u,h);for(r=0;r=0;o--)if(r[o]===t||r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;0===i?r.shift():m(r,i),1===r.length&&(n[e]=r[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},u.prototype.off=u.prototype.removeListener,u.prototype.removeAllListeners=function(e){var t,r,n;if(void 0===(r=this._events))return this;if(void 0===r.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==r[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete r[e]),this;if(0===arguments.length){var i,o=Object.keys(r);for(n=0;n=0;n--)this.removeListener(e,t[n]);return this},u.prototype.listeners=function(e){return g(this,e,!0)},u.prototype.rawListeners=function(e){return g(this,e,!1)},u.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):y.call(e,t)},u.prototype.listenerCount=y,u.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},{}],5:[function(e,t,r){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,c=r?-1:1,d=e[t+f];for(f+=c,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=c,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=c,l-=8);if(0===o)o=1-h;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=h}return(d?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,h=8*o-i-1,l=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?c/u:c*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,h-=8);e[r+d-p]|=128*g}},{}],6:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},{}],7:[function(e,t,r){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function i(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))} +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ +t.exports=function(e){return null!=e&&(n(e)||i(e)||!!e._isBuffer)}},{}],8:[function(e,t,r){var n,i,o=t.exports={};function a(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function u(e){if(n===setTimeout)return setTimeout(e,0);if((n===a||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}function h(e){if(i===clearTimeout)return clearTimeout(e);if((i===s||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{return i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:a}catch(e){n=a}try{i="function"==typeof clearTimeout?clearTimeout:s}catch(e){i=s}}();var l,f=[],c=!1,d=-1;function p(){c&&l&&(c=!1,l.length?f=l.concat(f):d=-1,f.length&&g())}function g(){if(!c){var e=u(p);c=!0;for(var t=f.length;t;){for(l=f,f=[];++d1)for(var r=1;r */ +var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:3}],10:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/lib/_stream_readable.js"),i.Writable=e("readable-stream/lib/_stream_writable.js"),i.Duplex=e("readable-stream/lib/_stream_duplex.js"),i.Transform=e("readable-stream/lib/_stream_transform.js"),i.PassThrough=e("readable-stream/lib/_stream_passthrough.js"),i.finished=e("readable-stream/lib/internal/streams/end-of-stream.js"),i.pipeline=e("readable-stream/lib/internal/streams/pipeline.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function h(e){if(l(),0===n.listenerCount(this,"error"))throw e}function l(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",h),e.removeListener("error",h),r.removeListener("end",l),r.removeListener("close",l),e.removeListener("close",l)}return r.on("error",h),e.on("error",h),r.on("end",l),r.on("close",l),e.on("close",l),e.emit("pipe",r),e}},{events:4,inherits:6,"readable-stream/lib/_stream_duplex.js":12,"readable-stream/lib/_stream_passthrough.js":13,"readable-stream/lib/_stream_readable.js":14,"readable-stream/lib/_stream_transform.js":15,"readable-stream/lib/_stream_writable.js":16,"readable-stream/lib/internal/streams/end-of-stream.js":20,"readable-stream/lib/internal/streams/pipeline.js":22}],11:[function(e,t,r){function n(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var i={};function o(e,t,r){function o(e,r,n){return"string"==typeof t?t:t(e,r,n)}r||(r=Error);var a=function(e){function t(t,r,n){return e.call(this,o(t,r,n))||this}return n(t,e),t}(r);a.prototype.name=r.name,a.prototype.code=e,i[e]=a}function a(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function s(e,t,r){return e.substr(!r||r<0?0:+r,t.length)===t}function u(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function h(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}o("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),o("ERR_INVALID_ARG_TYPE",(function(e,t,r){var n,i;if("string"==typeof t&&s(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be",u(e," argument"))i="The ".concat(e," ").concat(n," ").concat(a(t,"type"));else{var o=h(e,".")?"property":"argument";i='The "'.concat(e,'" ').concat(o," ").concat(n," ").concat(a(t,"type"))}return i+=". Received type ".concat(typeof r)}),TypeError),o("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),o("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),o("ERR_STREAM_PREMATURE_CLOSE","Premature close"),o("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),o("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),o("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),o("ERR_STREAM_WRITE_AFTER_END","write after end"),o("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),o("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),o("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=i},{}],12:[function(e,t,r){(function(r){(function(){var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=h;var i=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(h,i);for(var a=n(o.prototype),s=0;s0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===s.prototype||(t=h(t)),n)a.endEmitted?k(e,new S):O(e,a,t,!0);else if(a.ended)k(e,new _);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?O(e,a,t,!1):P(e,a)):O(e,a,t,!1)}else n||(a.reading=!1,P(e,a));return!a.ended&&(a.length=L?e=L:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function U(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=j(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function I(e,t){if(f("onEofChunk"),!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,t.sync?C(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function C(t){var r=t._readableState;f("emitReadable",r.needReadable,r.emittedReadable),r.needReadable=!1,r.emittedReadable||(f("emitReadable",r.flowing),r.emittedReadable=!0,e.nextTick(N,t))}function N(e){var t=e._readableState;f("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Y(e)}function P(t,r){r.readingMore||(r.readingMore=!0,e.nextTick(D,t,r))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function W(e){f("readable nexttick read 0"),e.read(0)}function F(t,r){r.resumeScheduled||(r.resumeScheduled=!0,e.nextTick(K,t,r))}function K(e,t){f("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Y(e),t.flowing&&!t.reading&&e.read(0)}function Y(e){var t=e._readableState;for(f("flow",t.flowing);t.flowing&&null!==e.read(););}function H(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function $(t){var r=t._readableState;f("endReadable",r.endEmitted),r.endEmitted||(r.ended=!0,e.nextTick(V,r,t))}function V(e,t){if(f("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function G(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return f("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?$(this):C(this),null;if(0===(e=U(e,t))&&t.ended)return 0===t.length&&$(this),null;var n,i=t.needReadable;return f("need readable",i),(0===t.length||t.length-e0?H(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&$(this)),null!==n&&this.emit("data",n),n},T.prototype._read=function(e){k(this,new E("_read()"))},T.prototype.pipe=function(t,r){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,f("pipe count=%d opts=%j",i.pipesCount,r);var a=r&&!1===r.end||t===e.stdout||t===e.stderr?b:u;function s(e,t){f("onunpipe"),e===n&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,c())}function u(){f("onend"),t.end()}i.endEmitted?e.nextTick(a):n.once("end",a),t.on("unpipe",s);var h=z(n);t.on("drain",h);var l=!1;function c(){f("cleanup"),t.removeListener("close",g),t.removeListener("finish",y),t.removeListener("drain",h),t.removeListener("error",p),t.removeListener("unpipe",s),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",d),l=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||h()}function d(e){f("ondata");var r=t.write(e);f("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==G(i.pipes,t))&&!l&&(f("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function p(e){f("onerror",e),b(),t.removeListener("error",p),0===o(t,"error")&&k(t,e)}function g(){t.removeListener("finish",y),b()}function y(){f("onfinish"),t.removeListener("close",g),b()}function b(){f("unpipe"),n.unpipe(t)}return n.on("data",d),R(t,"error",p),t.once("close",g),t.once("finish",y),t.emit("pipe",n),i.flowing||(f("pipe resume"),n.resume()),t},T.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===t&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,f("on readable",i.length,i.reading),i.length?C(this):i.reading||e.nextTick(W,this))),n},T.prototype.addListener=T.prototype.on,T.prototype.removeListener=function(t,r){var n=a.prototype.removeListener.call(this,t,r);return"readable"===t&&e.nextTick(q,this),n},T.prototype.removeAllListeners=function(t){var r=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==t&&void 0!==t||e.nextTick(q,this),r},T.prototype.resume=function(){var e=this._readableState;return e.flowing||(f("resume"),e.flowing=!e.readableListening,F(this,e)),e.paused=!1,this},T.prototype.pause=function(){return f("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(f("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},T.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(f("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){f("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new S(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(A.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(A.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),A.prototype._write=function(e,t,r){r(new b("_write()"))},A.prototype._writev=null,A.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||F(this,n,r),this},Object.defineProperty(A.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(A.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),A.prototype.destroy=d.destroy,A.prototype._undestroy=d.undestroy,A.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,t("_process"),void 0!==e?e:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":11,"./_stream_duplex":12,"./internal/streams/destroy":19,"./internal/streams/state":23,"./internal/streams/stream":24,_process:8,buffer:3,inherits:6,"util-deprecate":26}],17:[function(e,t,r){(function(r){(function(){var n;function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var o=e("./end-of-stream"),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),h=Symbol("ended"),l=Symbol("lastPromise"),f=Symbol("handlePromise"),c=Symbol("stream");function d(e,t){return{value:e,done:t}}function p(e){var t=e[a];if(null!==t){var r=e[c].read();null!==r&&(e[l]=null,e[a]=null,e[s]=null,t(d(r,!1)))}}function g(e){r.nextTick(p,e)}function y(e,t){return function(r,n){e.then((function(){t[h]?r(d(void 0,!0)):t[f](r,n)}),n)}}var b=Object.getPrototypeOf((function(){})),m=Object.setPrototypeOf((i(n={get stream(){return this[c]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[h])return Promise.resolve(d(void 0,!0));if(this[c].destroyed)return new Promise((function(t,n){r.nextTick((function(){e[u]?n(e[u]):t(d(void 0,!0))}))}));var n,i=this[l];if(i)n=new Promise(y(i,this));else{var o=this[c].read();if(null!==o)return Promise.resolve(d(o,!1));n=new Promise(this[f])}return this[l]=n,n}},Symbol.asyncIterator,(function(){return this})),i(n,"return",(function(){var e=this;return new Promise((function(t,r){e[c].destroy(null,(function(e){e?r(e):t(d(void 0,!0))}))}))})),n),b),v=function(e){var t,r=Object.create(m,(i(t={},c,{value:e,writable:!0}),i(t,a,{value:null,writable:!0}),i(t,s,{value:null,writable:!0}),i(t,u,{value:null,writable:!0}),i(t,h,{value:e._readableState.endEmitted,writable:!0}),i(t,f,{value:function(e,t){var n=r[c].read();n?(r[l]=null,r[a]=null,r[s]=null,e(d(n,!1))):(r[a]=e,r[s]=t)},writable:!0}),t));return r[l]=null,o(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=r[s];return null!==t&&(r[l]=null,r[a]=null,r[s]=null,t(e)),void(r[u]=e)}var n=r[a];null!==n&&(r[l]=null,r[a]=null,r[s]=null,n(d(void 0,!0))),r[h]=!0})),e.on("readable",g.bind(null,r)),r};t.exports=v}).call(this)}).call(this,e("_process"))},{"./end-of-stream":20,_process:8}],18:[function(e,t,r){function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function i(e){for(var t=1;t0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return h.alloc(0);for(var t=h.allocUnsafe(e>>>0),r=this.head,n=0;r;)c(r.data,t,n),n+=r.data.length,r=r.next;return t}},{key:"consume",value:function(e,t){var r;return ei.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0==(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=h.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,t}},{key:f,value:function(e,t){return l(this,i({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:3,util:2}],19:[function(e,t,r){(function(e){(function(){function r(t,r){var o=this,s=this._readableState&&this._readableState.destroyed,u=this._writableState&&this._writableState.destroyed;return s||u?(r?r(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(a,this,t)):e.nextTick(a,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!r&&t?o._writableState?o._writableState.errorEmitted?e.nextTick(i,o):(o._writableState.errorEmitted=!0,e.nextTick(n,o,t)):e.nextTick(n,o,t):r?(e.nextTick(i,o),r(t)):e.nextTick(i,o)})),this)}function n(e,t){a(e,t),i(e)}function i(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function o(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function a(e,t){e.emit("error",t)}function s(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:r,undestroy:o,errorOrDestroy:s}}).call(this)}).call(this,e("_process"))},{_process:8}],20:[function(e,t,r){var n=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function i(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i0,(function(e){n||(n=e),e&&o.forEach(f),a||(o.forEach(f),i(n))}))}));return t.reduce(c)}t.exports=p},{"../../../errors":11,"./end-of-stream":20}],23:[function(e,t,r){var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function i(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}function o(e,t,r,o){var a=i(t,o,r);if(null!=a){if(!isFinite(a)||Math.floor(a)!==a||a<0)throw new n(o?r:"highWaterMark",a);return Math.floor(a)}return e.objectMode?16:16384}t.exports={getHighWaterMark:o}},{"../../../errors":11}],24:[function(e,t,r){t.exports=e("events").EventEmitter},{events:4}],25:[function(e,t,r){var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function a(e){var t=o(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}function s(e){var t;switch(this.encoding=a(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=f,t=4;break;case"base64":this.text=y,this.end=b,t=3;break;default:return this.write=m,void(this.end=v)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function u(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function h(e,t,r){var n=t.length-1;if(n=0?(i>0&&(e.lastNeed=i-1),i):--n=0?(i>0&&(e.lastNeed=i-2),i):--n=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}function l(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function f(e){var t=this.lastTotal-this.lastNeed,r=l(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){var r=h(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function y(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function b(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function m(e){return e.toString(this.encoding)}function v(e){return e&&e.length?this.write(e):""}r.StringDecoder=s,s.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=this._blockSize;){for(var a=this._blockOffset;a0;++s)this._length[s]+=u,(u=this._length[s]/4294967296|0)>0&&(this._length[s]-=4294967296*u);return this},a.prototype._update=function(){throw new Error("_update is not implemented")},a.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},a.prototype._digest=function(){throw new Error("_digest is not implemented")},t.exports=a},{inherits:31,"safe-buffer":40,stream:10}],31:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],32:[function(e,t,r){var n=e("inherits"),i=e("hash-base"),o=e("safe-buffer").Buffer,a=new Array(16);function s(){i.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function u(e,t){return e<>>32-t}function h(e,t,r,n,i,o,a){return u(e+(t&r|~t&n)+i+o|0,a)+t|0}function l(e,t,r,n,i,o,a){return u(e+(t&n|r&~n)+i+o|0,a)+t|0}function f(e,t,r,n,i,o,a){return u(e+(t^r^n)+i+o|0,a)+t|0}function c(e,t,r,n,i,o,a){return u(e+(r^(t|~n))+i+o|0,a)+t|0}n(s,i),s.prototype._update=function(){for(var e=a,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d;r=h(r,n,i,o,e[0],3614090360,7),o=h(o,r,n,i,e[1],3905402710,12),i=h(i,o,r,n,e[2],606105819,17),n=h(n,i,o,r,e[3],3250441966,22),r=h(r,n,i,o,e[4],4118548399,7),o=h(o,r,n,i,e[5],1200080426,12),i=h(i,o,r,n,e[6],2821735955,17),n=h(n,i,o,r,e[7],4249261313,22),r=h(r,n,i,o,e[8],1770035416,7),o=h(o,r,n,i,e[9],2336552879,12),i=h(i,o,r,n,e[10],4294925233,17),n=h(n,i,o,r,e[11],2304563134,22),r=h(r,n,i,o,e[12],1804603682,7),o=h(o,r,n,i,e[13],4254626195,12),i=h(i,o,r,n,e[14],2792965006,17),r=l(r,n=h(n,i,o,r,e[15],1236535329,22),i,o,e[1],4129170786,5),o=l(o,r,n,i,e[6],3225465664,9),i=l(i,o,r,n,e[11],643717713,14),n=l(n,i,o,r,e[0],3921069994,20),r=l(r,n,i,o,e[5],3593408605,5),o=l(o,r,n,i,e[10],38016083,9),i=l(i,o,r,n,e[15],3634488961,14),n=l(n,i,o,r,e[4],3889429448,20),r=l(r,n,i,o,e[9],568446438,5),o=l(o,r,n,i,e[14],3275163606,9),i=l(i,o,r,n,e[3],4107603335,14),n=l(n,i,o,r,e[8],1163531501,20),r=l(r,n,i,o,e[13],2850285829,5),o=l(o,r,n,i,e[2],4243563512,9),i=l(i,o,r,n,e[7],1735328473,14),r=f(r,n=l(n,i,o,r,e[12],2368359562,20),i,o,e[5],4294588738,4),o=f(o,r,n,i,e[8],2272392833,11),i=f(i,o,r,n,e[11],1839030562,16),n=f(n,i,o,r,e[14],4259657740,23),r=f(r,n,i,o,e[1],2763975236,4),o=f(o,r,n,i,e[4],1272893353,11),i=f(i,o,r,n,e[7],4139469664,16),n=f(n,i,o,r,e[10],3200236656,23),r=f(r,n,i,o,e[13],681279174,4),o=f(o,r,n,i,e[0],3936430074,11),i=f(i,o,r,n,e[3],3572445317,16),n=f(n,i,o,r,e[6],76029189,23),r=f(r,n,i,o,e[9],3654602809,4),o=f(o,r,n,i,e[12],3873151461,11),i=f(i,o,r,n,e[15],530742520,16),r=c(r,n=f(n,i,o,r,e[2],3299628645,23),i,o,e[0],4096336452,6),o=c(o,r,n,i,e[7],1126891415,10),i=c(i,o,r,n,e[14],2878612391,15),n=c(n,i,o,r,e[5],4237533241,21),r=c(r,n,i,o,e[12],1700485571,6),o=c(o,r,n,i,e[3],2399980690,10),i=c(i,o,r,n,e[10],4293915773,15),n=c(n,i,o,r,e[1],2240044497,21),r=c(r,n,i,o,e[8],1873313359,6),o=c(o,r,n,i,e[15],4264355552,10),i=c(i,o,r,n,e[6],2734768916,15),n=c(n,i,o,r,e[13],1309151649,21),r=c(r,n,i,o,e[4],4149444226,6),o=c(o,r,n,i,e[11],3174756917,10),i=c(i,o,r,n,e[2],718787259,15),n=c(n,i,o,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0},s.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=o.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e},t.exports=s},{"hash-base":30,inherits:31,"safe-buffer":40}],33:[function(e,t,r){r.pbkdf2=e("./lib/async"),r.pbkdf2Sync=e("./lib/sync")},{"./lib/async":34,"./lib/sync":37}],34:[function(t,r,n){(function(e,n){(function(){var i,o=t("./precondition"),a=t("./default-encoding"),s=t("./sync"),u=t("safe-buffer").Buffer,h=n.crypto&&n.crypto.subtle,l={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},f=[];function c(e){if(n.process&&!n.process.browser)return Promise.resolve(!1);if(!h||!h.importKey||!h.deriveBits)return Promise.resolve(!1);if(void 0!==f[e])return f[e];var t=d(i=i||u.alloc(8),i,10,128,e).then((function(){return!0})).catch((function(){return!1}));return f[e]=t,t}function d(e,t,r,n,i){return h.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]).then((function(e){return h.deriveBits({name:"PBKDF2",salt:t,iterations:r,hash:{name:i}},e,n<<3)})).then((function(e){return u.from(e)}))}function p(t,r){t.then((function(t){e.nextTick((function(){r(null,t)}))}),(function(t){e.nextTick((function(){r(t)}))}))}r.exports=function(t,r,i,h,f,g){"function"==typeof f&&(g=f,f=void 0);var y=l[(f=f||"sha1").toLowerCase()];if(!y||"function"!=typeof n.Promise)return e.nextTick((function(){var e;try{e=s(t,r,i,h,f)}catch(e){return g(e)}g(null,e)}));if(o(t,r,i,h),"function"!=typeof g)throw new Error("No callback provided to pbkdf2");u.isBuffer(t)||(t=u.from(t,a)),u.isBuffer(r)||(r=u.from(r,a)),p(c(y).then((function(e){return e?d(t,r,i,h,y):s(t,r,i,h,f)})),g)}}).call(this)}).call(this,t("_process"),void 0!==e?e:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./default-encoding":35,"./precondition":36,"./sync":37,_process:8,"safe-buffer":40}],35:[function(e,t,r){(function(e){(function(){var r;r=e.browser||parseInt(e.version.split(".")[0].slice(1),10)>=6?"utf-8":"binary",t.exports=r}).call(this)}).call(this,e("_process"))},{_process:8}],36:[function(e,t,r){(function(e){(function(){var r=Math.pow(2,30)-1;function n(t,r){if("string"!=typeof t&&!e.isBuffer(t))throw new TypeError(r+" must be a buffer or string")}t.exports=function(e,t,i,o){if(n(e,"Password"),n(t,"Salt"),"number"!=typeof i)throw new TypeError("Iterations not a number");if(i<0)throw new TypeError("Bad iterations");if("number"!=typeof o)throw new TypeError("Key length not a number");if(o<0||o>r||o!=o)throw new TypeError("Bad key length")}}).call(this)}).call(this,{isBuffer:e("../../../../../../AppData/Roaming/npm/node_modules/browserify/node_modules/is-buffer/index.js")})},{"../../../../../../AppData/Roaming/npm/node_modules/browserify/node_modules/is-buffer/index.js":7}],37:[function(e,t,r){var n=e("create-hash/md5"),i=e("ripemd160"),o=e("sha.js"),a=e("./precondition"),s=e("./default-encoding"),u=e("safe-buffer").Buffer,h=u.alloc(128),l={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function f(e,t,r){var n=c(e),i="sha512"===e||"sha384"===e?128:64;t.length>i?t=n(t):t.lengtho)throw new RangeError("requested too many random bytes");var n=s.allocUnsafe(t);if(t>0)if(t>i)for(var a=0;a>>32-t}function g(e,t,r,n,i,o,a,s){return p(e+(t^r^n)+o+a|0,s)+i|0}function y(e,t,r,n,i,o,a,s){return p(e+(t&r|~t&n)+o+a|0,s)+i|0}function b(e,t,r,n,i,o,a,s){return p(e+((t|~r)^n)+o+a|0,s)+i|0}function m(e,t,r,n,i,o,a,s){return p(e+(t&n|r&~n)+o+a|0,s)+i|0}function v(e,t,r,n,i,o,a,s){return p(e+(t^(r|~n))+o+a|0,s)+i|0}i(d,o),d.prototype._update=function(){for(var e=a,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,d=0|this._e,w=0|this._a,_=0|this._b,E=0|this._c,S=0|this._d,k=0|this._e,x=0;x<80;x+=1){var R,A;x<16?(R=g(r,n,i,o,d,e[s[x]],f[0],h[x]),A=v(w,_,E,S,k,e[u[x]],c[0],l[x])):x<32?(R=y(r,n,i,o,d,e[s[x]],f[1],h[x]),A=m(w,_,E,S,k,e[u[x]],c[1],l[x])):x<48?(R=b(r,n,i,o,d,e[s[x]],f[2],h[x]),A=b(w,_,E,S,k,e[u[x]],c[2],l[x])):x<64?(R=m(r,n,i,o,d,e[s[x]],f[3],h[x]),A=y(w,_,E,S,k,e[u[x]],c[3],l[x])):(R=v(r,n,i,o,d,e[s[x]],f[4],h[x]),A=g(w,_,E,S,k,e[u[x]],c[4],l[x])),r=d,d=o,o=p(i,10),i=n,n=R,w=k,k=S,S=p(E,10),E=_,_=A}var T=this._b+i+S|0;this._b=this._c+o+k|0,this._c=this._d+d+w|0,this._d=this._e+r+_|0,this._e=this._a+n+E|0,this._a=T},d.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=n.alloc?n.alloc(20):new n(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e},t.exports=d},{buffer:3,"hash-base":30,inherits:31}],40:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:3}],41:[function(e,t,r){var n=e("safe-buffer").Buffer;function i(e,t){this._block=n.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}i.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=n.from(e,t));for(var r=this._block,i=this._blockSize,o=e.length,a=this._len,s=0;s=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},i.prototype._update=function(){throw new Error("_update must be implemented by subclass")},t.exports=i},{"safe-buffer":40}],42:[function(e,t,r){(r=t.exports=function(e){e=e.toLowerCase();var t=r[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t}).sha=e("./sha"),r.sha1=e("./sha1"),r.sha224=e("./sha224"),r.sha256=e("./sha256"),r.sha384=e("./sha384"),r.sha512=e("./sha512")},{"./sha":43,"./sha1":44,"./sha224":45,"./sha256":46,"./sha384":47,"./sha512":48}],43:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function h(e){return e<<5|e>>>27}function l(e){return e<<30|e>>>2}function f(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0;u<16;++u)t[u]=e.readInt32BE(4*u);for(;u<80;++u)t[u]=t[u-3]^t[u-8]^t[u-14]^t[u-16];for(var c=0;c<80;++c){var d=~~(c/20),p=h(r)+f(d,n,i,o)+s+t[c]+a[d]|0;s=o,o=i,i=l(n),n=r,r=p}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":41,inherits:31,"safe-buffer":40}],44:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1518500249,1859775393,-1894007588,-899497514],s=new Array(80);function u(){this.init(),this._w=s,i.call(this,64,56)}function h(e){return e<<1|e>>>31}function l(e){return e<<5|e>>>27}function f(e){return e<<30|e>>>2}function c(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}n(u,i),u.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0;u<16;++u)t[u]=e.readInt32BE(4*u);for(;u<80;++u)t[u]=h(t[u-3]^t[u-8]^t[u-14]^t[u-16]);for(var d=0;d<80;++d){var p=~~(d/20),g=l(r)+c(p,n,i,o)+s+t[d]+a[p]|0;s=o,o=i,i=f(n),n=r,r=g}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0},u.prototype._hash=function(){var e=o.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e},t.exports=u},{"./hash":41,inherits:31,"safe-buffer":40}],45:[function(e,t,r){var n=e("inherits"),i=e("./sha256"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(64);function u(){this.init(),this._w=s,o.call(this,64,56)}n(u,i),u.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e},t.exports=u},{"./hash":41,"./sha256":46,inherits:31,"safe-buffer":40}],46:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=new Array(64);function u(){this.init(),this._w=s,i.call(this,64,56)}function h(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function c(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function d(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function p(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}n(u,i),u.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,s=0|this._e,u=0|this._f,g=0|this._g,y=0|this._h,b=0;b<16;++b)t[b]=e.readInt32BE(4*b);for(;b<64;++b)t[b]=p(t[b-2])+t[b-7]+d(t[b-15])+t[b-16]|0;for(var m=0;m<64;++m){var v=y+c(s)+h(s,u,g)+a[m]+t[m]|0,w=f(r)+l(r,n,i)|0;y=g,g=u,u=s,s=o+v|0,o=i,i=n,n=r,r=v+w|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=o+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=g+this._g|0,this._h=y+this._h|0},u.prototype._hash=function(){var e=o.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e},t.exports=u},{"./hash":41,inherits:31,"safe-buffer":40}],47:[function(e,t,r){var n=e("inherits"),i=e("./sha512"),o=e("./hash"),a=e("safe-buffer").Buffer,s=new Array(160);function u(){this.init(),this._w=s,o.call(this,128,112)}n(u,i),u.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},u.prototype._hash=function(){var e=a.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e},t.exports=u},{"./hash":41,"./sha512":48,inherits:31,"safe-buffer":40}],48:[function(e,t,r){var n=e("inherits"),i=e("./hash"),o=e("safe-buffer").Buffer,a=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],s=new Array(160);function u(){this.init(),this._w=s,i.call(this,128,112)}function h(e,t,r){return r^e&(t^r)}function l(e,t,r){return e&t|r&(e|t)}function f(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function c(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function d(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function p(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function g(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function y(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function b(e,t){return e>>>0>>0?1:0}n(u,i),u.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},u.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,s=0|this._eh,u=0|this._fh,m=0|this._gh,v=0|this._hh,w=0|this._al,_=0|this._bl,E=0|this._cl,S=0|this._dl,k=0|this._el,x=0|this._fl,R=0|this._gl,A=0|this._hl,T=0;T<32;T+=2)t[T]=e.readInt32BE(4*T),t[T+1]=e.readInt32BE(4*T+4);for(;T<160;T+=2){var B=t[T-30],O=t[T-30+1],M=d(B,O),L=p(O,B),j=g(B=t[T-4],O=t[T-4+1]),U=y(O,B),I=t[T-14],C=t[T-14+1],N=t[T-32],P=t[T-32+1],D=L+C|0,z=M+I+b(D,L)|0;z=(z=z+j+b(D=D+U|0,U)|0)+N+b(D=D+P|0,P)|0,t[T]=z,t[T+1]=D}for(var q=0;q<160;q+=2){z=t[q],D=t[q+1];var W=l(r,n,i),F=l(w,_,E),K=f(r,w),Y=f(w,r),H=c(s,k),$=c(k,s),V=a[q],G=a[q+1],J=h(s,u,m),X=h(k,x,R),Z=A+$|0,Q=v+H+b(Z,A)|0;Q=(Q=(Q=Q+J+b(Z=Z+X|0,X)|0)+V+b(Z=Z+G|0,G)|0)+z+b(Z=Z+D|0,D)|0;var ee=Y+F|0,te=K+W+b(ee,Y)|0;v=m,A=R,m=u,R=x,u=s,x=k,s=o+Q+b(k=S+Z|0,S)|0,o=i,S=E,i=n,E=_,n=r,_=w,r=Q+te+b(w=Z+ee|0,Z)|0}this._al=this._al+w|0,this._bl=this._bl+_|0,this._cl=this._cl+E|0,this._dl=this._dl+S|0,this._el=this._el+k|0,this._fl=this._fl+x|0,this._gl=this._gl+R|0,this._hl=this._hl+A|0,this._ah=this._ah+r+b(this._al,w)|0,this._bh=this._bh+n+b(this._bl,_)|0,this._ch=this._ch+i+b(this._cl,E)|0,this._dh=this._dh+o+b(this._dl,S)|0,this._eh=this._eh+s+b(this._el,k)|0,this._fh=this._fh+u+b(this._fl,x)|0,this._gh=this._gh+m+b(this._gl,R)|0,this._hh=this._hh+v+b(this._hl,A)|0},u.prototype._hash=function(){var e=o.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e},t.exports=u},{"./hash":41,inherits:31,"safe-buffer":40}],49:[function(e,t,r){Object.defineProperty(r,"__esModule",{value:!0});const n={};let i;r.wordlists=n,r._default=i;try{r._default=i=e("./wordlists/czech.json"),n.czech=i}catch(e){}try{r._default=i=e("./wordlists/chinese_simplified.json"),n.chinese_simplified=i}catch(e){}try{r._default=i=e("./wordlists/chinese_traditional.json"),n.chinese_traditional=i}catch(e){}try{r._default=i=e("./wordlists/korean.json"),n.korean=i}catch(e){}try{r._default=i=e("./wordlists/french.json"),n.french=i}catch(e){}try{r._default=i=e("./wordlists/italian.json"),n.italian=i}catch(e){}try{r._default=i=e("./wordlists/spanish.json"),n.spanish=i}catch(e){}try{r._default=i=e("./wordlists/japanese.json"),n.japanese=i,n.JA=i}catch(e){}try{r._default=i=e("./wordlists/portuguese.json"),n.portuguese=i}catch(e){}try{r._default=i=e("./wordlists/english.json"),n.english=i,n.EN=i}catch(e){}},{"./wordlists/chinese_simplified.json":51,"./wordlists/chinese_traditional.json":void 0,"./wordlists/czech.json":void 0,"./wordlists/english.json":52,"./wordlists/french.json":void 0,"./wordlists/italian.json":void 0,"./wordlists/japanese.json":53,"./wordlists/korean.json":void 0,"./wordlists/portuguese.json":54,"./wordlists/spanish.json":void 0}],50:[function(e,t,r){(function(t){(function(){Object.defineProperty(r,"__esModule",{value:!0});const n=e("create-hash"),i=e("pbkdf2"),o=e("randombytes"),a=e("./_wordlists");let s=a._default;const u="Invalid mnemonic",h="Invalid entropy",l="Invalid mnemonic checksum",f="A wordlist is required but a default could not be found.\nPlease pass a 2048 word array explicitly.";function c(e,t,r,n,o){return Promise.resolve().then((()=>new Promise(((a,s)=>{const u=(e,t)=>e?s(e):a(t);i.pbkdf2(e,t,r,n,o,u)}))))}function d(e){return(e||"").normalize("NFKD")}function p(e,t,r){for(;e.lengthp(e.toString(2),"0",8))).join("")}function b(e){const t=8*e.length/32,r=n("sha256").update(e).digest();return y(Array.from(r)).slice(0,t)}function m(e){return"mnemonic"+(e||"")}function v(e,r){const n=t.from(d(e),"utf8"),o=t.from(m(d(r)),"utf8");return i.pbkdf2Sync(n,o,2048,64,"sha512")}function w(e,r){return Promise.resolve().then((()=>c(t.from(d(e),"utf8"),t.from(m(d(r)),"utf8"),2048,64,"sha512")))}function _(e,r){if(!(r=r||s))throw new Error(f);const n=d(e).split(" ");if(n.length%3!=0)throw new Error(u);const i=n.map((e=>{const t=r.indexOf(e);if(-1===t)throw new Error(u);return p(t.toString(2),"0",11)})).join(""),o=32*Math.floor(i.length/33),a=i.slice(0,o),c=i.slice(o),y=a.match(/(.{1,8})/g).map(g);if(y.length<16)throw new Error(h);if(y.length>32)throw new Error(h);if(y.length%4!=0)throw new Error(h);const m=t.from(y);if(b(m)!==c)throw new Error(l);return m.toString("hex")}function E(e,r){if(t.isBuffer(e)||(e=t.from(e,"hex")),!(r=r||s))throw new Error(f);if(e.length<16)throw new TypeError(h);if(e.length>32)throw new TypeError(h);if(e.length%4!=0)throw new TypeError(h);const n=(y(Array.from(e))+b(e)).match(/(.{1,11})/g).map((e=>{const t=g(e);return r[t]}));return"あいこくしん"===r[0]?n.join(" "):n.join(" ")}function S(e,t,r){if((e=e||128)%32!=0)throw new TypeError(h);return E((t=t||o)(e/8),r)}function k(e,t){try{_(e,t)}catch(e){return!1}return!0}function x(e){const t=a.wordlists[e];if(!t)throw new Error('Could not find wordlist for language "'+e+'"');s=t}function R(){if(!s)throw new Error("No Default Wordlist set");return Object.keys(a.wordlists).filter((e=>"JA"!==e&&"EN"!==e&&a.wordlists[e].every(((e,t)=>e===s[t]))))[0]}r.mnemonicToSeedSync=v,r.mnemonicToSeed=w,r.mnemonicToEntropy=_,r.entropyToMnemonic=E,r.generateMnemonic=S,r.validateMnemonic=k,r.setDefaultWordlist=x,r.getDefaultWordlist=R;var A=e("./_wordlists");r.wordlists=A.wordlists}).call(this)}).call(this,e("buffer").Buffer)},{"./_wordlists":49,buffer:3,"create-hash":28,pbkdf2:33,randombytes:38}],51:[function(e,t,r){t.exports=["的","一","是","在","不","了","有","和","人","这","中","大","为","上","个","国","我","以","要","他","时","来","用","们","生","到","作","地","于","出","就","分","对","成","会","可","主","发","年","动","同","工","也","能","下","过","子","说","产","种","面","而","方","后","多","定","行","学","法","所","民","得","经","十","三","之","进","着","等","部","度","家","电","力","里","如","水","化","高","自","二","理","起","小","物","现","实","加","量","都","两","体","制","机","当","使","点","从","业","本","去","把","性","好","应","开","它","合","还","因","由","其","些","然","前","外","天","政","四","日","那","社","义","事","平","形","相","全","表","间","样","与","关","各","重","新","线","内","数","正","心","反","你","明","看","原","又","么","利","比","或","但","质","气","第","向","道","命","此","变","条","只","没","结","解","问","意","建","月","公","无","系","军","很","情","者","最","立","代","想","已","通","并","提","直","题","党","程","展","五","果","料","象","员","革","位","入","常","文","总","次","品","式","活","设","及","管","特","件","长","求","老","头","基","资","边","流","路","级","少","图","山","统","接","知","较","将","组","见","计","别","她","手","角","期","根","论","运","农","指","几","九","区","强","放","决","西","被","干","做","必","战","先","回","则","任","取","据","处","队","南","给","色","光","门","即","保","治","北","造","百","规","热","领","七","海","口","东","导","器","压","志","世","金","增","争","济","阶","油","思","术","极","交","受","联","什","认","六","共","权","收","证","改","清","美","再","采","转","更","单","风","切","打","白","教","速","花","带","安","场","身","车","例","真","务","具","万","每","目","至","达","走","积","示","议","声","报","斗","完","类","八","离","华","名","确","才","科","张","信","马","节","话","米","整","空","元","况","今","集","温","传","土","许","步","群","广","石","记","需","段","研","界","拉","林","律","叫","且","究","观","越","织","装","影","算","低","持","音","众","书","布","复","容","儿","须","际","商","非","验","连","断","深","难","近","矿","千","周","委","素","技","备","半","办","青","省","列","习","响","约","支","般","史","感","劳","便","团","往","酸","历","市","克","何","除","消","构","府","称","太","准","精","值","号","率","族","维","划","选","标","写","存","候","毛","亲","快","效","斯","院","查","江","型","眼","王","按","格","养","易","置","派","层","片","始","却","专","状","育","厂","京","识","适","属","圆","包","火","住","调","满","县","局","照","参","红","细","引","听","该","铁","价","严","首","底","液","官","德","随","病","苏","失","尔","死","讲","配","女","黄","推","显","谈","罪","神","艺","呢","席","含","企","望","密","批","营","项","防","举","球","英","氧","势","告","李","台","落","木","帮","轮","破","亚","师","围","注","远","字","材","排","供","河","态","封","另","施","减","树","溶","怎","止","案","言","士","均","武","固","叶","鱼","波","视","仅","费","紧","爱","左","章","早","朝","害","续","轻","服","试","食","充","兵","源","判","护","司","足","某","练","差","致","板","田","降","黑","犯","负","击","范","继","兴","似","余","坚","曲","输","修","故","城","夫","够","送","笔","船","占","右","财","吃","富","春","职","觉","汉","画","功","巴","跟","虽","杂","飞","检","吸","助","升","阳","互","初","创","抗","考","投","坏","策","古","径","换","未","跑","留","钢","曾","端","责","站","简","述","钱","副","尽","帝","射","草","冲","承","独","令","限","阿","宣","环","双","请","超","微","让","控","州","良","轴","找","否","纪","益","依","优","顶","础","载","倒","房","突","坐","粉","敌","略","客","袁","冷","胜","绝","析","块","剂","测","丝","协","诉","念","陈","仍","罗","盐","友","洋","错","苦","夜","刑","移","频","逐","靠","混","母","短","皮","终","聚","汽","村","云","哪","既","距","卫","停","烈","央","察","烧","迅","境","若","印","洲","刻","括","激","孔","搞","甚","室","待","核","校","散","侵","吧","甲","游","久","菜","味","旧","模","湖","货","损","预","阻","毫","普","稳","乙","妈","植","息","扩","银","语","挥","酒","守","拿","序","纸","医","缺","雨","吗","针","刘","啊","急","唱","误","训","愿","审","附","获","茶","鲜","粮","斤","孩","脱","硫","肥","善","龙","演","父","渐","血","欢","械","掌","歌","沙","刚","攻","谓","盾","讨","晚","粒","乱","燃","矛","乎","杀","药","宁","鲁","贵","钟","煤","读","班","伯","香","介","迫","句","丰","培","握","兰","担","弦","蛋","沉","假","穿","执","答","乐","谁","顺","烟","缩","征","脸","喜","松","脚","困","异","免","背","星","福","买","染","井","概","慢","怕","磁","倍","祖","皇","促","静","补","评","翻","肉","践","尼","衣","宽","扬","棉","希","伤","操","垂","秋","宜","氢","套","督","振","架","亮","末","宪","庆","编","牛","触","映","雷","销","诗","座","居","抓","裂","胞","呼","娘","景","威","绿","晶","厚","盟","衡","鸡","孙","延","危","胶","屋","乡","临","陆","顾","掉","呀","灯","岁","措","束","耐","剧","玉","赵","跳","哥","季","课","凯","胡","额","款","绍","卷","齐","伟","蒸","殖","永","宗","苗","川","炉","岩","弱","零","杨","奏","沿","露","杆","探","滑","镇","饭","浓","航","怀","赶","库","夺","伊","灵","税","途","灭","赛","归","召","鼓","播","盘","裁","险","康","唯","录","菌","纯","借","糖","盖","横","符","私","努","堂","域","枪","润","幅","哈","竟","熟","虫","泽","脑","壤","碳","欧","遍","侧","寨","敢","彻","虑","斜","薄","庭","纳","弹","饲","伸","折","麦","湿","暗","荷","瓦","塞","床","筑","恶","户","访","塔","奇","透","梁","刀","旋","迹","卡","氯","遇","份","毒","泥","退","洗","摆","灰","彩","卖","耗","夏","择","忙","铜","献","硬","予","繁","圈","雪","函","亦","抽","篇","阵","阴","丁","尺","追","堆","雄","迎","泛","爸","楼","避","谋","吨","野","猪","旗","累","偏","典","馆","索","秦","脂","潮","爷","豆","忽","托","惊","塑","遗","愈","朱","替","纤","粗","倾","尚","痛","楚","谢","奋","购","磨","君","池","旁","碎","骨","监","捕","弟","暴","割","贯","殊","释","词","亡","壁","顿","宝","午","尘","闻","揭","炮","残","冬","桥","妇","警","综","招","吴","付","浮","遭","徐","您","摇","谷","赞","箱","隔","订","男","吹","园","纷","唐","败","宋","玻","巨","耕","坦","荣","闭","湾","键","凡","驻","锅","救","恩","剥","凝","碱","齿","截","炼","麻","纺","禁","废","盛","版","缓","净","睛","昌","婚","涉","筒","嘴","插","岸","朗","庄","街","藏","姑","贸","腐","奴","啦","惯","乘","伙","恢","匀","纱","扎","辩","耳","彪","臣","亿","璃","抵","脉","秀","萨","俄","网","舞","店","喷","纵","寸","汗","挂","洪","贺","闪","柬","爆","烯","津","稻","墙","软","勇","像","滚","厘","蒙","芳","肯","坡","柱","荡","腿","仪","旅","尾","轧","冰","贡","登","黎","削","钻","勒","逃","障","氨","郭","峰","币","港","伏","轨","亩","毕","擦","莫","刺","浪","秘","援","株","健","售","股","岛","甘","泡","睡","童","铸","汤","阀","休","汇","舍","牧","绕","炸","哲","磷","绩","朋","淡","尖","启","陷","柴","呈","徒","颜","泪","稍","忘","泵","蓝","拖","洞","授","镜","辛","壮","锋","贫","虚","弯","摩","泰","幼","廷","尊","窗","纲","弄","隶","疑","氏","宫","姐","震","瑞","怪","尤","琴","循","描","膜","违","夹","腰","缘","珠","穷","森","枝","竹","沟","催","绳","忆","邦","剩","幸","浆","栏","拥","牙","贮","礼","滤","钠","纹","罢","拍","咱","喊","袖","埃","勤","罚","焦","潜","伍","墨","欲","缝","姓","刊","饱","仿","奖","铝","鬼","丽","跨","默","挖","链","扫","喝","袋","炭","污","幕","诸","弧","励","梅","奶","洁","灾","舟","鉴","苯","讼","抱","毁","懂","寒","智","埔","寄","届","跃","渡","挑","丹","艰","贝","碰","拔","爹","戴","码","梦","芽","熔","赤","渔","哭","敬","颗","奔","铅","仲","虎","稀","妹","乏","珍","申","桌","遵","允","隆","螺","仓","魏","锐","晓","氮","兼","隐","碍","赫","拨","忠","肃","缸","牵","抢","博","巧","壳","兄","杜","讯","诚","碧","祥","柯","页","巡","矩","悲","灌","龄","伦","票","寻","桂","铺","圣","恐","恰","郑","趣","抬","荒","腾","贴","柔","滴","猛","阔","辆","妻","填","撤","储","签","闹","扰","紫","砂","递","戏","吊","陶","伐","喂","疗","瓶","婆","抚","臂","摸","忍","虾","蜡","邻","胸","巩","挤","偶","弃","槽","劲","乳","邓","吉","仁","烂","砖","租","乌","舰","伴","瓜","浅","丙","暂","燥","橡","柳","迷","暖","牌","秧","胆","详","簧","踏","瓷","谱","呆","宾","糊","洛","辉","愤","竞","隙","怒","粘","乃","绪","肩","籍","敏","涂","熙","皆","侦","悬","掘","享","纠","醒","狂","锁","淀","恨","牲","霸","爬","赏","逆","玩","陵","祝","秒","浙","貌","役","彼","悉","鸭","趋","凤","晨","畜","辈","秩","卵","署","梯","炎","滩","棋","驱","筛","峡","冒","啥","寿","译","浸","泉","帽","迟","硅","疆","贷","漏","稿","冠","嫩","胁","芯","牢","叛","蚀","奥","鸣","岭","羊","凭","串","塘","绘","酵","融","盆","锡","庙","筹","冻","辅","摄","袭","筋","拒","僚","旱","钾","鸟","漆","沈","眉","疏","添","棒","穗","硝","韩","逼","扭","侨","凉","挺","碗","栽","炒","杯","患","馏","劝","豪","辽","勃","鸿","旦","吏","拜","狗","埋","辊","掩","饮","搬","骂","辞","勾","扣","估","蒋","绒","雾","丈","朵","姆","拟","宇","辑","陕","雕","偿","蓄","崇","剪","倡","厅","咬","驶","薯","刷","斥","番","赋","奉","佛","浇","漫","曼","扇","钙","桃","扶","仔","返","俗","亏","腔","鞋","棱","覆","框","悄","叔","撞","骗","勘","旺","沸","孤","吐","孟","渠","屈","疾","妙","惜","仰","狠","胀","谐","抛","霉","桑","岗","嘛","衰","盗","渗","脏","赖","涌","甜","曹","阅","肌","哩","厉","烃","纬","毅","昨","伪","症","煮","叹","钉","搭","茎","笼","酷","偷","弓","锥","恒","杰","坑","鼻","翼","纶","叙","狱","逮","罐","络","棚","抑","膨","蔬","寺","骤","穆","冶","枯","册","尸","凸","绅","坯","牺","焰","轰","欣","晋","瘦","御","锭","锦","丧","旬","锻","垄","搜","扑","邀","亭","酯","迈","舒","脆","酶","闲","忧","酚","顽","羽","涨","卸","仗","陪","辟","惩","杭","姚","肚","捉","飘","漂","昆","欺","吾","郎","烷","汁","呵","饰","萧","雅","邮","迁","燕","撒","姻","赴","宴","烦","债","帐","斑","铃","旨","醇","董","饼","雏","姿","拌","傅","腹","妥","揉","贤","拆","歪","葡","胺","丢","浩","徽","昂","垫","挡","览","贪","慰","缴","汪","慌","冯","诺","姜","谊","凶","劣","诬","耀","昏","躺","盈","骑","乔","溪","丛","卢","抹","闷","咨","刮","驾","缆","悟","摘","铒","掷","颇","幻","柄","惠","惨","佳","仇","腊","窝","涤","剑","瞧","堡","泼","葱","罩","霍","捞","胎","苍","滨","俩","捅","湘","砍","霞","邵","萄","疯","淮","遂","熊","粪","烘","宿","档","戈","驳","嫂","裕","徙","箭","捐","肠","撑","晒","辨","殿","莲","摊","搅","酱","屏","疫","哀","蔡","堵","沫","皱","畅","叠","阁","莱","敲","辖","钩","痕","坝","巷","饿","祸","丘","玄","溜","曰","逻","彭","尝","卿","妨","艇","吞","韦","怨","矮","歇"]},{}],52:[function(e,t,r){t.exports=["abandon","ability","able","about","above","absent","absorb","abstract","absurd","abuse","access","accident","account","accuse","achieve","acid","acoustic","acquire","across","act","action","actor","actress","actual","adapt","add","addict","address","adjust","admit","adult","advance","advice","aerobic","affair","afford","afraid","again","age","agent","agree","ahead","aim","air","airport","aisle","alarm","album","alcohol","alert","alien","all","alley","allow","almost","alone","alpha","already","also","alter","always","amateur","amazing","among","amount","amused","analyst","anchor","ancient","anger","angle","angry","animal","ankle","announce","annual","another","answer","antenna","antique","anxiety","any","apart","apology","appear","apple","approve","april","arch","arctic","area","arena","argue","arm","armed","armor","army","around","arrange","arrest","arrive","arrow","art","artefact","artist","artwork","ask","aspect","assault","asset","assist","assume","asthma","athlete","atom","attack","attend","attitude","attract","auction","audit","august","aunt","author","auto","autumn","average","avocado","avoid","awake","aware","away","awesome","awful","awkward","axis","baby","bachelor","bacon","badge","bag","balance","balcony","ball","bamboo","banana","banner","bar","barely","bargain","barrel","base","basic","basket","battle","beach","bean","beauty","because","become","beef","before","begin","behave","behind","believe","below","belt","bench","benefit","best","betray","better","between","beyond","bicycle","bid","bike","bind","biology","bird","birth","bitter","black","blade","blame","blanket","blast","bleak","bless","blind","blood","blossom","blouse","blue","blur","blush","board","boat","body","boil","bomb","bone","bonus","book","boost","border","boring","borrow","boss","bottom","bounce","box","boy","bracket","brain","brand","brass","brave","bread","breeze","brick","bridge","brief","bright","bring","brisk","broccoli","broken","bronze","broom","brother","brown","brush","bubble","buddy","budget","buffalo","build","bulb","bulk","bullet","bundle","bunker","burden","burger","burst","bus","business","busy","butter","buyer","buzz","cabbage","cabin","cable","cactus","cage","cake","call","calm","camera","camp","can","canal","cancel","candy","cannon","canoe","canvas","canyon","capable","capital","captain","car","carbon","card","cargo","carpet","carry","cart","case","cash","casino","castle","casual","cat","catalog","catch","category","cattle","caught","cause","caution","cave","ceiling","celery","cement","census","century","cereal","certain","chair","chalk","champion","change","chaos","chapter","charge","chase","chat","cheap","check","cheese","chef","cherry","chest","chicken","chief","child","chimney","choice","choose","chronic","chuckle","chunk","churn","cigar","cinnamon","circle","citizen","city","civil","claim","clap","clarify","claw","clay","clean","clerk","clever","click","client","cliff","climb","clinic","clip","clock","clog","close","cloth","cloud","clown","club","clump","cluster","clutch","coach","coast","coconut","code","coffee","coil","coin","collect","color","column","combine","come","comfort","comic","common","company","concert","conduct","confirm","congress","connect","consider","control","convince","cook","cool","copper","copy","coral","core","corn","correct","cost","cotton","couch","country","couple","course","cousin","cover","coyote","crack","cradle","craft","cram","crane","crash","crater","crawl","crazy","cream","credit","creek","crew","cricket","crime","crisp","critic","crop","cross","crouch","crowd","crucial","cruel","cruise","crumble","crunch","crush","cry","crystal","cube","culture","cup","cupboard","curious","current","curtain","curve","cushion","custom","cute","cycle","dad","damage","damp","dance","danger","daring","dash","daughter","dawn","day","deal","debate","debris","decade","december","decide","decline","decorate","decrease","deer","defense","define","defy","degree","delay","deliver","demand","demise","denial","dentist","deny","depart","depend","deposit","depth","deputy","derive","describe","desert","design","desk","despair","destroy","detail","detect","develop","device","devote","diagram","dial","diamond","diary","dice","diesel","diet","differ","digital","dignity","dilemma","dinner","dinosaur","direct","dirt","disagree","discover","disease","dish","dismiss","disorder","display","distance","divert","divide","divorce","dizzy","doctor","document","dog","doll","dolphin","domain","donate","donkey","donor","door","dose","double","dove","draft","dragon","drama","drastic","draw","dream","dress","drift","drill","drink","drip","drive","drop","drum","dry","duck","dumb","dune","during","dust","dutch","duty","dwarf","dynamic","eager","eagle","early","earn","earth","easily","east","easy","echo","ecology","economy","edge","edit","educate","effort","egg","eight","either","elbow","elder","electric","elegant","element","elephant","elevator","elite","else","embark","embody","embrace","emerge","emotion","employ","empower","empty","enable","enact","end","endless","endorse","enemy","energy","enforce","engage","engine","enhance","enjoy","enlist","enough","enrich","enroll","ensure","enter","entire","entry","envelope","episode","equal","equip","era","erase","erode","erosion","error","erupt","escape","essay","essence","estate","eternal","ethics","evidence","evil","evoke","evolve","exact","example","excess","exchange","excite","exclude","excuse","execute","exercise","exhaust","exhibit","exile","exist","exit","exotic","expand","expect","expire","explain","expose","express","extend","extra","eye","eyebrow","fabric","face","faculty","fade","faint","faith","fall","false","fame","family","famous","fan","fancy","fantasy","farm","fashion","fat","fatal","father","fatigue","fault","favorite","feature","february","federal","fee","feed","feel","female","fence","festival","fetch","fever","few","fiber","fiction","field","figure","file","film","filter","final","find","fine","finger","finish","fire","firm","first","fiscal","fish","fit","fitness","fix","flag","flame","flash","flat","flavor","flee","flight","flip","float","flock","floor","flower","fluid","flush","fly","foam","focus","fog","foil","fold","follow","food","foot","force","forest","forget","fork","fortune","forum","forward","fossil","foster","found","fox","fragile","frame","frequent","fresh","friend","fringe","frog","front","frost","frown","frozen","fruit","fuel","fun","funny","furnace","fury","future","gadget","gain","galaxy","gallery","game","gap","garage","garbage","garden","garlic","garment","gas","gasp","gate","gather","gauge","gaze","general","genius","genre","gentle","genuine","gesture","ghost","giant","gift","giggle","ginger","giraffe","girl","give","glad","glance","glare","glass","glide","glimpse","globe","gloom","glory","glove","glow","glue","goat","goddess","gold","good","goose","gorilla","gospel","gossip","govern","gown","grab","grace","grain","grant","grape","grass","gravity","great","green","grid","grief","grit","grocery","group","grow","grunt","guard","guess","guide","guilt","guitar","gun","gym","habit","hair","half","hammer","hamster","hand","happy","harbor","hard","harsh","harvest","hat","have","hawk","hazard","head","health","heart","heavy","hedgehog","height","hello","helmet","help","hen","hero","hidden","high","hill","hint","hip","hire","history","hobby","hockey","hold","hole","holiday","hollow","home","honey","hood","hope","horn","horror","horse","hospital","host","hotel","hour","hover","hub","huge","human","humble","humor","hundred","hungry","hunt","hurdle","hurry","hurt","husband","hybrid","ice","icon","idea","identify","idle","ignore","ill","illegal","illness","image","imitate","immense","immune","impact","impose","improve","impulse","inch","include","income","increase","index","indicate","indoor","industry","infant","inflict","inform","inhale","inherit","initial","inject","injury","inmate","inner","innocent","input","inquiry","insane","insect","inside","inspire","install","intact","interest","into","invest","invite","involve","iron","island","isolate","issue","item","ivory","jacket","jaguar","jar","jazz","jealous","jeans","jelly","jewel","job","join","joke","journey","joy","judge","juice","jump","jungle","junior","junk","just","kangaroo","keen","keep","ketchup","key","kick","kid","kidney","kind","kingdom","kiss","kit","kitchen","kite","kitten","kiwi","knee","knife","knock","know","lab","label","labor","ladder","lady","lake","lamp","language","laptop","large","later","latin","laugh","laundry","lava","law","lawn","lawsuit","layer","lazy","leader","leaf","learn","leave","lecture","left","leg","legal","legend","leisure","lemon","lend","length","lens","leopard","lesson","letter","level","liar","liberty","library","license","life","lift","light","like","limb","limit","link","lion","liquid","list","little","live","lizard","load","loan","lobster","local","lock","logic","lonely","long","loop","lottery","loud","lounge","love","loyal","lucky","luggage","lumber","lunar","lunch","luxury","lyrics","machine","mad","magic","magnet","maid","mail","main","major","make","mammal","man","manage","mandate","mango","mansion","manual","maple","marble","march","margin","marine","market","marriage","mask","mass","master","match","material","math","matrix","matter","maximum","maze","meadow","mean","measure","meat","mechanic","medal","media","melody","melt","member","memory","mention","menu","mercy","merge","merit","merry","mesh","message","metal","method","middle","midnight","milk","million","mimic","mind","minimum","minor","minute","miracle","mirror","misery","miss","mistake","mix","mixed","mixture","mobile","model","modify","mom","moment","monitor","monkey","monster","month","moon","moral","more","morning","mosquito","mother","motion","motor","mountain","mouse","move","movie","much","muffin","mule","multiply","muscle","museum","mushroom","music","must","mutual","myself","mystery","myth","naive","name","napkin","narrow","nasty","nation","nature","near","neck","need","negative","neglect","neither","nephew","nerve","nest","net","network","neutral","never","news","next","nice","night","noble","noise","nominee","noodle","normal","north","nose","notable","note","nothing","notice","novel","now","nuclear","number","nurse","nut","oak","obey","object","oblige","obscure","observe","obtain","obvious","occur","ocean","october","odor","off","offer","office","often","oil","okay","old","olive","olympic","omit","once","one","onion","online","only","open","opera","opinion","oppose","option","orange","orbit","orchard","order","ordinary","organ","orient","original","orphan","ostrich","other","outdoor","outer","output","outside","oval","oven","over","own","owner","oxygen","oyster","ozone","pact","paddle","page","pair","palace","palm","panda","panel","panic","panther","paper","parade","parent","park","parrot","party","pass","patch","path","patient","patrol","pattern","pause","pave","payment","peace","peanut","pear","peasant","pelican","pen","penalty","pencil","people","pepper","perfect","permit","person","pet","phone","photo","phrase","physical","piano","picnic","picture","piece","pig","pigeon","pill","pilot","pink","pioneer","pipe","pistol","pitch","pizza","place","planet","plastic","plate","play","please","pledge","pluck","plug","plunge","poem","poet","point","polar","pole","police","pond","pony","pool","popular","portion","position","possible","post","potato","pottery","poverty","powder","power","practice","praise","predict","prefer","prepare","present","pretty","prevent","price","pride","primary","print","priority","prison","private","prize","problem","process","produce","profit","program","project","promote","proof","property","prosper","protect","proud","provide","public","pudding","pull","pulp","pulse","pumpkin","punch","pupil","puppy","purchase","purity","purpose","purse","push","put","puzzle","pyramid","quality","quantum","quarter","question","quick","quit","quiz","quote","rabbit","raccoon","race","rack","radar","radio","rail","rain","raise","rally","ramp","ranch","random","range","rapid","rare","rate","rather","raven","raw","razor","ready","real","reason","rebel","rebuild","recall","receive","recipe","record","recycle","reduce","reflect","reform","refuse","region","regret","regular","reject","relax","release","relief","rely","remain","remember","remind","remove","render","renew","rent","reopen","repair","repeat","replace","report","require","rescue","resemble","resist","resource","response","result","retire","retreat","return","reunion","reveal","review","reward","rhythm","rib","ribbon","rice","rich","ride","ridge","rifle","right","rigid","ring","riot","ripple","risk","ritual","rival","river","road","roast","robot","robust","rocket","romance","roof","rookie","room","rose","rotate","rough","round","route","royal","rubber","rude","rug","rule","run","runway","rural","sad","saddle","sadness","safe","sail","salad","salmon","salon","salt","salute","same","sample","sand","satisfy","satoshi","sauce","sausage","save","say","scale","scan","scare","scatter","scene","scheme","school","science","scissors","scorpion","scout","scrap","screen","script","scrub","sea","search","season","seat","second","secret","section","security","seed","seek","segment","select","sell","seminar","senior","sense","sentence","series","service","session","settle","setup","seven","shadow","shaft","shallow","share","shed","shell","sheriff","shield","shift","shine","ship","shiver","shock","shoe","shoot","shop","short","shoulder","shove","shrimp","shrug","shuffle","shy","sibling","sick","side","siege","sight","sign","silent","silk","silly","silver","similar","simple","since","sing","siren","sister","situate","six","size","skate","sketch","ski","skill","skin","skirt","skull","slab","slam","sleep","slender","slice","slide","slight","slim","slogan","slot","slow","slush","small","smart","smile","smoke","smooth","snack","snake","snap","sniff","snow","soap","soccer","social","sock","soda","soft","solar","soldier","solid","solution","solve","someone","song","soon","sorry","sort","soul","sound","soup","source","south","space","spare","spatial","spawn","speak","special","speed","spell","spend","sphere","spice","spider","spike","spin","spirit","split","spoil","sponsor","spoon","sport","spot","spray","spread","spring","spy","square","squeeze","squirrel","stable","stadium","staff","stage","stairs","stamp","stand","start","state","stay","steak","steel","stem","step","stereo","stick","still","sting","stock","stomach","stone","stool","story","stove","strategy","street","strike","strong","struggle","student","stuff","stumble","style","subject","submit","subway","success","such","sudden","suffer","sugar","suggest","suit","summer","sun","sunny","sunset","super","supply","supreme","sure","surface","surge","surprise","surround","survey","suspect","sustain","swallow","swamp","swap","swarm","swear","sweet","swift","swim","swing","switch","sword","symbol","symptom","syrup","system","table","tackle","tag","tail","talent","talk","tank","tape","target","task","taste","tattoo","taxi","teach","team","tell","ten","tenant","tennis","tent","term","test","text","thank","that","theme","then","theory","there","they","thing","this","thought","three","thrive","throw","thumb","thunder","ticket","tide","tiger","tilt","timber","time","tiny","tip","tired","tissue","title","toast","tobacco","today","toddler","toe","together","toilet","token","tomato","tomorrow","tone","tongue","tonight","tool","tooth","top","topic","topple","torch","tornado","tortoise","toss","total","tourist","toward","tower","town","toy","track","trade","traffic","tragic","train","transfer","trap","trash","travel","tray","treat","tree","trend","trial","tribe","trick","trigger","trim","trip","trophy","trouble","truck","true","truly","trumpet","trust","truth","try","tube","tuition","tumble","tuna","tunnel","turkey","turn","turtle","twelve","twenty","twice","twin","twist","two","type","typical","ugly","umbrella","unable","unaware","uncle","uncover","under","undo","unfair","unfold","unhappy","uniform","unique","unit","universe","unknown","unlock","until","unusual","unveil","update","upgrade","uphold","upon","upper","upset","urban","urge","usage","use","used","useful","useless","usual","utility","vacant","vacuum","vague","valid","valley","valve","van","vanish","vapor","various","vast","vault","vehicle","velvet","vendor","venture","venue","verb","verify","version","very","vessel","veteran","viable","vibrant","vicious","victory","video","view","village","vintage","violin","virtual","virus","visa","visit","visual","vital","vivid","vocal","voice","void","volcano","volume","vote","voyage","wage","wagon","wait","walk","wall","walnut","want","warfare","warm","warrior","wash","wasp","waste","water","wave","way","wealth","weapon","wear","weasel","weather","web","wedding","weekend","weird","welcome","west","wet","whale","what","wheat","wheel","when","where","whip","whisper","wide","width","wife","wild","will","win","window","wine","wing","wink","winner","winter","wire","wisdom","wise","wish","witness","wolf","woman","wonder","wood","wool","word","work","world","worry","worth","wrap","wreck","wrestle","wrist","write","wrong","yard","year","yellow","you","young","youth","zebra","zero","zone","zoo"]},{}],53:[function(e,t,r){t.exports=["あいこくしん","あいさつ","あいだ","あおぞら","あかちゃん","あきる","あけがた","あける","あこがれる","あさい","あさひ","あしあと","あじわう","あずかる","あずき","あそぶ","あたえる","あたためる","あたりまえ","あたる","あつい","あつかう","あっしゅく","あつまり","あつめる","あてな","あてはまる","あひる","あぶら","あぶる","あふれる","あまい","あまど","あまやかす","あまり","あみもの","あめりか","あやまる","あゆむ","あらいぐま","あらし","あらすじ","あらためる","あらゆる","あらわす","ありがとう","あわせる","あわてる","あんい","あんがい","あんこ","あんぜん","あんてい","あんない","あんまり","いいだす","いおん","いがい","いがく","いきおい","いきなり","いきもの","いきる","いくじ","いくぶん","いけばな","いけん","いこう","いこく","いこつ","いさましい","いさん","いしき","いじゅう","いじょう","いじわる","いずみ","いずれ","いせい","いせえび","いせかい","いせき","いぜん","いそうろう","いそがしい","いだい","いだく","いたずら","いたみ","いたりあ","いちおう","いちじ","いちど","いちば","いちぶ","いちりゅう","いつか","いっしゅん","いっせい","いっそう","いったん","いっち","いってい","いっぽう","いてざ","いてん","いどう","いとこ","いない","いなか","いねむり","いのち","いのる","いはつ","いばる","いはん","いびき","いひん","いふく","いへん","いほう","いみん","いもうと","いもたれ","いもり","いやがる","いやす","いよかん","いよく","いらい","いらすと","いりぐち","いりょう","いれい","いれもの","いれる","いろえんぴつ","いわい","いわう","いわかん","いわば","いわゆる","いんげんまめ","いんさつ","いんしょう","いんよう","うえき","うえる","うおざ","うがい","うかぶ","うかべる","うきわ","うくらいな","うくれれ","うけたまわる","うけつけ","うけとる","うけもつ","うける","うごかす","うごく","うこん","うさぎ","うしなう","うしろがみ","うすい","うすぎ","うすぐらい","うすめる","うせつ","うちあわせ","うちがわ","うちき","うちゅう","うっかり","うつくしい","うったえる","うつる","うどん","うなぎ","うなじ","うなずく","うなる","うねる","うのう","うぶげ","うぶごえ","うまれる","うめる","うもう","うやまう","うよく","うらがえす","うらぐち","うらない","うりあげ","うりきれ","うるさい","うれしい","うれゆき","うれる","うろこ","うわき","うわさ","うんこう","うんちん","うんてん","うんどう","えいえん","えいが","えいきょう","えいご","えいせい","えいぶん","えいよう","えいわ","えおり","えがお","えがく","えきたい","えくせる","えしゃく","えすて","えつらん","えのぐ","えほうまき","えほん","えまき","えもじ","えもの","えらい","えらぶ","えりあ","えんえん","えんかい","えんぎ","えんげき","えんしゅう","えんぜつ","えんそく","えんちょう","えんとつ","おいかける","おいこす","おいしい","おいつく","おうえん","おうさま","おうじ","おうせつ","おうたい","おうふく","おうべい","おうよう","おえる","おおい","おおう","おおどおり","おおや","おおよそ","おかえり","おかず","おがむ","おかわり","おぎなう","おきる","おくさま","おくじょう","おくりがな","おくる","おくれる","おこす","おこなう","おこる","おさえる","おさない","おさめる","おしいれ","おしえる","おじぎ","おじさん","おしゃれ","おそらく","おそわる","おたがい","おたく","おだやか","おちつく","おっと","おつり","おでかけ","おとしもの","おとなしい","おどり","おどろかす","おばさん","おまいり","おめでとう","おもいで","おもう","おもたい","おもちゃ","おやつ","おやゆび","およぼす","おらんだ","おろす","おんがく","おんけい","おんしゃ","おんせん","おんだん","おんちゅう","おんどけい","かあつ","かいが","がいき","がいけん","がいこう","かいさつ","かいしゃ","かいすいよく","かいぜん","かいぞうど","かいつう","かいてん","かいとう","かいふく","がいへき","かいほう","かいよう","がいらい","かいわ","かえる","かおり","かかえる","かがく","かがし","かがみ","かくご","かくとく","かざる","がぞう","かたい","かたち","がちょう","がっきゅう","がっこう","がっさん","がっしょう","かなざわし","かのう","がはく","かぶか","かほう","かほご","かまう","かまぼこ","かめれおん","かゆい","かようび","からい","かるい","かろう","かわく","かわら","がんか","かんけい","かんこう","かんしゃ","かんそう","かんたん","かんち","がんばる","きあい","きあつ","きいろ","ぎいん","きうい","きうん","きえる","きおう","きおく","きおち","きおん","きかい","きかく","きかんしゃ","ききて","きくばり","きくらげ","きけんせい","きこう","きこえる","きこく","きさい","きさく","きさま","きさらぎ","ぎじかがく","ぎしき","ぎじたいけん","ぎじにってい","ぎじゅつしゃ","きすう","きせい","きせき","きせつ","きそう","きぞく","きぞん","きたえる","きちょう","きつえん","ぎっちり","きつつき","きつね","きてい","きどう","きどく","きない","きなが","きなこ","きぬごし","きねん","きのう","きのした","きはく","きびしい","きひん","きふく","きぶん","きぼう","きほん","きまる","きみつ","きむずかしい","きめる","きもだめし","きもち","きもの","きゃく","きやく","ぎゅうにく","きよう","きょうりゅう","きらい","きらく","きりん","きれい","きれつ","きろく","ぎろん","きわめる","ぎんいろ","きんかくじ","きんじょ","きんようび","ぐあい","くいず","くうかん","くうき","くうぐん","くうこう","ぐうせい","くうそう","ぐうたら","くうふく","くうぼ","くかん","くきょう","くげん","ぐこう","くさい","くさき","くさばな","くさる","くしゃみ","くしょう","くすのき","くすりゆび","くせげ","くせん","ぐたいてき","くださる","くたびれる","くちこみ","くちさき","くつした","ぐっすり","くつろぐ","くとうてん","くどく","くなん","くねくね","くのう","くふう","くみあわせ","くみたてる","くめる","くやくしょ","くらす","くらべる","くるま","くれる","くろう","くわしい","ぐんかん","ぐんしょく","ぐんたい","ぐんて","けあな","けいかく","けいけん","けいこ","けいさつ","げいじゅつ","けいたい","げいのうじん","けいれき","けいろ","けおとす","けおりもの","げきか","げきげん","げきだん","げきちん","げきとつ","げきは","げきやく","げこう","げこくじょう","げざい","けさき","げざん","けしき","けしごむ","けしょう","げすと","けたば","けちゃっぷ","けちらす","けつあつ","けつい","けつえき","けっこん","けつじょ","けっせき","けってい","けつまつ","げつようび","げつれい","けつろん","げどく","けとばす","けとる","けなげ","けなす","けなみ","けぬき","げねつ","けねん","けはい","げひん","けぶかい","げぼく","けまり","けみかる","けむし","けむり","けもの","けらい","けろけろ","けわしい","けんい","けんえつ","けんお","けんか","げんき","けんげん","けんこう","けんさく","けんしゅう","けんすう","げんそう","けんちく","けんてい","けんとう","けんない","けんにん","げんぶつ","けんま","けんみん","けんめい","けんらん","けんり","こあくま","こいぬ","こいびと","ごうい","こうえん","こうおん","こうかん","ごうきゅう","ごうけい","こうこう","こうさい","こうじ","こうすい","ごうせい","こうそく","こうたい","こうちゃ","こうつう","こうてい","こうどう","こうない","こうはい","ごうほう","ごうまん","こうもく","こうりつ","こえる","こおり","ごかい","ごがつ","ごかん","こくご","こくさい","こくとう","こくない","こくはく","こぐま","こけい","こける","ここのか","こころ","こさめ","こしつ","こすう","こせい","こせき","こぜん","こそだて","こたい","こたえる","こたつ","こちょう","こっか","こつこつ","こつばん","こつぶ","こてい","こてん","ことがら","ことし","ことば","ことり","こなごな","こねこね","このまま","このみ","このよ","ごはん","こひつじ","こふう","こふん","こぼれる","ごまあぶら","こまかい","ごますり","こまつな","こまる","こむぎこ","こもじ","こもち","こもの","こもん","こやく","こやま","こゆう","こゆび","こよい","こよう","こりる","これくしょん","ころっけ","こわもて","こわれる","こんいん","こんかい","こんき","こんしゅう","こんすい","こんだて","こんとん","こんなん","こんびに","こんぽん","こんまけ","こんや","こんれい","こんわく","ざいえき","さいかい","さいきん","ざいげん","ざいこ","さいしょ","さいせい","ざいたく","ざいちゅう","さいてき","ざいりょう","さうな","さかいし","さがす","さかな","さかみち","さがる","さぎょう","さくし","さくひん","さくら","さこく","さこつ","さずかる","ざせき","さたん","さつえい","ざつおん","ざっか","ざつがく","さっきょく","ざっし","さつじん","ざっそう","さつたば","さつまいも","さてい","さといも","さとう","さとおや","さとし","さとる","さのう","さばく","さびしい","さべつ","さほう","さほど","さます","さみしい","さみだれ","さむけ","さめる","さやえんどう","さゆう","さよう","さよく","さらだ","ざるそば","さわやか","さわる","さんいん","さんか","さんきゃく","さんこう","さんさい","ざんしょ","さんすう","さんせい","さんそ","さんち","さんま","さんみ","さんらん","しあい","しあげ","しあさって","しあわせ","しいく","しいん","しうち","しえい","しおけ","しかい","しかく","じかん","しごと","しすう","じだい","したうけ","したぎ","したて","したみ","しちょう","しちりん","しっかり","しつじ","しつもん","してい","してき","してつ","じてん","じどう","しなぎれ","しなもの","しなん","しねま","しねん","しのぐ","しのぶ","しはい","しばかり","しはつ","しはらい","しはん","しひょう","しふく","じぶん","しへい","しほう","しほん","しまう","しまる","しみん","しむける","じむしょ","しめい","しめる","しもん","しゃいん","しゃうん","しゃおん","じゃがいも","しやくしょ","しゃくほう","しゃけん","しゃこ","しゃざい","しゃしん","しゃせん","しゃそう","しゃたい","しゃちょう","しゃっきん","じゃま","しゃりん","しゃれい","じゆう","じゅうしょ","しゅくはく","じゅしん","しゅっせき","しゅみ","しゅらば","じゅんばん","しょうかい","しょくたく","しょっけん","しょどう","しょもつ","しらせる","しらべる","しんか","しんこう","じんじゃ","しんせいじ","しんちく","しんりん","すあげ","すあし","すあな","ずあん","すいえい","すいか","すいとう","ずいぶん","すいようび","すうがく","すうじつ","すうせん","すおどり","すきま","すくう","すくない","すける","すごい","すこし","ずさん","すずしい","すすむ","すすめる","すっかり","ずっしり","ずっと","すてき","すてる","すねる","すのこ","すはだ","すばらしい","ずひょう","ずぶぬれ","すぶり","すふれ","すべて","すべる","ずほう","すぼん","すまい","すめし","すもう","すやき","すらすら","するめ","すれちがう","すろっと","すわる","すんぜん","すんぽう","せあぶら","せいかつ","せいげん","せいじ","せいよう","せおう","せかいかん","せきにん","せきむ","せきゆ","せきらんうん","せけん","せこう","せすじ","せたい","せたけ","せっかく","せっきゃく","ぜっく","せっけん","せっこつ","せっさたくま","せつぞく","せつだん","せつでん","せっぱん","せつび","せつぶん","せつめい","せつりつ","せなか","せのび","せはば","せびろ","せぼね","せまい","せまる","せめる","せもたれ","せりふ","ぜんあく","せんい","せんえい","せんか","せんきょ","せんく","せんげん","ぜんご","せんさい","せんしゅ","せんすい","せんせい","せんぞ","せんたく","せんちょう","せんてい","せんとう","せんぬき","せんねん","せんぱい","ぜんぶ","ぜんぽう","せんむ","せんめんじょ","せんもん","せんやく","せんゆう","せんよう","ぜんら","ぜんりゃく","せんれい","せんろ","そあく","そいとげる","そいね","そうがんきょう","そうき","そうご","そうしん","そうだん","そうなん","そうび","そうめん","そうり","そえもの","そえん","そがい","そげき","そこう","そこそこ","そざい","そしな","そせい","そせん","そそぐ","そだてる","そつう","そつえん","そっかん","そつぎょう","そっけつ","そっこう","そっせん","そっと","そとがわ","そとづら","そなえる","そなた","そふぼ","そぼく","そぼろ","そまつ","そまる","そむく","そむりえ","そめる","そもそも","そよかぜ","そらまめ","そろう","そんかい","そんけい","そんざい","そんしつ","そんぞく","そんちょう","ぞんび","ぞんぶん","そんみん","たあい","たいいん","たいうん","たいえき","たいおう","だいがく","たいき","たいぐう","たいけん","たいこ","たいざい","だいじょうぶ","だいすき","たいせつ","たいそう","だいたい","たいちょう","たいてい","だいどころ","たいない","たいねつ","たいのう","たいはん","だいひょう","たいふう","たいへん","たいほ","たいまつばな","たいみんぐ","たいむ","たいめん","たいやき","たいよう","たいら","たいりょく","たいる","たいわん","たうえ","たえる","たおす","たおる","たおれる","たかい","たかね","たきび","たくさん","たこく","たこやき","たさい","たしざん","だじゃれ","たすける","たずさわる","たそがれ","たたかう","たたく","ただしい","たたみ","たちばな","だっかい","だっきゃく","だっこ","だっしゅつ","だったい","たてる","たとえる","たなばた","たにん","たぬき","たのしみ","たはつ","たぶん","たべる","たぼう","たまご","たまる","だむる","ためいき","ためす","ためる","たもつ","たやすい","たよる","たらす","たりきほんがん","たりょう","たりる","たると","たれる","たれんと","たろっと","たわむれる","だんあつ","たんい","たんおん","たんか","たんき","たんけん","たんご","たんさん","たんじょうび","だんせい","たんそく","たんたい","だんち","たんてい","たんとう","だんな","たんにん","だんねつ","たんのう","たんぴん","だんぼう","たんまつ","たんめい","だんれつ","だんろ","だんわ","ちあい","ちあん","ちいき","ちいさい","ちえん","ちかい","ちから","ちきゅう","ちきん","ちけいず","ちけん","ちこく","ちさい","ちしき","ちしりょう","ちせい","ちそう","ちたい","ちたん","ちちおや","ちつじょ","ちてき","ちてん","ちぬき","ちぬり","ちのう","ちひょう","ちへいせん","ちほう","ちまた","ちみつ","ちみどろ","ちめいど","ちゃんこなべ","ちゅうい","ちゆりょく","ちょうし","ちょさくけん","ちらし","ちらみ","ちりがみ","ちりょう","ちるど","ちわわ","ちんたい","ちんもく","ついか","ついたち","つうか","つうじょう","つうはん","つうわ","つかう","つかれる","つくね","つくる","つけね","つける","つごう","つたえる","つづく","つつじ","つつむ","つとめる","つながる","つなみ","つねづね","つのる","つぶす","つまらない","つまる","つみき","つめたい","つもり","つもる","つよい","つるぼ","つるみく","つわもの","つわり","てあし","てあて","てあみ","ていおん","ていか","ていき","ていけい","ていこく","ていさつ","ていし","ていせい","ていたい","ていど","ていねい","ていひょう","ていへん","ていぼう","てうち","ておくれ","てきとう","てくび","でこぼこ","てさぎょう","てさげ","てすり","てそう","てちがい","てちょう","てつがく","てつづき","でっぱ","てつぼう","てつや","でぬかえ","てぬき","てぬぐい","てのひら","てはい","てぶくろ","てふだ","てほどき","てほん","てまえ","てまきずし","てみじか","てみやげ","てらす","てれび","てわけ","てわたし","でんあつ","てんいん","てんかい","てんき","てんぐ","てんけん","てんごく","てんさい","てんし","てんすう","でんち","てんてき","てんとう","てんない","てんぷら","てんぼうだい","てんめつ","てんらんかい","でんりょく","でんわ","どあい","といれ","どうかん","とうきゅう","どうぐ","とうし","とうむぎ","とおい","とおか","とおく","とおす","とおる","とかい","とかす","ときおり","ときどき","とくい","とくしゅう","とくてん","とくに","とくべつ","とけい","とける","とこや","とさか","としょかん","とそう","とたん","とちゅう","とっきゅう","とっくん","とつぜん","とつにゅう","とどける","ととのえる","とない","となえる","となり","とのさま","とばす","どぶがわ","とほう","とまる","とめる","ともだち","ともる","どようび","とらえる","とんかつ","どんぶり","ないかく","ないこう","ないしょ","ないす","ないせん","ないそう","なおす","ながい","なくす","なげる","なこうど","なさけ","なたでここ","なっとう","なつやすみ","ななおし","なにごと","なにもの","なにわ","なのか","なふだ","なまいき","なまえ","なまみ","なみだ","なめらか","なめる","なやむ","ならう","ならび","ならぶ","なれる","なわとび","なわばり","にあう","にいがた","にうけ","におい","にかい","にがて","にきび","にくしみ","にくまん","にげる","にさんかたんそ","にしき","にせもの","にちじょう","にちようび","にっか","にっき","にっけい","にっこう","にっさん","にっしょく","にっすう","にっせき","にってい","になう","にほん","にまめ","にもつ","にやり","にゅういん","にりんしゃ","にわとり","にんい","にんか","にんき","にんげん","にんしき","にんずう","にんそう","にんたい","にんち","にんてい","にんにく","にんぷ","にんまり","にんむ","にんめい","にんよう","ぬいくぎ","ぬかす","ぬぐいとる","ぬぐう","ぬくもり","ぬすむ","ぬまえび","ぬめり","ぬらす","ぬんちゃく","ねあげ","ねいき","ねいる","ねいろ","ねぐせ","ねくたい","ねくら","ねこぜ","ねこむ","ねさげ","ねすごす","ねそべる","ねだん","ねつい","ねっしん","ねつぞう","ねったいぎょ","ねぶそく","ねふだ","ねぼう","ねほりはほり","ねまき","ねまわし","ねみみ","ねむい","ねむたい","ねもと","ねらう","ねわざ","ねんいり","ねんおし","ねんかん","ねんきん","ねんぐ","ねんざ","ねんし","ねんちゃく","ねんど","ねんぴ","ねんぶつ","ねんまつ","ねんりょう","ねんれい","のいず","のおづま","のがす","のきなみ","のこぎり","のこす","のこる","のせる","のぞく","のぞむ","のたまう","のちほど","のっく","のばす","のはら","のべる","のぼる","のみもの","のやま","のらいぬ","のらねこ","のりもの","のりゆき","のれん","のんき","ばあい","はあく","ばあさん","ばいか","ばいく","はいけん","はいご","はいしん","はいすい","はいせん","はいそう","はいち","ばいばい","はいれつ","はえる","はおる","はかい","ばかり","はかる","はくしゅ","はけん","はこぶ","はさみ","はさん","はしご","ばしょ","はしる","はせる","ぱそこん","はそん","はたん","はちみつ","はつおん","はっかく","はづき","はっきり","はっくつ","はっけん","はっこう","はっさん","はっしん","はったつ","はっちゅう","はってん","はっぴょう","はっぽう","はなす","はなび","はにかむ","はぶらし","はみがき","はむかう","はめつ","はやい","はやし","はらう","はろうぃん","はわい","はんい","はんえい","はんおん","はんかく","はんきょう","ばんぐみ","はんこ","はんしゃ","はんすう","はんだん","ぱんち","ぱんつ","はんてい","はんとし","はんのう","はんぱ","はんぶん","はんぺん","はんぼうき","はんめい","はんらん","はんろん","ひいき","ひうん","ひえる","ひかく","ひかり","ひかる","ひかん","ひくい","ひけつ","ひこうき","ひこく","ひさい","ひさしぶり","ひさん","びじゅつかん","ひしょ","ひそか","ひそむ","ひたむき","ひだり","ひたる","ひつぎ","ひっこし","ひっし","ひつじゅひん","ひっす","ひつぜん","ぴったり","ぴっちり","ひつよう","ひてい","ひとごみ","ひなまつり","ひなん","ひねる","ひはん","ひびく","ひひょう","ひほう","ひまわり","ひまん","ひみつ","ひめい","ひめじし","ひやけ","ひやす","ひよう","びょうき","ひらがな","ひらく","ひりつ","ひりょう","ひるま","ひるやすみ","ひれい","ひろい","ひろう","ひろき","ひろゆき","ひんかく","ひんけつ","ひんこん","ひんしゅ","ひんそう","ぴんち","ひんぱん","びんぼう","ふあん","ふいうち","ふうけい","ふうせん","ぷうたろう","ふうとう","ふうふ","ふえる","ふおん","ふかい","ふきん","ふくざつ","ふくぶくろ","ふこう","ふさい","ふしぎ","ふじみ","ふすま","ふせい","ふせぐ","ふそく","ぶたにく","ふたん","ふちょう","ふつう","ふつか","ふっかつ","ふっき","ふっこく","ぶどう","ふとる","ふとん","ふのう","ふはい","ふひょう","ふへん","ふまん","ふみん","ふめつ","ふめん","ふよう","ふりこ","ふりる","ふるい","ふんいき","ぶんがく","ぶんぐ","ふんしつ","ぶんせき","ふんそう","ぶんぽう","へいあん","へいおん","へいがい","へいき","へいげん","へいこう","へいさ","へいしゃ","へいせつ","へいそ","へいたく","へいてん","へいねつ","へいわ","へきが","へこむ","べにいろ","べにしょうが","へらす","へんかん","べんきょう","べんごし","へんさい","へんたい","べんり","ほあん","ほいく","ぼうぎょ","ほうこく","ほうそう","ほうほう","ほうもん","ほうりつ","ほえる","ほおん","ほかん","ほきょう","ぼきん","ほくろ","ほけつ","ほけん","ほこう","ほこる","ほしい","ほしつ","ほしゅ","ほしょう","ほせい","ほそい","ほそく","ほたて","ほたる","ぽちぶくろ","ほっきょく","ほっさ","ほったん","ほとんど","ほめる","ほんい","ほんき","ほんけ","ほんしつ","ほんやく","まいにち","まかい","まかせる","まがる","まける","まこと","まさつ","まじめ","ますく","まぜる","まつり","まとめ","まなぶ","まぬけ","まねく","まほう","まもる","まゆげ","まよう","まろやか","まわす","まわり","まわる","まんが","まんきつ","まんぞく","まんなか","みいら","みうち","みえる","みがく","みかた","みかん","みけん","みこん","みじかい","みすい","みすえる","みせる","みっか","みつかる","みつける","みてい","みとめる","みなと","みなみかさい","みねらる","みのう","みのがす","みほん","みもと","みやげ","みらい","みりょく","みわく","みんか","みんぞく","むいか","むえき","むえん","むかい","むかう","むかえ","むかし","むぎちゃ","むける","むげん","むさぼる","むしあつい","むしば","むじゅん","むしろ","むすう","むすこ","むすぶ","むすめ","むせる","むせん","むちゅう","むなしい","むのう","むやみ","むよう","むらさき","むりょう","むろん","めいあん","めいうん","めいえん","めいかく","めいきょく","めいさい","めいし","めいそう","めいぶつ","めいれい","めいわく","めぐまれる","めざす","めした","めずらしい","めだつ","めまい","めやす","めんきょ","めんせき","めんどう","もうしあげる","もうどうけん","もえる","もくし","もくてき","もくようび","もちろん","もどる","もらう","もんく","もんだい","やおや","やける","やさい","やさしい","やすい","やすたろう","やすみ","やせる","やそう","やたい","やちん","やっと","やっぱり","やぶる","やめる","ややこしい","やよい","やわらかい","ゆうき","ゆうびんきょく","ゆうべ","ゆうめい","ゆけつ","ゆしゅつ","ゆせん","ゆそう","ゆたか","ゆちゃく","ゆでる","ゆにゅう","ゆびわ","ゆらい","ゆれる","ようい","ようか","ようきゅう","ようじ","ようす","ようちえん","よかぜ","よかん","よきん","よくせい","よくぼう","よけい","よごれる","よさん","よしゅう","よそう","よそく","よっか","よてい","よどがわく","よねつ","よやく","よゆう","よろこぶ","よろしい","らいう","らくがき","らくご","らくさつ","らくだ","らしんばん","らせん","らぞく","らたい","らっか","られつ","りえき","りかい","りきさく","りきせつ","りくぐん","りくつ","りけん","りこう","りせい","りそう","りそく","りてん","りねん","りゆう","りゅうがく","りよう","りょうり","りょかん","りょくちゃ","りょこう","りりく","りれき","りろん","りんご","るいけい","るいさい","るいじ","るいせき","るすばん","るりがわら","れいかん","れいぎ","れいせい","れいぞうこ","れいとう","れいぼう","れきし","れきだい","れんあい","れんけい","れんこん","れんさい","れんしゅう","れんぞく","れんらく","ろうか","ろうご","ろうじん","ろうそく","ろくが","ろこつ","ろじうら","ろしゅつ","ろせん","ろてん","ろめん","ろれつ","ろんぎ","ろんぱ","ろんぶん","ろんり","わかす","わかめ","わかやま","わかれる","わしつ","わじまし","わすれもの","わらう","われる"]},{}],54:[function(e,t,r){t.exports=["abacate","abaixo","abalar","abater","abduzir","abelha","aberto","abismo","abotoar","abranger","abreviar","abrigar","abrupto","absinto","absoluto","absurdo","abutre","acabado","acalmar","acampar","acanhar","acaso","aceitar","acelerar","acenar","acervo","acessar","acetona","achatar","acidez","acima","acionado","acirrar","aclamar","aclive","acolhida","acomodar","acoplar","acordar","acumular","acusador","adaptar","adega","adentro","adepto","adequar","aderente","adesivo","adeus","adiante","aditivo","adjetivo","adjunto","admirar","adorar","adquirir","adubo","adverso","advogado","aeronave","afastar","aferir","afetivo","afinador","afivelar","aflito","afluente","afrontar","agachar","agarrar","agasalho","agenciar","agilizar","agiota","agitado","agora","agradar","agreste","agrupar","aguardar","agulha","ajoelhar","ajudar","ajustar","alameda","alarme","alastrar","alavanca","albergue","albino","alcatra","aldeia","alecrim","alegria","alertar","alface","alfinete","algum","alheio","aliar","alicate","alienar","alinhar","aliviar","almofada","alocar","alpiste","alterar","altitude","alucinar","alugar","aluno","alusivo","alvo","amaciar","amador","amarelo","amassar","ambas","ambiente","ameixa","amenizar","amido","amistoso","amizade","amolador","amontoar","amoroso","amostra","amparar","ampliar","ampola","anagrama","analisar","anarquia","anatomia","andaime","anel","anexo","angular","animar","anjo","anomalia","anotado","ansioso","anterior","anuidade","anunciar","anzol","apagador","apalpar","apanhado","apego","apelido","apertada","apesar","apetite","apito","aplauso","aplicada","apoio","apontar","aposta","aprendiz","aprovar","aquecer","arame","aranha","arara","arcada","ardente","areia","arejar","arenito","aresta","argiloso","argola","arma","arquivo","arraial","arrebate","arriscar","arroba","arrumar","arsenal","arterial","artigo","arvoredo","asfaltar","asilado","aspirar","assador","assinar","assoalho","assunto","astral","atacado","atadura","atalho","atarefar","atear","atender","aterro","ateu","atingir","atirador","ativo","atoleiro","atracar","atrevido","atriz","atual","atum","auditor","aumentar","aura","aurora","autismo","autoria","autuar","avaliar","avante","avaria","avental","avesso","aviador","avisar","avulso","axila","azarar","azedo","azeite","azulejo","babar","babosa","bacalhau","bacharel","bacia","bagagem","baiano","bailar","baioneta","bairro","baixista","bajular","baleia","baliza","balsa","banal","bandeira","banho","banir","banquete","barato","barbado","baronesa","barraca","barulho","baseado","bastante","batata","batedor","batida","batom","batucar","baunilha","beber","beijo","beirada","beisebol","beldade","beleza","belga","beliscar","bendito","bengala","benzer","berimbau","berlinda","berro","besouro","bexiga","bezerro","bico","bicudo","bienal","bifocal","bifurcar","bigorna","bilhete","bimestre","bimotor","biologia","biombo","biosfera","bipolar","birrento","biscoito","bisneto","bispo","bissexto","bitola","bizarro","blindado","bloco","bloquear","boato","bobagem","bocado","bocejo","bochecha","boicotar","bolada","boletim","bolha","bolo","bombeiro","bonde","boneco","bonita","borbulha","borda","boreal","borracha","bovino","boxeador","branco","brasa","braveza","breu","briga","brilho","brincar","broa","brochura","bronzear","broto","bruxo","bucha","budismo","bufar","bule","buraco","busca","busto","buzina","cabana","cabelo","cabide","cabo","cabrito","cacau","cacetada","cachorro","cacique","cadastro","cadeado","cafezal","caiaque","caipira","caixote","cajado","caju","calafrio","calcular","caldeira","calibrar","calmante","calota","camada","cambista","camisa","camomila","campanha","camuflar","canavial","cancelar","caneta","canguru","canhoto","canivete","canoa","cansado","cantar","canudo","capacho","capela","capinar","capotar","capricho","captador","capuz","caracol","carbono","cardeal","careca","carimbar","carneiro","carpete","carreira","cartaz","carvalho","casaco","casca","casebre","castelo","casulo","catarata","cativar","caule","causador","cautelar","cavalo","caverna","cebola","cedilha","cegonha","celebrar","celular","cenoura","censo","centeio","cercar","cerrado","certeiro","cerveja","cetim","cevada","chacota","chaleira","chamado","chapada","charme","chatice","chave","chefe","chegada","cheiro","cheque","chicote","chifre","chinelo","chocalho","chover","chumbo","chutar","chuva","cicatriz","ciclone","cidade","cidreira","ciente","cigana","cimento","cinto","cinza","ciranda","circuito","cirurgia","citar","clareza","clero","clicar","clone","clube","coado","coagir","cobaia","cobertor","cobrar","cocada","coelho","coentro","coeso","cogumelo","coibir","coifa","coiote","colar","coleira","colher","colidir","colmeia","colono","coluna","comando","combinar","comentar","comitiva","comover","complexo","comum","concha","condor","conectar","confuso","congelar","conhecer","conjugar","consumir","contrato","convite","cooperar","copeiro","copiador","copo","coquetel","coragem","cordial","corneta","coronha","corporal","correio","cortejo","coruja","corvo","cosseno","costela","cotonete","couro","couve","covil","cozinha","cratera","cravo","creche","credor","creme","crer","crespo","criada","criminal","crioulo","crise","criticar","crosta","crua","cruzeiro","cubano","cueca","cuidado","cujo","culatra","culminar","culpar","cultura","cumprir","cunhado","cupido","curativo","curral","cursar","curto","cuspir","custear","cutelo","damasco","datar","debater","debitar","deboche","debulhar","decalque","decimal","declive","decote","decretar","dedal","dedicado","deduzir","defesa","defumar","degelo","degrau","degustar","deitado","deixar","delator","delegado","delinear","delonga","demanda","demitir","demolido","dentista","depenado","depilar","depois","depressa","depurar","deriva","derramar","desafio","desbotar","descanso","desenho","desfiado","desgaste","desigual","deslize","desmamar","desova","despesa","destaque","desviar","detalhar","detentor","detonar","detrito","deusa","dever","devido","devotado","dezena","diagrama","dialeto","didata","difuso","digitar","dilatado","diluente","diminuir","dinastia","dinheiro","diocese","direto","discreta","disfarce","disparo","disquete","dissipar","distante","ditador","diurno","diverso","divisor","divulgar","dizer","dobrador","dolorido","domador","dominado","donativo","donzela","dormente","dorsal","dosagem","dourado","doutor","drenagem","drible","drogaria","duelar","duende","dueto","duplo","duquesa","durante","duvidoso","eclodir","ecoar","ecologia","edificar","edital","educado","efeito","efetivar","ejetar","elaborar","eleger","eleitor","elenco","elevador","eliminar","elogiar","embargo","embolado","embrulho","embutido","emenda","emergir","emissor","empatia","empenho","empinado","empolgar","emprego","empurrar","emulador","encaixe","encenado","enchente","encontro","endeusar","endossar","enfaixar","enfeite","enfim","engajado","engenho","englobar","engomado","engraxar","enguia","enjoar","enlatar","enquanto","enraizar","enrolado","enrugar","ensaio","enseada","ensino","ensopado","entanto","enteado","entidade","entortar","entrada","entulho","envergar","enviado","envolver","enxame","enxerto","enxofre","enxuto","epiderme","equipar","ereto","erguido","errata","erva","ervilha","esbanjar","esbelto","escama","escola","escrita","escuta","esfinge","esfolar","esfregar","esfumado","esgrima","esmalte","espanto","espelho","espiga","esponja","espreita","espumar","esquerda","estaca","esteira","esticar","estofado","estrela","estudo","esvaziar","etanol","etiqueta","euforia","europeu","evacuar","evaporar","evasivo","eventual","evidente","evoluir","exagero","exalar","examinar","exato","exausto","excesso","excitar","exclamar","executar","exemplo","exibir","exigente","exonerar","expandir","expelir","expirar","explanar","exposto","expresso","expulsar","externo","extinto","extrato","fabricar","fabuloso","faceta","facial","fada","fadiga","faixa","falar","falta","familiar","fandango","fanfarra","fantoche","fardado","farelo","farinha","farofa","farpa","fartura","fatia","fator","favorita","faxina","fazenda","fechado","feijoada","feirante","felino","feminino","fenda","feno","fera","feriado","ferrugem","ferver","festejar","fetal","feudal","fiapo","fibrose","ficar","ficheiro","figurado","fileira","filho","filme","filtrar","firmeza","fisgada","fissura","fita","fivela","fixador","fixo","flacidez","flamingo","flanela","flechada","flora","flutuar","fluxo","focal","focinho","fofocar","fogo","foguete","foice","folgado","folheto","forjar","formiga","forno","forte","fosco","fossa","fragata","fralda","frango","frasco","fraterno","freira","frente","fretar","frieza","friso","fritura","fronha","frustrar","fruteira","fugir","fulano","fuligem","fundar","fungo","funil","furador","furioso","futebol","gabarito","gabinete","gado","gaiato","gaiola","gaivota","galega","galho","galinha","galocha","ganhar","garagem","garfo","gargalo","garimpo","garoupa","garrafa","gasoduto","gasto","gata","gatilho","gaveta","gazela","gelado","geleia","gelo","gemada","gemer","gemido","generoso","gengiva","genial","genoma","genro","geologia","gerador","germinar","gesso","gestor","ginasta","gincana","gingado","girafa","girino","glacial","glicose","global","glorioso","goela","goiaba","golfe","golpear","gordura","gorjeta","gorro","gostoso","goteira","governar","gracejo","gradual","grafite","gralha","grampo","granada","gratuito","graveto","graxa","grego","grelhar","greve","grilo","grisalho","gritaria","grosso","grotesco","grudado","grunhido","gruta","guache","guarani","guaxinim","guerrear","guiar","guincho","guisado","gula","guloso","guru","habitar","harmonia","haste","haver","hectare","herdar","heresia","hesitar","hiato","hibernar","hidratar","hiena","hino","hipismo","hipnose","hipoteca","hoje","holofote","homem","honesto","honrado","hormonal","hospedar","humorado","iate","ideia","idoso","ignorado","igreja","iguana","ileso","ilha","iludido","iluminar","ilustrar","imagem","imediato","imenso","imersivo","iminente","imitador","imortal","impacto","impedir","implante","impor","imprensa","impune","imunizar","inalador","inapto","inativo","incenso","inchar","incidir","incluir","incolor","indeciso","indireto","indutor","ineficaz","inerente","infantil","infestar","infinito","inflamar","informal","infrator","ingerir","inibido","inicial","inimigo","injetar","inocente","inodoro","inovador","inox","inquieto","inscrito","inseto","insistir","inspetor","instalar","insulto","intacto","integral","intimar","intocado","intriga","invasor","inverno","invicto","invocar","iogurte","iraniano","ironizar","irreal","irritado","isca","isento","isolado","isqueiro","italiano","janeiro","jangada","janta","jararaca","jardim","jarro","jasmim","jato","javali","jazida","jejum","joaninha","joelhada","jogador","joia","jornal","jorrar","jovem","juba","judeu","judoca","juiz","julgador","julho","jurado","jurista","juro","justa","labareda","laboral","lacre","lactante","ladrilho","lagarta","lagoa","laje","lamber","lamentar","laminar","lampejo","lanche","lapidar","lapso","laranja","lareira","largura","lasanha","lastro","lateral","latido","lavanda","lavoura","lavrador","laxante","lazer","lealdade","lebre","legado","legendar","legista","leigo","leiloar","leitura","lembrete","leme","lenhador","lentilha","leoa","lesma","leste","letivo","letreiro","levar","leveza","levitar","liberal","libido","liderar","ligar","ligeiro","limitar","limoeiro","limpador","linda","linear","linhagem","liquidez","listagem","lisura","litoral","livro","lixa","lixeira","locador","locutor","lojista","lombo","lona","longe","lontra","lorde","lotado","loteria","loucura","lousa","louvar","luar","lucidez","lucro","luneta","lustre","lutador","luva","macaco","macete","machado","macio","madeira","madrinha","magnata","magreza","maior","mais","malandro","malha","malote","maluco","mamilo","mamoeiro","mamute","manada","mancha","mandato","manequim","manhoso","manivela","manobrar","mansa","manter","manusear","mapeado","maquinar","marcador","maresia","marfim","margem","marinho","marmita","maroto","marquise","marreco","martelo","marujo","mascote","masmorra","massagem","mastigar","matagal","materno","matinal","matutar","maxilar","medalha","medida","medusa","megafone","meiga","melancia","melhor","membro","memorial","menino","menos","mensagem","mental","merecer","mergulho","mesada","mesclar","mesmo","mesquita","mestre","metade","meteoro","metragem","mexer","mexicano","micro","migalha","migrar","milagre","milenar","milhar","mimado","minerar","minhoca","ministro","minoria","miolo","mirante","mirtilo","misturar","mocidade","moderno","modular","moeda","moer","moinho","moita","moldura","moleza","molho","molinete","molusco","montanha","moqueca","morango","morcego","mordomo","morena","mosaico","mosquete","mostarda","motel","motim","moto","motriz","muda","muito","mulata","mulher","multar","mundial","munido","muralha","murcho","muscular","museu","musical","nacional","nadador","naja","namoro","narina","narrado","nascer","nativa","natureza","navalha","navegar","navio","neblina","nebuloso","negativa","negociar","negrito","nervoso","neta","neural","nevasca","nevoeiro","ninar","ninho","nitidez","nivelar","nobreza","noite","noiva","nomear","nominal","nordeste","nortear","notar","noticiar","noturno","novelo","novilho","novo","nublado","nudez","numeral","nupcial","nutrir","nuvem","obcecado","obedecer","objetivo","obrigado","obscuro","obstetra","obter","obturar","ocidente","ocioso","ocorrer","oculista","ocupado","ofegante","ofensiva","oferenda","oficina","ofuscado","ogiva","olaria","oleoso","olhar","oliveira","ombro","omelete","omisso","omitir","ondulado","oneroso","ontem","opcional","operador","oponente","oportuno","oposto","orar","orbitar","ordem","ordinal","orfanato","orgasmo","orgulho","oriental","origem","oriundo","orla","ortodoxo","orvalho","oscilar","ossada","osso","ostentar","otimismo","ousadia","outono","outubro","ouvido","ovelha","ovular","oxidar","oxigenar","pacato","paciente","pacote","pactuar","padaria","padrinho","pagar","pagode","painel","pairar","paisagem","palavra","palestra","palheta","palito","palmada","palpitar","pancada","panela","panfleto","panqueca","pantanal","papagaio","papelada","papiro","parafina","parcial","pardal","parede","partida","pasmo","passado","pastel","patamar","patente","patinar","patrono","paulada","pausar","peculiar","pedalar","pedestre","pediatra","pedra","pegada","peitoral","peixe","pele","pelicano","penca","pendurar","peneira","penhasco","pensador","pente","perceber","perfeito","pergunta","perito","permitir","perna","perplexo","persiana","pertence","peruca","pescado","pesquisa","pessoa","petiscar","piada","picado","piedade","pigmento","pilastra","pilhado","pilotar","pimenta","pincel","pinguim","pinha","pinote","pintar","pioneiro","pipoca","piquete","piranha","pires","pirueta","piscar","pistola","pitanga","pivete","planta","plaqueta","platina","plebeu","plumagem","pluvial","pneu","poda","poeira","poetisa","polegada","policiar","poluente","polvilho","pomar","pomba","ponderar","pontaria","populoso","porta","possuir","postal","pote","poupar","pouso","povoar","praia","prancha","prato","praxe","prece","predador","prefeito","premiar","prensar","preparar","presilha","pretexto","prevenir","prezar","primata","princesa","prisma","privado","processo","produto","profeta","proibido","projeto","prometer","propagar","prosa","protetor","provador","publicar","pudim","pular","pulmonar","pulseira","punhal","punir","pupilo","pureza","puxador","quadra","quantia","quarto","quase","quebrar","queda","queijo","quente","querido","quimono","quina","quiosque","rabanada","rabisco","rachar","racionar","radial","raiar","rainha","raio","raiva","rajada","ralado","ramal","ranger","ranhura","rapadura","rapel","rapidez","raposa","raquete","raridade","rasante","rascunho","rasgar","raspador","rasteira","rasurar","ratazana","ratoeira","realeza","reanimar","reaver","rebaixar","rebelde","rebolar","recado","recente","recheio","recibo","recordar","recrutar","recuar","rede","redimir","redonda","reduzida","reenvio","refinar","refletir","refogar","refresco","refugiar","regalia","regime","regra","reinado","reitor","rejeitar","relativo","remador","remendo","remorso","renovado","reparo","repelir","repleto","repolho","represa","repudiar","requerer","resenha","resfriar","resgatar","residir","resolver","respeito","ressaca","restante","resumir","retalho","reter","retirar","retomada","retratar","revelar","revisor","revolta","riacho","rica","rigidez","rigoroso","rimar","ringue","risada","risco","risonho","robalo","rochedo","rodada","rodeio","rodovia","roedor","roleta","romano","roncar","rosado","roseira","rosto","rota","roteiro","rotina","rotular","rouco","roupa","roxo","rubro","rugido","rugoso","ruivo","rumo","rupestre","russo","sabor","saciar","sacola","sacudir","sadio","safira","saga","sagrada","saibro","salada","saleiro","salgado","saliva","salpicar","salsicha","saltar","salvador","sambar","samurai","sanar","sanfona","sangue","sanidade","sapato","sarda","sargento","sarjeta","saturar","saudade","saxofone","sazonal","secar","secular","seda","sedento","sediado","sedoso","sedutor","segmento","segredo","segundo","seiva","seleto","selvagem","semanal","semente","senador","senhor","sensual","sentado","separado","sereia","seringa","serra","servo","setembro","setor","sigilo","silhueta","silicone","simetria","simpatia","simular","sinal","sincero","singular","sinopse","sintonia","sirene","siri","situado","soberano","sobra","socorro","sogro","soja","solda","soletrar","solteiro","sombrio","sonata","sondar","sonegar","sonhador","sono","soprano","soquete","sorrir","sorteio","sossego","sotaque","soterrar","sovado","sozinho","suavizar","subida","submerso","subsolo","subtrair","sucata","sucesso","suco","sudeste","sufixo","sugador","sugerir","sujeito","sulfato","sumir","suor","superior","suplicar","suposto","suprimir","surdina","surfista","surpresa","surreal","surtir","suspiro","sustento","tabela","tablete","tabuada","tacho","tagarela","talher","talo","talvez","tamanho","tamborim","tampa","tangente","tanto","tapar","tapioca","tardio","tarefa","tarja","tarraxa","tatuagem","taurino","taxativo","taxista","teatral","tecer","tecido","teclado","tedioso","teia","teimar","telefone","telhado","tempero","tenente","tensor","tentar","termal","terno","terreno","tese","tesoura","testado","teto","textura","texugo","tiara","tigela","tijolo","timbrar","timidez","tingido","tinteiro","tiragem","titular","toalha","tocha","tolerar","tolice","tomada","tomilho","tonel","tontura","topete","tora","torcido","torneio","torque","torrada","torto","tostar","touca","toupeira","toxina","trabalho","tracejar","tradutor","trafegar","trajeto","trama","trancar","trapo","traseiro","tratador","travar","treino","tremer","trepidar","trevo","triagem","tribo","triciclo","tridente","trilogia","trindade","triplo","triturar","triunfal","trocar","trombeta","trova","trunfo","truque","tubular","tucano","tudo","tulipa","tupi","turbo","turma","turquesa","tutelar","tutorial","uivar","umbigo","unha","unidade","uniforme","urologia","urso","urtiga","urubu","usado","usina","usufruir","vacina","vadiar","vagaroso","vaidoso","vala","valente","validade","valores","vantagem","vaqueiro","varanda","vareta","varrer","vascular","vasilha","vassoura","vazar","vazio","veado","vedar","vegetar","veicular","veleiro","velhice","veludo","vencedor","vendaval","venerar","ventre","verbal","verdade","vereador","vergonha","vermelho","verniz","versar","vertente","vespa","vestido","vetorial","viaduto","viagem","viajar","viatura","vibrador","videira","vidraria","viela","viga","vigente","vigiar","vigorar","vilarejo","vinco","vinheta","vinil","violeta","virada","virtude","visitar","visto","vitral","viveiro","vizinho","voador","voar","vogal","volante","voleibol","voltagem","volumoso","vontade","vulto","vuvuzela","xadrez","xarope","xeque","xeretar","xerife","xingar","zangado","zarpar","zebu","zelador","zombar","zoologia","zumbido"]},{}]},{},[50])(50);var N=void 0!==N?N:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},P=[],D=[],z="undefined"!=typeof Uint8Array?Uint8Array:Array,q=!1;function W(){q=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t>18&63]+P[i>>12&63]+P[i>>6&63]+P[63&i]);return o.join("")}function K(e){var t;q||W();for(var r=e.length,n=r%3,i="",o=[],a=16383,s=0,u=r-n;su?u:s+a));return 1===n?(t=e[r-1],i+=P[t>>2],i+=P[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=P[t>>10],i+=P[t>>4&63],i+=P[t<<2&63],i+="="),o.push(i),o.join("")}function Y(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,c=r?-1:1,d=e[t+f];for(f+=c,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=c,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=c,l-=8);if(0===o)o=1-h;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=h}return(d?-1:1)*a*Math.pow(2,o-n)}function H(e,t,r,n,i,o){var a,s,u,h=8*o-i-1,l=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?c/u:c*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,h-=8);e[r+d-p]|=128*g}var $={}.toString,V=Array.isArray||function(e){return"[object Array]"==$.call(e)};function G(){return X.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function J(e,t){if(G()=G())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G().toString(16)+" bytes");return 0|e}function ne(e){return!(null==e||!e._isBuffer)}function ie(e,t){if(ne(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Oe(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Me(e).length;default:if(n)return Oe(e).length;t=(""+t).toLowerCase(),n=!0}}function oe(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return ve(this,t,r);case"utf8":case"utf-8":return ye(this,t,r);case"ascii":return be(this,t,r);case"latin1":case"binary":return me(this,t,r);case"base64":return ge(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return we(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function ae(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function se(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=X.from(t,n)),ne(t))return 0===t.length?-1:ue(e,t,r,n,i);if("number"==typeof t)return t&=255,X.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):ue(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function ue(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function h(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var l=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var f=!0,c=0;ci&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function ge(e,t,r){return 0===t&&r===e.length?K(e):K(e.slice(t,r))}function ye(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:h>223?3:h>191?2:1;if(i+f<=r)switch(f){case 1:h<128&&(l=h);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&h)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&h)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&h)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,f=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=f}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},X.prototype.compare=function(e,t,r,n,i){if(!ne(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(o,a),u=this.slice(n,i),h=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return he(this,e,t,r);case"utf8":case"utf-8":return le(this,e,t,r);case"ascii":return fe(this,e,t,r);case"latin1":case"binary":return ce(this,e,t,r);case"base64":return de(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pe(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},X.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function be(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function Ee(e,t,r,n,i,o){if(!ne(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function Se(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function ke(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function xe(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Re(e,t,r,n,i){return i||xe(e,0,r,4),H(e,t,r,n,23,4),r+4}function Ae(e,t,r,n,i){return i||xe(e,0,r,8),H(e,t,r,n,52,8),r+8}X.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},X.prototype.readUInt8=function(e,t){return t||_e(e,1,this.length),this[e]},X.prototype.readUInt16LE=function(e,t){return t||_e(e,2,this.length),this[e]|this[e+1]<<8},X.prototype.readUInt16BE=function(e,t){return t||_e(e,2,this.length),this[e]<<8|this[e+1]},X.prototype.readUInt32LE=function(e,t){return t||_e(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},X.prototype.readUInt32BE=function(e,t){return t||_e(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},X.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||_e(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},X.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||_e(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},X.prototype.readInt8=function(e,t){return t||_e(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},X.prototype.readInt16LE=function(e,t){t||_e(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},X.prototype.readInt16BE=function(e,t){t||_e(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},X.prototype.readInt32LE=function(e,t){return t||_e(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},X.prototype.readInt32BE=function(e,t){return t||_e(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},X.prototype.readFloatLE=function(e,t){return t||_e(e,4,this.length),Y(this,e,!0,23,4)},X.prototype.readFloatBE=function(e,t){return t||_e(e,4,this.length),Y(this,e,!1,23,4)},X.prototype.readDoubleLE=function(e,t){return t||_e(e,8,this.length),Y(this,e,!0,52,8)},X.prototype.readDoubleBE=function(e,t){return t||_e(e,8,this.length),Y(this,e,!1,52,8)},X.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||Ee(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},X.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,1,255,0),X.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},X.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,2,65535,0),X.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Se(this,e,t,!0),t+2},X.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,2,65535,0),X.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Se(this,e,t,!1),t+2},X.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,4,4294967295,0),X.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):ke(this,e,t,!0),t+4},X.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,4,4294967295,0),X.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):ke(this,e,t,!1),t+4},X.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Ee(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},X.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Ee(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},X.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,1,127,-128),X.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},X.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,2,32767,-32768),X.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Se(this,e,t,!0),t+2},X.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,2,32767,-32768),X.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Se(this,e,t,!1),t+2},X.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,4,2147483647,-2147483648),X.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):ke(this,e,t,!0),t+4},X.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Ee(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),X.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):ke(this,e,t,!1),t+4},X.prototype.writeFloatLE=function(e,t,r){return Re(this,e,t,!0,r)},X.prototype.writeFloatBE=function(e,t,r){return Re(this,e,t,!1,r)},X.prototype.writeDoubleLE=function(e,t,r){return Ae(this,e,t,!0,r)},X.prototype.writeDoubleBE=function(e,t,r){return Ae(this,e,t,!1,r)},X.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!X.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Me(e){return function(e){var t,r,n,i,o,a;q||W();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new z(3*s/4-o),n=o>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=D[e.charCodeAt(t)]<<2|D[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=D[e.charCodeAt(t)]<<10|D[e.charCodeAt(t+1)]<<4|D[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Te,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Le(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function je(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Ue={},Ie={exports:{}};"function"==typeof Object.create?Ie.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:Ie.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e};for(var Ce={exports:{}},Ne={},Pe={byteLength:function(e){var t=Ye(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=Ye(e),i=n[0],o=n[1],a=new qe(function(e,t,r){return 3*(t+r)/4-r}(0,i,o)),s=0,u=o>0?i-4:i;for(r=0;r>16&255,a[s++]=t>>8&255,a[s++]=255&t;2===o&&(t=ze[e.charCodeAt(r)]<<2|ze[e.charCodeAt(r+1)]>>4,a[s++]=255&t);1===o&&(t=ze[e.charCodeAt(r)]<<10|ze[e.charCodeAt(r+1)]<<4|ze[e.charCodeAt(r+2)]>>2,a[s++]=t>>8&255,a[s++]=255&t);return a},fromByteArray:function(e){for(var t,r=e.length,n=r%3,i=[],o=16383,a=0,s=r-n;as?s:a+o));1===n?(t=e[r-1],i.push(De[t>>2]+De[t<<4&63]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],i.push(De[t>>10]+De[t>>4&63]+De[t<<2&63]+"="));return i.join("")}},De=[],ze=[],qe="undefined"!=typeof Uint8Array?Uint8Array:Array,We="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Fe=0,Ke=We.length;Fe0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function He(e,t,r){for(var n,i,o=[],a=t;a>18&63]+De[i>>12&63]+De[i>>6&63]+De[63&i]);return o.join("")}ze["-".charCodeAt(0)]=62,ze["_".charCodeAt(0)]=63;var $e={}; +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */function Ve(){}function Ge(){Ge.init.call(this)}function Je(e){return void 0===e._maxListeners?Ge.defaultMaxListeners:e._maxListeners}function Xe(e,t,r){if(t)e.call(r);else for(var n=e.length,i=ot(e,n),o=0;o0&&a.length>i){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else a=o[t]=r,++e._eventsCount;return e}function nt(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function it(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function ot(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}$e.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,f=r?i-1:0,c=r?-1:1,d=e[t+f];for(f+=c,o=d&(1<<-l)-1,d>>=-l,l+=s;l>0;o=256*o+e[t+f],f+=c,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+f],f+=c,l-=8);if(0===o)o=1-h;else{if(o===u)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),o-=h}return(d?-1:1)*a*Math.pow(2,o-n)},$e.write=function(e,t,r,n,i,o){var a,s,u,h=8*o-i-1,l=(1<>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?c/u:c*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=l?(s=0,a=l):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+d]=255&s,d+=p,s/=256,i-=8);for(a=a<0;e[r+d]=255&a,d+=p,a/=256,h-=8);e[r+d-p]|=128*g}, +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function(e){const t=Pe,r=$e,n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=function(e){+e!=e&&(e=0);return a.alloc(+e)},e.INSPECT_MAX_BYTES=50;const i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,a.prototype),t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return h(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!a.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|d(e,t);let n=o(r);const i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return function(e){if($(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return l(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if($(e,ArrayBuffer)||e&&$(e.buffer,ArrayBuffer))return f(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&($(e,SharedArrayBuffer)||e&&$(e.buffer,SharedArrayBuffer)))return f(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return a.from(n,t,r);const i=function(e){if(a.isBuffer(e)){const t=0|c(e.length),r=o(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||V(e.length)?o(0):l(e);if("Buffer"===e.type&&Array.isArray(e.data))return l(e.data)}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return a.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function h(e){return u(e),o(e<0?0:0|c(e))}function l(e){const t=e.length<0?0:0|c(e.length),r=o(t);for(let n=0;n=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function d(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||$(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return K(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(e).length;default:if(i)return n?-1:K(e).length;t=(""+t).toLowerCase(),i=!0}}function p(e,t,r){let n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return k(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return A(this,t,r);case"base64":return S(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),V(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:b(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):b(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,r,n,i){let o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function h(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){let n=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){let r=!0;for(let n=0;ni&&(n=i):n=i;const o=t.length;let a;for(n>o/2&&(n=o/2),a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function S(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function k(e,t,r){r=Math.min(e.length,r);const n=[];let i=t;for(;i239?4:t>223?3:t>191?2:1;if(i+a<=r){let r,n,s,u;switch(a){case 1:t<128&&(o=t);break;case 2:r=e[i+1],128==(192&r)&&(u=(31&t)<<6|63&r,u>127&&(o=u));break;case 3:r=e[i+1],n=e[i+2],128==(192&r)&&128==(192&n)&&(u=(15&t)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:r=e[i+1],n=e[i+2],s=e[i+3],128==(192&r)&&128==(192&n)&&128==(192&s)&&(u=(15&t)<<18|(63&r)<<12|(63&n)<<6|63&s,u>65535&&u<1114112&&(o=u))}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=a}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",n=0;for(;nn.length?(a.isBuffer(t)||(t=a.from(t)),t.copy(n,i)):Uint8Array.prototype.set.call(n,t,i);else{if(!a.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(n,i)}i+=t.length}return n},a.byteLength=d,a.prototype._isBuffer=!0,a.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;tr&&(t+=" ... "),""},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(e,t,r,n,i){if($(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;let o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0);const u=Math.min(o,s),h=this.slice(n,i),l=e.slice(t,r);for(let e=0;e>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return v(this,e,t,r);case"ascii":case"latin1":case"binary":return w(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function R(e,t,r){let n="";r=Math.min(e.length,r);for(let i=t;in)&&(r=n);let i="";for(let n=t;nr)throw new RangeError("Trying to access beyond buffer length")}function M(e,t,r,n,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function L(e,t,r,n,i){z(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,a>>=8,e[r++]=a,r}function j(e,t,r,n,i){z(t,n,i,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let a=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=a,a>>=8,e[r+2]=a,a>>=8,e[r+1]=a,a>>=8,e[r]=a,r+8}function U(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function I(e,t,n,i,o){return t=+t,n>>>=0,o||U(e,0,n,4),r.write(e,t,n,i,23,4),n+4}function C(e,t,n,i,o){return t=+t,n>>>=0,o||U(e,0,n,8),r.write(e,t,n,i,52,8),n+8}a.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e+--t],i=1;for(;t>0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUint8=a.prototype.readUInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),this[e]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||O(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readBigUInt64LE=J((function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const n=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(n)+(BigInt(i)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const n=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(n)<>>=0,t>>>=0,r||O(e,t,this.length);let n=this[e],i=1,o=0;for(;++o=i&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||O(e,t,this.length);let n=t,i=1,o=this[e+--n];for(;n>0&&(i*=256);)o+=this[e+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return e>>>=0,t||O(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){e>>>=0,t||O(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||O(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readBigInt64LE=J((function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const n=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(n)<>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const n=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(n)<>>=0,t||O(e,4,this.length),r.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||O(e,4,this.length),r.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||O(e,8,this.length),r.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||O(e,8,this.length),r.read(this,e,!1,52,8)},a.prototype.writeUintLE=a.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t>>>=0,r>>>=0,!n){M(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,!n){M(this,e,t,r,Math.pow(2,8*r)-1,0)}let i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},a.prototype.writeUint8=a.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeBigUInt64LE=J((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),a.prototype.writeBigUInt64BE=J((function(e,t=0){return j(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);M(this,e,t,r,n-1,-n)}let i=0,o=1,a=0;for(this[t]=255&e;++i>0)-a&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){const n=Math.pow(2,8*r-1);M(this,e,t,r,n-1,-n)}let i=r-1,o=1,a=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===a&&0!==this[t+i+1]&&(a=1),this[t+i]=(e/o>>0)-a&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||M(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeBigInt64LE=J((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),a.prototype.writeBigInt64BE=J((function(e,t=0){return j(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),a.prototype.writeFloatLE=function(e,t,r){return I(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return I(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return C(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return C(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(!a.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function z(e,t,r,n,i,o){if(e>r||e3?0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(o+1)}${n}`:`>= -(2${n} ** ${8*(o+1)-1}${n}) and < 2 ** ${8*(o+1)-1}${n}`:`>= ${t}${n} and <= ${r}${n}`,new N.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||W(t,e.length-(r+1))}(n,i,o)}function q(e,t){if("number"!=typeof e)throw new N.ERR_INVALID_ARG_TYPE(t,"number",e)}function W(e,t,r){if(Math.floor(e)!==e)throw q(e,r),new N.ERR_OUT_OF_RANGE(r||"offset","an integer",e);if(t<0)throw new N.ERR_BUFFER_OUT_OF_BOUNDS;throw new N.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${t}`,e)}P("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),P("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),P("ERR_OUT_OF_RANGE",(function(e,t,r){let n=`The value of "${e}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${t}. Received ${i}`,n}),RangeError);const F=/[^+/0-9A-Za-z-_]/g;function K(e,t){let r;t=t||1/0;const n=e.length;let i=null;const o=[];for(let a=0;a55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Y(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function H(e,t,r,n){let i;for(i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function $(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function V(e){return e!=e}const G=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)t[n+i]=e[r]+e[i]}return t}();function J(e){return"undefined"==typeof BigInt?X:e}function X(){throw new Error("BigInt not supported")}}(Ne),function(e,t){var r=Ne,n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(Ce,Ce.exports),Ve.prototype=Object.create(null),Ge.EventEmitter=Ge,Ge.usingDomains=!1,Ge.prototype.domain=void 0,Ge.prototype._events=void 0,Ge.prototype._maxListeners=void 0,Ge.defaultMaxListeners=10,Ge.init=function(){this.domain=null,Ge.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Ve,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ge.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Ge.prototype.getMaxListeners=function(){return Je(this)},Ge.prototype.emit=function(e){var t,r,n,i,o,a,s,u="error"===e;if(a=this._events)u=u&&null==a.error;else if(!u)return!1;if(s=this.domain,u){if(t=arguments[1],!s){if(t instanceof Error)throw t;var h=new Error('Uncaught, unspecified "error" event. ('+t+")");throw h.context=t,h}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=s,t.domainThrown=!1,s.emit("error",t),!1}if(!(r=a[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:Xe(r,l,this);break;case 2:Ze(r,l,this,arguments[1]);break;case 3:Qe(r,l,this,arguments[1],arguments[2]);break;case 4:et(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===t||r[o].listener&&r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Ve,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]};var at=Object.freeze({__proto__:null,default:Ge,EventEmitter:Ge});function st(){throw new Error("setTimeout has not been defined")}function ut(){throw new Error("clearTimeout has not been defined")}var ht=st,lt=ut;function ft(e){if(ht===setTimeout)return setTimeout(e,0);if((ht===st||!ht)&&setTimeout)return ht=setTimeout,setTimeout(e,0);try{return ht(e,0)}catch(t){try{return ht.call(null,e,0)}catch(t){return ht.call(this,e,0)}}}"function"==typeof N.setTimeout&&(ht=setTimeout),"function"==typeof N.clearTimeout&&(lt=clearTimeout);var ct,dt=[],pt=!1,gt=-1;function yt(){pt&&ct&&(pt=!1,ct.length?dt=ct.concat(dt):gt=-1,dt.length&&bt())}function bt(){if(!pt){var e=ft(yt);pt=!0;for(var t=dt.length;t;){for(ct=dt,dt=[];++gt1)for(var r=1;r=a)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(e){return"[Circular]"}default:return e}})),u=i[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),c(r)?n.showHidden=r:r&&t._extend(n,r),y(n.showHidden)&&(n.showHidden=!1),y(n.depth)&&(n.depth=2),y(n.colors)&&(n.colors=!1),y(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=a),u(n,e,n.depth)}function a(e,t){var r=o.styles[t];return r?"["+o.colors[r][0]+"m"+e+"["+o.colors[r][1]+"m":e}function s(e,t){return e}function u(e,r,n){if(e.customInspect&&r&&_(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,e);return g(i)||(i=u(e,i,n)),i}var o=function(e,t){if(y(t))return e.stylize("undefined","undefined");if(g(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(p(t))return e.stylize(""+t,"number");if(c(t))return e.stylize(""+t,"boolean");if(d(t))return e.stylize("null","null")}(e,r);if(o)return o;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),w(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return h(r);if(0===a.length){if(_(r)){var m=r.name?": "+r.name:"";return e.stylize("[Function"+m+"]","special")}if(b(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(v(r))return e.stylize(Date.prototype.toString.call(r),"date");if(w(r))return h(r)}var E,S="",k=!1,x=["{","}"];(f(r)&&(k=!0,x=["[","]"]),_(r))&&(S=" [Function"+(r.name?": "+r.name:"")+"]");return b(r)&&(S=" "+RegExp.prototype.toString.call(r)),v(r)&&(S=" "+Date.prototype.toUTCString.call(r)),w(r)&&(S=" "+h(r)),0!==a.length||k&&0!=r.length?n<0?b(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),E=k?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(E,S,x)):x[0]+S+x[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,o){var a,s,h;if((h=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=h.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):h.set&&(s=e.stylize("[Setter]","special")),R(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(h.value)<0?(s=d(r)?u(e,h.value,null):u(e,h.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),y(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function f(e){return Array.isArray(e)}function c(e){return"boolean"==typeof e}function d(e){return null===e}function p(e){return"number"==typeof e}function g(e){return"string"==typeof e}function y(e){return void 0===e}function b(e){return m(e)&&"[object RegExp]"===E(e)}function m(e){return"object"==typeof e&&null!==e}function v(e){return m(e)&&"[object Date]"===E(e)}function w(e){return m(e)&&("[object Error]"===E(e)||e instanceof Error)}function _(e){return"function"==typeof e}function E(e){return Object.prototype.toString.call(e)}function S(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(y(n)&&(n=Mt.env.NODE_DEBUG||""),e=e.toUpperCase(),!i[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=Mt.pid;i[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else i[e]=function(){};return i[e]},t.inspect=o,o.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=f,t.isBoolean=c,t.isNull=d,t.isNullOrUndefined=function(e){return null==e},t.isNumber=p,t.isString=g,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=y,t.isRegExp=b,t.isObject=m,t.isDate=v,t.isError=w,t.isFunction=_,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=jt;var k=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function x(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),k[e.getMonth()],t].join(" ")}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){console.log("%s - %s",x(),t.format.apply(t,arguments))},t.inherits=Ie.exports,t._extend=function(e,t){if(!t||!m(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}(Lt),Ut.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},Ut.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},Ut.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},Ut.prototype.clear=function(){this.head=this.tail=null,this.length=0},Ut.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},Ut.prototype.concat=function(e){if(0===this.length)return Ne.Buffer.alloc(0);if(1===this.length)return this.head.data;for(var t=Ne.Buffer.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var It={},Ct=Ce.exports.Buffer,Nt=Ct.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};var Pt=It.StringDecoder=Dt;function Dt(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(Ct.isEncoding===Nt||!Nt(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=Wt,this.end=Ft,t=4;break;case"utf8":this.fillLast=qt,t=4;break;case"base64":this.text=Kt,this.end=Yt,t=3;break;default:return this.write=Ht,void(this.end=$t)}this.lastNeed=0,this.lastTotal=0,this.lastChar=Ct.allocUnsafe(t)}function zt(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function qt(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function Wt(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function Ft(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function Kt(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function Yt(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function Ht(e){return e.toString(this.encoding)}function $t(e){return e&&e.length?this.write(e):""}Dt.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},Dt.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length},Jt.ReadableState=Gt;var Vt=Lt.debuglog("stream");function Gt(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof Sr&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new Ut,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new Pt(e.encoding),this.encoding=e.encoding)}function Jt(e){if(!(this instanceof Jt))return new Jt(e);this._readableState=new Gt(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Ge.call(this)}function Xt(e,t,r,n,i){var o=function(e,t){var r=null;X.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(o)e.emit("error",o);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,Qt(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||n||(r=t.decoder.write(r),u=!t.objectMode&&0===r.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Qt(e))),function(e,t){t.readingMore||(t.readingMore=!0,mt(tr,e,t))}(e,t)}else i||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function Qt(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Vt("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?mt(er,e):er(e))}function er(e){Vt("emit readable"),e.emit("readable"),ir(e)}function tr(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=X.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function ar(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,mt(sr,t,e))}function sr(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function ur(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return Vt("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ar(this):Qt(this),null;if(0===(e=Zt(e,t))&&t.ended)return 0===t.length&&ar(this),null;var n,i=t.needReadable;return Vt("need readable",i),(0===t.length||t.length-e0?or(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ar(this)),null!==n&&this.emit("data",n),n},Jt.prototype._read=function(e){this.emit("error",new Error("not implemented"))},Jt.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,Vt("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?a:h;function o(e){Vt("onunpipe"),e===r&&h()}function a(){Vt("onend"),e.end()}n.endEmitted?mt(i):r.once("end",i),e.on("unpipe",o);var s=function(e){return function(){var t=e._readableState;Vt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,ir(e))}}(r);e.on("drain",s);var u=!1;function h(){Vt("cleanup"),e.removeListener("close",d),e.removeListener("finish",p),e.removeListener("drain",s),e.removeListener("error",c),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",h),r.removeListener("data",f),u=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||s()}var l=!1;function f(t){Vt("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==ur(n.pipes,e))&&!u&&(Vt("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function c(t){var r;Vt("onerror",t),g(),e.removeListener("error",c),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function d(){e.removeListener("finish",p),g()}function p(){Vt("onfinish"),e.removeListener("close",d),g()}function g(){Vt("unpipe"),r.unpipe(e)}return r.on("data",f),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",c),e.once("close",d),e.once("finish",p),e.emit("pipe",r),n.flowing||(Vt("pipe resume"),r.resume()),e},Jt.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},cr.prototype._write=function(e,t,r){r(new Error("not implemented"))},cr.prototype._writev=null,cr.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,mr(e,t),r&&(t.finished?mt(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Lt.inherits(Sr,Jt);for(var wr=Object.keys(cr.prototype),_r=0;_r64?t=e(t):t.length<64&&(t=Pr.concat([t,zr],64));for(var r=this._ipad=Pr.allocUnsafe(64),n=this._opad=Pr.allocUnsafe(64),i=0;i<64;i++)r[i]=54^t[i],n[i]=92^t[i];this._hash=[r]}Nr(qr,Dr),qr.prototype._update=function(e){this._hash.push(e)},qr.prototype._final=function(){var e=this._alg(Pr.concat(this._hash));return this._alg(Pr.concat([this._opad,e]))};var Wr=qr,Fr={exports:{}}; +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +!function(e,t){var r=Ne,n=r.Buffer;function i(e,t){for(var r in e)t[r]=e[r]}function o(e,t,r){return n(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return n(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var i=n(e);return void 0!==t?"string"==typeof r?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}}(Fr,Fr.exports);var Kr={exports:{}},Yr=r(at),Hr=Yr.EventEmitter;function $r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function Vr(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Gr(e,t){for(var r=0;r0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return Jr.alloc(0);for(var t,r,n,i=Jr.allocUnsafe(e>>>0),o=this.head,a=0;o;)t=o.data,r=i,n=a,Jr.prototype.copy.call(t,r,n),a+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var r;return ei.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0==(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=Jr.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0==(e-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,t}},{key:Zr,value:function(e,t){return Xr(this,function(e){for(var t=1;t2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}sn("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),sn("ERR_INVALID_ARG_TYPE",(function(e,t,r){var n,i,o,a;if("string"==typeof t&&(i="not ",t.substr(!o||o<0?0:+o,i.length)===i)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))a="The ".concat(e," ").concat(n," ").concat(un(t,"type"));else{var s=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";a='The "'.concat(e,'" ').concat(s," ").concat(n," ").concat(un(t,"type"))}return a+=". Received type ".concat(typeof r)}),TypeError),sn("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),sn("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),sn("ERR_STREAM_PREMATURE_CLOSE","Premature close"),sn("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),sn("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),sn("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),sn("ERR_STREAM_WRITE_AFTER_END","write after end"),sn("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),sn("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),sn("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),on.codes=an;var hn=on.codes.ERR_INVALID_OPT_VALUE;var ln={getHighWaterMark:function(e,t,r,n){var i=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,n,r);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new hn(n?r:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}},fn={exports:{}};"function"==typeof Object.create?fn.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:fn.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}};var cn=function(e,t){if(dn("noDeprecation"))return e;var r=!1;return function(){if(!r){if(dn("throwDeprecation"))throw new Error(t);dn("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}};function dn(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}var pn,gn=Cn;function yn(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,r){var n=e.entry;e.entry=null;for(;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next}t.corkedRequestsFree.next=e}(t,e)}}Cn.WritableState=In;var bn={deprecate:cn},mn=Hr,vn=Ne.Buffer,wn=e.Uint8Array||function(){};var _n,En=nn,Sn=ln.getHighWaterMark,kn=on.codes,xn=kn.ERR_INVALID_ARG_TYPE,Rn=kn.ERR_METHOD_NOT_IMPLEMENTED,An=kn.ERR_MULTIPLE_CALLBACK,Tn=kn.ERR_STREAM_CANNOT_PIPE,Bn=kn.ERR_STREAM_DESTROYED,On=kn.ERR_STREAM_NULL_VALUES,Mn=kn.ERR_STREAM_WRITE_AFTER_END,Ln=kn.ERR_UNKNOWN_ENCODING,jn=En.errorOrDestroy;function Un(){}function In(e,t,r){pn=pn||Kn,e=e||{},"boolean"!=typeof r&&(r=t instanceof pn),this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=Sn(this,e,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var n=!1===e.decodeStrings;this.decodeStrings=!n,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if("function"!=typeof i)throw new An;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(Mt.nextTick(i,n),Mt.nextTick(Wn,e,t),e._writableState.errorEmitted=!0,jn(e,n)):(i(n),e._writableState.errorEmitted=!0,jn(e,n),Wn(e,t))}(e,r,n,t,i);else{var o=zn(r)||e.destroyed;o||r.corked||r.bufferProcessing||!r.bufferedRequest||Dn(e,r),n?Mt.nextTick(Pn,e,r,o,i):Pn(e,r,o,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new yn(this)}function Cn(e){var t=this instanceof(pn=pn||Kn);if(!t&&!_n.call(Cn,this))return new Cn(e);this._writableState=new In(e,this,t),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),mn.call(this)}function Nn(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new Bn("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function Pn(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),Wn(e,t)}function Dn(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var a=0,s=!0;r;)i[a]=r,r.isBuf||(s=!1),r=r.next,a+=1;i.allBuffers=s,Nn(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new yn(t),t.bufferedRequestCount=0}else{for(;r;){var u=r.chunk,h=r.encoding,l=r.callback;if(Nn(e,t,!1,t.objectMode?1:u.length,u,h,l),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function zn(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function qn(e,t){e._final((function(r){t.pendingcb--,r&&jn(e,r),t.prefinished=!0,e.emit("prefinish"),Wn(e,t)}))}function Wn(e,t){var r=zn(t);if(r&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,Mt.nextTick(qn,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var n=e._readableState;(!n||n.autoDestroy&&n.endEmitted)&&e.destroy()}return r}fn.exports(Cn,mn),In.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(In.prototype,"buffer",{get:bn.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(_n=Function.prototype[Symbol.hasInstance],Object.defineProperty(Cn,Symbol.hasInstance,{value:function(e){return!!_n.call(this,e)||this===Cn&&(e&&e._writableState instanceof In)}})):_n=function(e){return e instanceof this},Cn.prototype.pipe=function(){jn(this,new Tn)},Cn.prototype.write=function(e,t,r){var n,i=this._writableState,o=!1,a=!i.objectMode&&(n=e,vn.isBuffer(n)||n instanceof wn);return a&&!vn.isBuffer(e)&&(e=function(e){return vn.from(e)}(e)),"function"==typeof t&&(r=t,t=null),a?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=Un),i.ending?function(e,t){var r=new Mn;jn(e,r),Mt.nextTick(t,r)}(this,r):(a||function(e,t,r,n){var i;return null===r?i=new On:"string"==typeof r||t.objectMode||(i=new xn("chunk",["string","Buffer"],r)),!i||(jn(e,i),Mt.nextTick(n,i),!1)}(this,i,e,r))&&(i.pendingcb++,o=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=vn.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new Ln(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(Cn.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Cn.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Cn.prototype._write=function(e,t,r){r(new Rn("_write()"))},Cn.prototype._writev=null,Cn.prototype.end=function(e,t,r){var n=this._writableState;return"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||function(e,t,r){t.ending=!0,Wn(e,t),r&&(t.finished?Mt.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r),this},Object.defineProperty(Cn.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Cn.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),Cn.prototype.destroy=En.destroy,Cn.prototype._undestroy=En.undestroy,Cn.prototype._destroy=function(e,t){t(e)};var Fn=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t},Kn=Jn,Yn=wi,Hn=gn;fn.exports(Jn,Yn);for(var $n=Fn(Hn.prototype),Vn=0;Vn<$n.length;Vn++){var Gn=$n[Vn];Jn.prototype[Gn]||(Jn.prototype[Gn]=Hn.prototype[Gn])}function Jn(e){if(!(this instanceof Jn))return new Jn(e);Yn.call(this,e),Hn.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",Xn)))}function Xn(){this._writableState.ended||Mt.nextTick(Zn,this)}function Zn(e){e.end()}Object.defineProperty(Jn.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Jn.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Jn.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(Jn.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}});var Qn=on.codes.ERR_STREAM_PREMATURE_CLOSE;function ei(){}var ti,ri=function e(t,r,n){if("function"==typeof r)return e(t,null,r);r||(r={}),n=function(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===Si.prototype||(t=function(e){return Si.from(e)}(t)),n)a.endEmitted?Pi(e,new Ni):Fi(e,a,t,!0);else if(a.ended)Pi(e,new Ii);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?Fi(e,a,t,!1):$i(e,a)):Fi(e,a,t,!1)}else n||(a.reading=!1,$i(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=1073741824?e=1073741824:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function Yi(e){var t=e._readableState;xi("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(xi("emitReadable",t.flowing),t.emittedReadable=!0,Mt.nextTick(Hi,e))}function Hi(e){var t=e._readableState;xi("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,Zi(e)}function $i(e,t){t.readingMore||(t.readingMore=!0,Mt.nextTick(Vi,e,t))}function Vi(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function Ji(e){xi("readable nexttick read 0"),e.read(0)}function Xi(e,t){xi("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),Zi(e),t.flowing&&!t.reading&&e.read(0)}function Zi(e){var t=e._readableState;for(xi("flow",t.flowing);t.flowing&&null!==e.read(););}function Qi(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function eo(e){var t=e._readableState;xi("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,Mt.nextTick(to,t,e))}function to(e,t){if(xi("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function ro(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return xi("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?eo(this):Yi(this),null;if(0===(e=Ki(e,t))&&t.ended)return 0===t.length&&eo(this),null;var n,i=t.needReadable;return xi("need readable",i),(0===t.length||t.length-e0?Qi(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&eo(this)),null!==n&&this.emit("data",n),n},qi.prototype._read=function(e){Pi(this,new Ci("_read()"))},qi.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,xi("pipe count=%d opts=%j",n.pipesCount,t);var i=(!t||!1!==t.end)&&e!==Mt.stdout&&e!==Mt.stderr?a:d;function o(t,i){xi("onunpipe"),t===r&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,xi("cleanup"),e.removeListener("close",f),e.removeListener("finish",c),e.removeListener("drain",s),e.removeListener("error",l),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",d),r.removeListener("data",h),u=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||s())}function a(){xi("onend"),e.end()}n.endEmitted?Mt.nextTick(i):r.once("end",i),e.on("unpipe",o);var s=function(e){return function(){var t=e._readableState;xi("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&_i(e,"data")&&(t.flowing=!0,Zi(e))}}(r);e.on("drain",s);var u=!1;function h(t){xi("ondata");var i=e.write(t);xi("dest.write",i),!1===i&&((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==ro(n.pipes,e))&&!u&&(xi("false write response, pause",n.awaitDrain),n.awaitDrain++),r.pause())}function l(t){xi("onerror",t),d(),e.removeListener("error",l),0===_i(e,"error")&&Pi(e,t)}function f(){e.removeListener("finish",c),d()}function c(){xi("onfinish"),e.removeListener("close",f),d()}function d(){xi("unpipe"),r.unpipe(e)}return r.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",l),e.once("close",f),e.once("finish",c),e.emit("pipe",r),n.flowing||(xi("pipe resume"),r.resume()),e},qi.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r)),this;if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==n.flowing&&this.resume()):"readable"===e&&(n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,xi("on readable",n.length,n.reading),n.length?Yi(this):n.reading||Mt.nextTick(Ji,this))),r},qi.prototype.addListener=qi.prototype.on,qi.prototype.removeListener=function(e,t){var r=Ei.prototype.removeListener.call(this,e,t);return"readable"===e&&Mt.nextTick(Gi,this),r},qi.prototype.removeAllListeners=function(e){var t=Ei.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||Mt.nextTick(Gi,this),t},qi.prototype.resume=function(){var e=this._readableState;return e.flowing||(xi("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,Mt.nextTick(Xi,e,t))}(this,e)),e.paused=!1,this},qi.prototype.pause=function(){return xi("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(xi("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},qi.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",(function(){if(xi("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(i){(xi("wrapped data"),r.decoder&&(i=r.decoder.write(i)),r.objectMode&&null==i)||(r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause()))})),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o0,(function(e){n||(n=e),e&&o.forEach(ko),a||(o.forEach(ko),i(n))}))}));return t.reduce(xo)};!function(e,t){(t=Kr.exports=wi).Stream=t,t.Readable=t,t.Writable=gn,t.Duplex=Kn,t.Transform=no,t.PassThrough=yo,t.finished=ri,t.pipeline=Ao}(0,Kr.exports);var To=Fr.exports.Buffer,Bo=Kr.exports.Transform;function Oo(e){Bo.call(this),this._block=To.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}(0,fn.exports)(Oo,Bo),Oo.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(e){n=e}r(n)},Oo.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(e){t=e}e(t)},Oo.prototype.update=function(e,t){if(function(e,t){if(!To.isBuffer(e)&&"string"!=typeof e)throw new TypeError(t+" must be a string or a buffer")}(e,"Data"),this._finalized)throw new Error("Digest already called");To.isBuffer(e)||(e=To.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i0;++o)this._length[o]+=a,(a=this._length[o]/4294967296|0)>0&&(this._length[o]-=4294967296*a);return this},Oo.prototype._update=function(){throw new Error("_update is not implemented")},Oo.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();void 0!==e&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t},Oo.prototype._digest=function(){throw new Error("_digest is not implemented")};var Mo=Oo,Lo=Ie.exports,jo=Mo,Uo=Ce.exports.Buffer,Io=new Array(16);function Co(){jo.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}function No(e,t){return e<>>32-t}function Po(e,t,r,n,i,o,a){return No(e+(t&r|~t&n)+i+o|0,a)+t|0}function Do(e,t,r,n,i,o,a){return No(e+(t&n|r&~n)+i+o|0,a)+t|0}function zo(e,t,r,n,i,o,a){return No(e+(t^r^n)+i+o|0,a)+t|0}function qo(e,t,r,n,i,o,a){return No(e+(r^(t|~n))+i+o|0,a)+t|0}Lo(Co,jo),Co.prototype._update=function(){for(var e=Io,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);var r=this._a,n=this._b,i=this._c,o=this._d;r=Po(r,n,i,o,e[0],3614090360,7),o=Po(o,r,n,i,e[1],3905402710,12),i=Po(i,o,r,n,e[2],606105819,17),n=Po(n,i,o,r,e[3],3250441966,22),r=Po(r,n,i,o,e[4],4118548399,7),o=Po(o,r,n,i,e[5],1200080426,12),i=Po(i,o,r,n,e[6],2821735955,17),n=Po(n,i,o,r,e[7],4249261313,22),r=Po(r,n,i,o,e[8],1770035416,7),o=Po(o,r,n,i,e[9],2336552879,12),i=Po(i,o,r,n,e[10],4294925233,17),n=Po(n,i,o,r,e[11],2304563134,22),r=Po(r,n,i,o,e[12],1804603682,7),o=Po(o,r,n,i,e[13],4254626195,12),i=Po(i,o,r,n,e[14],2792965006,17),r=Do(r,n=Po(n,i,o,r,e[15],1236535329,22),i,o,e[1],4129170786,5),o=Do(o,r,n,i,e[6],3225465664,9),i=Do(i,o,r,n,e[11],643717713,14),n=Do(n,i,o,r,e[0],3921069994,20),r=Do(r,n,i,o,e[5],3593408605,5),o=Do(o,r,n,i,e[10],38016083,9),i=Do(i,o,r,n,e[15],3634488961,14),n=Do(n,i,o,r,e[4],3889429448,20),r=Do(r,n,i,o,e[9],568446438,5),o=Do(o,r,n,i,e[14],3275163606,9),i=Do(i,o,r,n,e[3],4107603335,14),n=Do(n,i,o,r,e[8],1163531501,20),r=Do(r,n,i,o,e[13],2850285829,5),o=Do(o,r,n,i,e[2],4243563512,9),i=Do(i,o,r,n,e[7],1735328473,14),r=zo(r,n=Do(n,i,o,r,e[12],2368359562,20),i,o,e[5],4294588738,4),o=zo(o,r,n,i,e[8],2272392833,11),i=zo(i,o,r,n,e[11],1839030562,16),n=zo(n,i,o,r,e[14],4259657740,23),r=zo(r,n,i,o,e[1],2763975236,4),o=zo(o,r,n,i,e[4],1272893353,11),i=zo(i,o,r,n,e[7],4139469664,16),n=zo(n,i,o,r,e[10],3200236656,23),r=zo(r,n,i,o,e[13],681279174,4),o=zo(o,r,n,i,e[0],3936430074,11),i=zo(i,o,r,n,e[3],3572445317,16),n=zo(n,i,o,r,e[6],76029189,23),r=zo(r,n,i,o,e[9],3654602809,4),o=zo(o,r,n,i,e[12],3873151461,11),i=zo(i,o,r,n,e[15],530742520,16),r=qo(r,n=zo(n,i,o,r,e[2],3299628645,23),i,o,e[0],4096336452,6),o=qo(o,r,n,i,e[7],1126891415,10),i=qo(i,o,r,n,e[14],2878612391,15),n=qo(n,i,o,r,e[5],4237533241,21),r=qo(r,n,i,o,e[12],1700485571,6),o=qo(o,r,n,i,e[3],2399980690,10),i=qo(i,o,r,n,e[10],4293915773,15),n=qo(n,i,o,r,e[1],2240044497,21),r=qo(r,n,i,o,e[8],1873313359,6),o=qo(o,r,n,i,e[15],4264355552,10),i=qo(i,o,r,n,e[6],2734768916,15),n=qo(n,i,o,r,e[13],1309151649,21),r=qo(r,n,i,o,e[4],4149444226,6),o=qo(o,r,n,i,e[11],3174756917,10),i=qo(i,o,r,n,e[2],718787259,15),n=qo(n,i,o,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+o|0},Co.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=Uo.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e};var Wo=Co,Fo=Ne.Buffer,Ko=Ie.exports,Yo=Mo,Ho=new Array(16),$o=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Vo=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Go=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Jo=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],Xo=[0,1518500249,1859775393,2400959708,2840853838],Zo=[1352829926,1548603684,1836072691,2053994217,0];function Qo(){Yo.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}function ea(e,t){return e<>>32-t}function ta(e,t,r,n,i,o,a,s){return ea(e+(t^r^n)+o+a|0,s)+i|0}function ra(e,t,r,n,i,o,a,s){return ea(e+(t&r|~t&n)+o+a|0,s)+i|0}function na(e,t,r,n,i,o,a,s){return ea(e+((t|~r)^n)+o+a|0,s)+i|0}function ia(e,t,r,n,i,o,a,s){return ea(e+(t&n|r&~n)+o+a|0,s)+i|0}function oa(e,t,r,n,i,o,a,s){return ea(e+(t^(r|~n))+o+a|0,s)+i|0}Ko(Qo,Yo),Qo.prototype._update=function(){for(var e=Ho,t=0;t<16;++t)e[t]=this._block.readInt32LE(4*t);for(var r=0|this._a,n=0|this._b,i=0|this._c,o=0|this._d,a=0|this._e,s=0|this._a,u=0|this._b,h=0|this._c,l=0|this._d,f=0|this._e,c=0;c<80;c+=1){var d,p;c<16?(d=ta(r,n,i,o,a,e[$o[c]],Xo[0],Go[c]),p=oa(s,u,h,l,f,e[Vo[c]],Zo[0],Jo[c])):c<32?(d=ra(r,n,i,o,a,e[$o[c]],Xo[1],Go[c]),p=ia(s,u,h,l,f,e[Vo[c]],Zo[1],Jo[c])):c<48?(d=na(r,n,i,o,a,e[$o[c]],Xo[2],Go[c]),p=na(s,u,h,l,f,e[Vo[c]],Zo[2],Jo[c])):c<64?(d=ia(r,n,i,o,a,e[$o[c]],Xo[3],Go[c]),p=ra(s,u,h,l,f,e[Vo[c]],Zo[3],Jo[c])):(d=oa(r,n,i,o,a,e[$o[c]],Xo[4],Go[c]),p=ta(s,u,h,l,f,e[Vo[c]],Zo[4],Jo[c])),r=a,a=o,o=ea(i,10),i=n,n=d,s=f,f=l,l=ea(h,10),h=u,u=p}var g=this._b+i+l|0;this._b=this._c+o+f|0,this._c=this._d+a+s|0,this._d=this._e+r+u|0,this._e=this._a+n+h|0,this._a=g},Qo.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=Fo.alloc?Fo.alloc(20):new Fo(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e};var aa=Qo,sa={exports:{}},ua=Ce.exports.Buffer;function ha(e,t){this._block=ua.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}ha.prototype.update=function(e,t){"string"==typeof e&&(t=t||"utf8",e=ua.from(e,t));for(var r=this._block,n=this._blockSize,i=e.length,o=this._len,a=0;a=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=8*this._len;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(4294967295&r)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var o=this._hash();return e?o.toString(e):o},ha.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var la=ha,fa=Ie.exports,ca=la,da=Ce.exports.Buffer,pa=[1518500249,1859775393,-1894007588,-899497514],ga=new Array(80);function ya(){this.init(),this._w=ga,ca.call(this,64,56)}function ba(e){return e<<30|e>>>2}function ma(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}fa(ya,ca),ya.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},ya.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,s=0|this._e,u=0;u<16;++u)r[u]=e.readInt32BE(4*u);for(;u<80;++u)r[u]=r[u-3]^r[u-8]^r[u-14]^r[u-16];for(var h=0;h<80;++h){var l=~~(h/20),f=0|((t=n)<<5|t>>>27)+ma(l,i,o,a)+s+r[h]+pa[l];s=a,a=o,o=ba(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=s+this._e|0},ya.prototype._hash=function(){var e=da.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e};var va=ya,wa=Ie.exports,_a=la,Ea=Ce.exports.Buffer,Sa=[1518500249,1859775393,-1894007588,-899497514],ka=new Array(80);function xa(){this.init(),this._w=ka,_a.call(this,64,56)}function Ra(e){return e<<5|e>>>27}function Aa(e){return e<<30|e>>>2}function Ta(e,t,r,n){return 0===e?t&r|~t&n:2===e?t&r|t&n|r&n:t^r^n}wa(xa,_a),xa.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this},xa.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,s=0|this._e,u=0;u<16;++u)r[u]=e.readInt32BE(4*u);for(;u<80;++u)r[u]=(t=r[u-3]^r[u-8]^r[u-14]^r[u-16])<<1|t>>>31;for(var h=0;h<80;++h){var l=~~(h/20),f=Ra(n)+Ta(l,i,o,a)+s+r[h]+Sa[l]|0;s=a,a=o,o=Aa(i),i=n,n=f}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=s+this._e|0},xa.prototype._hash=function(){var e=Ea.allocUnsafe(20);return e.writeInt32BE(0|this._a,0),e.writeInt32BE(0|this._b,4),e.writeInt32BE(0|this._c,8),e.writeInt32BE(0|this._d,12),e.writeInt32BE(0|this._e,16),e};var Ba=xa,Oa=Ie.exports,Ma=la,La=Ce.exports.Buffer,ja=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ua=new Array(64);function Ia(){this.init(),this._w=Ua,Ma.call(this,64,56)}function Ca(e,t,r){return r^e&(t^r)}function Na(e,t,r){return e&t|r&(e|t)}function Pa(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function Da(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function za(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}Oa(Ia,Ma),Ia.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this},Ia.prototype._update=function(e){for(var t,r=this._w,n=0|this._a,i=0|this._b,o=0|this._c,a=0|this._d,s=0|this._e,u=0|this._f,h=0|this._g,l=0|this._h,f=0;f<16;++f)r[f]=e.readInt32BE(4*f);for(;f<64;++f)r[f]=0|(((t=r[f-2])>>>17|t<<15)^(t>>>19|t<<13)^t>>>10)+r[f-7]+za(r[f-15])+r[f-16];for(var c=0;c<64;++c){var d=l+Da(s)+Ca(s,u,h)+ja[c]+r[c]|0,p=Pa(n)+Na(n,i,o)|0;l=h,h=u,u=s,s=a+d|0,a=o,o=i,i=n,n=d+p|0}this._a=n+this._a|0,this._b=i+this._b|0,this._c=o+this._c|0,this._d=a+this._d|0,this._e=s+this._e|0,this._f=u+this._f|0,this._g=h+this._g|0,this._h=l+this._h|0},Ia.prototype._hash=function(){var e=La.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var qa=Ia,Wa=Ie.exports,Fa=qa,Ka=la,Ya=Ce.exports.Buffer,Ha=new Array(64);function $a(){this.init(),this._w=Ha,Ka.call(this,64,56)}Wa($a,Fa),$a.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},$a.prototype._hash=function(){var e=Ya.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var Va=$a,Ga=Ie.exports,Ja=la,Xa=Ce.exports.Buffer,Za=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Qa=new Array(160);function es(){this.init(),this._w=Qa,Ja.call(this,128,112)}function ts(e,t,r){return r^e&(t^r)}function rs(e,t,r){return e&t|r&(e|t)}function ns(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function is(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function os(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function as(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function ss(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function us(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function hs(e,t){return e>>>0>>0?1:0}Ga(es,Ja),es.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this},es.prototype._update=function(e){for(var t=this._w,r=0|this._ah,n=0|this._bh,i=0|this._ch,o=0|this._dh,a=0|this._eh,s=0|this._fh,u=0|this._gh,h=0|this._hh,l=0|this._al,f=0|this._bl,c=0|this._cl,d=0|this._dl,p=0|this._el,g=0|this._fl,y=0|this._gl,b=0|this._hl,m=0;m<32;m+=2)t[m]=e.readInt32BE(4*m),t[m+1]=e.readInt32BE(4*m+4);for(;m<160;m+=2){var v=t[m-30],w=t[m-30+1],_=os(v,w),E=as(w,v),S=ss(v=t[m-4],w=t[m-4+1]),k=us(w,v),x=t[m-14],R=t[m-14+1],A=t[m-32],T=t[m-32+1],B=E+R|0,O=_+x+hs(B,E)|0;O=(O=O+S+hs(B=B+k|0,k)|0)+A+hs(B=B+T|0,T)|0,t[m]=O,t[m+1]=B}for(var M=0;M<160;M+=2){O=t[M],B=t[M+1];var L=rs(r,n,i),j=rs(l,f,c),U=ns(r,l),I=ns(l,r),C=is(a,p),N=is(p,a),P=Za[M],D=Za[M+1],z=ts(a,s,u),q=ts(p,g,y),W=b+N|0,F=h+C+hs(W,b)|0;F=(F=(F=F+z+hs(W=W+q|0,q)|0)+P+hs(W=W+D|0,D)|0)+O+hs(W=W+B|0,B)|0;var K=I+j|0,Y=U+L+hs(K,I)|0;h=u,b=y,u=s,y=g,s=a,g=p,a=o+F+hs(p=d+W|0,d)|0,o=i,d=c,i=n,c=f,n=r,f=l,r=F+Y+hs(l=W+K|0,W)|0}this._al=this._al+l|0,this._bl=this._bl+f|0,this._cl=this._cl+c|0,this._dl=this._dl+d|0,this._el=this._el+p|0,this._fl=this._fl+g|0,this._gl=this._gl+y|0,this._hl=this._hl+b|0,this._ah=this._ah+r+hs(this._al,l)|0,this._bh=this._bh+n+hs(this._bl,f)|0,this._ch=this._ch+i+hs(this._cl,c)|0,this._dh=this._dh+o+hs(this._dl,d)|0,this._eh=this._eh+a+hs(this._el,p)|0,this._fh=this._fh+s+hs(this._fl,g)|0,this._gh=this._gh+u+hs(this._gl,y)|0,this._hh=this._hh+h+hs(this._hl,b)|0},es.prototype._hash=function(){var e=Xa.allocUnsafe(64);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var ls=es,fs=Ie.exports,cs=ls,ds=la,ps=Ce.exports.Buffer,gs=new Array(160);function ys(){this.init(),this._w=gs,ds.call(this,128,112)}fs(ys,cs),ys.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},ys.prototype._hash=function(){var e=ps.allocUnsafe(48);function t(t,r,n){e.writeInt32BE(t,n),e.writeInt32BE(r,n+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var bs=ys,ms=sa.exports=function(e){e=e.toLowerCase();var t=ms[e];if(!t)throw new Error(e+" is not supported (we accept pull requests)");return new t};ms.sha=va,ms.sha1=Ba,ms.sha224=Va,ms.sha256=qa,ms.sha384=bs,ms.sha512=ls;var vs=Ie.exports,ws=Wr,_s=Cr,Es=Ce.exports.Buffer,Ss=function(e){return(new Wo).update(e).digest()},ks=aa,xs=sa.exports,Rs=Es.alloc(128);function As(e,t){_s.call(this,"digest"),"string"==typeof t&&(t=Es.from(t));var r="sha512"===e||"sha384"===e?128:64;(this._alg=e,this._key=t,t.length>r)?t=("rmd160"===e?new ks:xs(e)).update(t).digest():t.length>24&255,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r,e[t+4]=n>>24&255,e[t+5]=n>>16&255,e[t+6]=n>>8&255,e[t+7]=255&n}function p(e,t,r,n,i){var o,a=0;for(o=0;o>>8)-1}function g(e,t,r,n){return p(e,t,r,n,16)}function y(e,t,r,n){return p(e,t,r,n,32)}function b(e,t,r,n){!function(e,t,r,n){for(var i,o=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,c=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,y=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,b=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,m=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,v=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,_=o,E=a,S=s,k=u,x=h,R=l,A=f,T=c,B=d,O=p,M=g,L=y,j=b,U=m,I=v,C=w,N=0;N<20;N+=2)_^=(i=(j^=(i=(B^=(i=(x^=(i=_+j|0)<<7|i>>>25)+_|0)<<9|i>>>23)+x|0)<<13|i>>>19)+B|0)<<18|i>>>14,R^=(i=(E^=(i=(U^=(i=(O^=(i=R+E|0)<<7|i>>>25)+R|0)<<9|i>>>23)+O|0)<<13|i>>>19)+U|0)<<18|i>>>14,M^=(i=(A^=(i=(S^=(i=(I^=(i=M+A|0)<<7|i>>>25)+M|0)<<9|i>>>23)+I|0)<<13|i>>>19)+S|0)<<18|i>>>14,C^=(i=(L^=(i=(T^=(i=(k^=(i=C+L|0)<<7|i>>>25)+C|0)<<9|i>>>23)+k|0)<<13|i>>>19)+T|0)<<18|i>>>14,_^=(i=(k^=(i=(S^=(i=(E^=(i=_+k|0)<<7|i>>>25)+_|0)<<9|i>>>23)+E|0)<<13|i>>>19)+S|0)<<18|i>>>14,R^=(i=(x^=(i=(T^=(i=(A^=(i=R+x|0)<<7|i>>>25)+R|0)<<9|i>>>23)+A|0)<<13|i>>>19)+T|0)<<18|i>>>14,M^=(i=(O^=(i=(B^=(i=(L^=(i=M+O|0)<<7|i>>>25)+M|0)<<9|i>>>23)+L|0)<<13|i>>>19)+B|0)<<18|i>>>14,C^=(i=(I^=(i=(U^=(i=(j^=(i=C+I|0)<<7|i>>>25)+C|0)<<9|i>>>23)+j|0)<<13|i>>>19)+U|0)<<18|i>>>14;_=_+o|0,E=E+a|0,S=S+s|0,k=k+u|0,x=x+h|0,R=R+l|0,A=A+f|0,T=T+c|0,B=B+d|0,O=O+p|0,M=M+g|0,L=L+y|0,j=j+b|0,U=U+m|0,I=I+v|0,C=C+w|0,e[0]=_>>>0&255,e[1]=_>>>8&255,e[2]=_>>>16&255,e[3]=_>>>24&255,e[4]=E>>>0&255,e[5]=E>>>8&255,e[6]=E>>>16&255,e[7]=E>>>24&255,e[8]=S>>>0&255,e[9]=S>>>8&255,e[10]=S>>>16&255,e[11]=S>>>24&255,e[12]=k>>>0&255,e[13]=k>>>8&255,e[14]=k>>>16&255,e[15]=k>>>24&255,e[16]=x>>>0&255,e[17]=x>>>8&255,e[18]=x>>>16&255,e[19]=x>>>24&255,e[20]=R>>>0&255,e[21]=R>>>8&255,e[22]=R>>>16&255,e[23]=R>>>24&255,e[24]=A>>>0&255,e[25]=A>>>8&255,e[26]=A>>>16&255,e[27]=A>>>24&255,e[28]=T>>>0&255,e[29]=T>>>8&255,e[30]=T>>>16&255,e[31]=T>>>24&255,e[32]=B>>>0&255,e[33]=B>>>8&255,e[34]=B>>>16&255,e[35]=B>>>24&255,e[36]=O>>>0&255,e[37]=O>>>8&255,e[38]=O>>>16&255,e[39]=O>>>24&255,e[40]=M>>>0&255,e[41]=M>>>8&255,e[42]=M>>>16&255,e[43]=M>>>24&255,e[44]=L>>>0&255,e[45]=L>>>8&255,e[46]=L>>>16&255,e[47]=L>>>24&255,e[48]=j>>>0&255,e[49]=j>>>8&255,e[50]=j>>>16&255,e[51]=j>>>24&255,e[52]=U>>>0&255,e[53]=U>>>8&255,e[54]=U>>>16&255,e[55]=U>>>24&255,e[56]=I>>>0&255,e[57]=I>>>8&255,e[58]=I>>>16&255,e[59]=I>>>24&255,e[60]=C>>>0&255,e[61]=C>>>8&255,e[62]=C>>>16&255,e[63]=C>>>24&255}(e,t,r,n)}function m(e,t,r,n){!function(e,t,r,n){for(var i,o=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,s=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,u=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,h=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,l=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,c=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,d=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,g=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,y=255&r[16]|(255&r[17])<<8|(255&r[18])<<16|(255&r[19])<<24,b=255&r[20]|(255&r[21])<<8|(255&r[22])<<16|(255&r[23])<<24,m=255&r[24]|(255&r[25])<<8|(255&r[26])<<16|(255&r[27])<<24,v=255&r[28]|(255&r[29])<<8|(255&r[30])<<16|(255&r[31])<<24,w=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,_=0;_<20;_+=2)o^=(i=(b^=(i=(d^=(i=(h^=(i=o+b|0)<<7|i>>>25)+o|0)<<9|i>>>23)+h|0)<<13|i>>>19)+d|0)<<18|i>>>14,l^=(i=(a^=(i=(m^=(i=(p^=(i=l+a|0)<<7|i>>>25)+l|0)<<9|i>>>23)+p|0)<<13|i>>>19)+m|0)<<18|i>>>14,g^=(i=(f^=(i=(s^=(i=(v^=(i=g+f|0)<<7|i>>>25)+g|0)<<9|i>>>23)+v|0)<<13|i>>>19)+s|0)<<18|i>>>14,w^=(i=(y^=(i=(c^=(i=(u^=(i=w+y|0)<<7|i>>>25)+w|0)<<9|i>>>23)+u|0)<<13|i>>>19)+c|0)<<18|i>>>14,o^=(i=(u^=(i=(s^=(i=(a^=(i=o+u|0)<<7|i>>>25)+o|0)<<9|i>>>23)+a|0)<<13|i>>>19)+s|0)<<18|i>>>14,l^=(i=(h^=(i=(c^=(i=(f^=(i=l+h|0)<<7|i>>>25)+l|0)<<9|i>>>23)+f|0)<<13|i>>>19)+c|0)<<18|i>>>14,g^=(i=(p^=(i=(d^=(i=(y^=(i=g+p|0)<<7|i>>>25)+g|0)<<9|i>>>23)+y|0)<<13|i>>>19)+d|0)<<18|i>>>14,w^=(i=(v^=(i=(m^=(i=(b^=(i=w+v|0)<<7|i>>>25)+w|0)<<9|i>>>23)+b|0)<<13|i>>>19)+m|0)<<18|i>>>14;e[0]=o>>>0&255,e[1]=o>>>8&255,e[2]=o>>>16&255,e[3]=o>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=g>>>0&255,e[9]=g>>>8&255,e[10]=g>>>16&255,e[11]=g>>>24&255,e[12]=w>>>0&255,e[13]=w>>>8&255,e[14]=w>>>16&255,e[15]=w>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=c>>>0&255,e[21]=c>>>8&255,e[22]=c>>>16&255,e[23]=c>>>24&255,e[24]=d>>>0&255,e[25]=d>>>8&255,e[26]=d>>>16&255,e[27]=d>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,t,r,n)}var v=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function w(e,t,r,n,i,o,a){var s,u,h=new Uint8Array(16),l=new Uint8Array(64);for(u=0;u<16;u++)h[u]=0;for(u=0;u<8;u++)h[u]=o[u];for(;i>=64;){for(b(l,h,a,v),u=0;u<64;u++)e[t+u]=r[n+u]^l[u];for(s=1,u=8;u<16;u++)s=s+(255&h[u])|0,h[u]=255&s,s>>>=8;i-=64,t+=64,n+=64}if(i>0)for(b(l,h,a,v),u=0;u=64;){for(b(u,s,i,v),a=0;a<64;a++)e[t+a]=u[a];for(o=1,a=8;a<16;a++)o=o+(255&s[a])|0,s[a]=255&o,o>>>=8;r-=64,t+=64}if(r>0)for(b(u,s,i,v),a=0;a>>13|r<<3),n=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(r>>>10|n<<6),i=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(n>>>7|i<<9),o=255&e[8]|(255&e[9])<<8,this.r[4]=255&(i>>>4|o<<12),this.r[5]=o>>>1&8190,a=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(o>>>14|a<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(a>>>11|s<<5),u=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|u<<8),this.r[9]=u>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function x(e,t,r,n,i,o){var a=new k(o);return a.update(r,n,i),a.finish(e,t),0}function R(e,t,r,n,i,o){var a=new Uint8Array(16);return x(a,0,r,n,i,o),g(e,t,a,0)}function A(e,t,r,n,i){var o;if(r<32)return-1;for(S(e,0,t,0,r,n,i),x(e,16,e,32,r-32,e),o=0;o<16;o++)e[o]=0;return 0}function T(e,t,r,n,i){var o,a=new Uint8Array(32);if(r<32)return-1;if(E(a,0,32,n,i),0!==R(t,16,t,32,r-32,a))return-1;for(S(e,0,t,0,r,n,i),o=0;o<32;o++)e[o]=0;return 0}function B(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function O(e){var t,r,n=1;for(t=0;t<16;t++)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function M(e,t,r){for(var n,i=~(r-1),o=0;o<16;o++)n=i&(e[o]^t[o]),e[o]^=n,t[o]^=n}function L(e,r){var n,i,o,a=t(),s=t();for(n=0;n<16;n++)s[n]=r[n];for(O(s),O(s),O(s),i=0;i<2;i++){for(a[0]=s[0]-65517,n=1;n<15;n++)a[n]=s[n]-65535-(a[n-1]>>16&1),a[n-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),o=a[15]>>16&1,a[14]&=65535,M(s,a,1-o)}for(n=0;n<16;n++)e[2*n]=255&s[n],e[2*n+1]=s[n]>>8}function j(e,t){var r=new Uint8Array(32),n=new Uint8Array(32);return L(r,e),L(n,t),y(r,0,n,0)}function I(e){var t=new Uint8Array(32);return L(t,e),1&t[0]}function C(e,t){var r;for(r=0;r<16;r++)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function N(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]+r[n]}function P(e,t,r){for(var n=0;n<16;n++)e[n]=t[n]-r[n]}function D(e,t,r){var n,i,o=0,a=0,s=0,u=0,h=0,l=0,f=0,c=0,d=0,p=0,g=0,y=0,b=0,m=0,v=0,w=0,_=0,E=0,S=0,k=0,x=0,R=0,A=0,T=0,B=0,O=0,M=0,L=0,j=0,U=0,I=0,C=r[0],N=r[1],P=r[2],D=r[3],z=r[4],q=r[5],W=r[6],F=r[7],K=r[8],Y=r[9],H=r[10],$=r[11],V=r[12],G=r[13],J=r[14],X=r[15];o+=(n=t[0])*C,a+=n*N,s+=n*P,u+=n*D,h+=n*z,l+=n*q,f+=n*W,c+=n*F,d+=n*K,p+=n*Y,g+=n*H,y+=n*$,b+=n*V,m+=n*G,v+=n*J,w+=n*X,a+=(n=t[1])*C,s+=n*N,u+=n*P,h+=n*D,l+=n*z,f+=n*q,c+=n*W,d+=n*F,p+=n*K,g+=n*Y,y+=n*H,b+=n*$,m+=n*V,v+=n*G,w+=n*J,_+=n*X,s+=(n=t[2])*C,u+=n*N,h+=n*P,l+=n*D,f+=n*z,c+=n*q,d+=n*W,p+=n*F,g+=n*K,y+=n*Y,b+=n*H,m+=n*$,v+=n*V,w+=n*G,_+=n*J,E+=n*X,u+=(n=t[3])*C,h+=n*N,l+=n*P,f+=n*D,c+=n*z,d+=n*q,p+=n*W,g+=n*F,y+=n*K,b+=n*Y,m+=n*H,v+=n*$,w+=n*V,_+=n*G,E+=n*J,S+=n*X,h+=(n=t[4])*C,l+=n*N,f+=n*P,c+=n*D,d+=n*z,p+=n*q,g+=n*W,y+=n*F,b+=n*K,m+=n*Y,v+=n*H,w+=n*$,_+=n*V,E+=n*G,S+=n*J,k+=n*X,l+=(n=t[5])*C,f+=n*N,c+=n*P,d+=n*D,p+=n*z,g+=n*q,y+=n*W,b+=n*F,m+=n*K,v+=n*Y,w+=n*H,_+=n*$,E+=n*V,S+=n*G,k+=n*J,x+=n*X,f+=(n=t[6])*C,c+=n*N,d+=n*P,p+=n*D,g+=n*z,y+=n*q,b+=n*W,m+=n*F,v+=n*K,w+=n*Y,_+=n*H,E+=n*$,S+=n*V,k+=n*G,x+=n*J,R+=n*X,c+=(n=t[7])*C,d+=n*N,p+=n*P,g+=n*D,y+=n*z,b+=n*q,m+=n*W,v+=n*F,w+=n*K,_+=n*Y,E+=n*H,S+=n*$,k+=n*V,x+=n*G,R+=n*J,A+=n*X,d+=(n=t[8])*C,p+=n*N,g+=n*P,y+=n*D,b+=n*z,m+=n*q,v+=n*W,w+=n*F,_+=n*K,E+=n*Y,S+=n*H,k+=n*$,x+=n*V,R+=n*G,A+=n*J,T+=n*X,p+=(n=t[9])*C,g+=n*N,y+=n*P,b+=n*D,m+=n*z,v+=n*q,w+=n*W,_+=n*F,E+=n*K,S+=n*Y,k+=n*H,x+=n*$,R+=n*V,A+=n*G,T+=n*J,B+=n*X,g+=(n=t[10])*C,y+=n*N,b+=n*P,m+=n*D,v+=n*z,w+=n*q,_+=n*W,E+=n*F,S+=n*K,k+=n*Y,x+=n*H,R+=n*$,A+=n*V,T+=n*G,B+=n*J,O+=n*X,y+=(n=t[11])*C,b+=n*N,m+=n*P,v+=n*D,w+=n*z,_+=n*q,E+=n*W,S+=n*F,k+=n*K,x+=n*Y,R+=n*H,A+=n*$,T+=n*V,B+=n*G,O+=n*J,M+=n*X,b+=(n=t[12])*C,m+=n*N,v+=n*P,w+=n*D,_+=n*z,E+=n*q,S+=n*W,k+=n*F,x+=n*K,R+=n*Y,A+=n*H,T+=n*$,B+=n*V,O+=n*G,M+=n*J,L+=n*X,m+=(n=t[13])*C,v+=n*N,w+=n*P,_+=n*D,E+=n*z,S+=n*q,k+=n*W,x+=n*F,R+=n*K,A+=n*Y,T+=n*H,B+=n*$,O+=n*V,M+=n*G,L+=n*J,j+=n*X,v+=(n=t[14])*C,w+=n*N,_+=n*P,E+=n*D,S+=n*z,k+=n*q,x+=n*W,R+=n*F,A+=n*K,T+=n*Y,B+=n*H,O+=n*$,M+=n*V,L+=n*G,j+=n*J,U+=n*X,w+=(n=t[15])*C,a+=38*(E+=n*P),s+=38*(S+=n*D),u+=38*(k+=n*z),h+=38*(x+=n*q),l+=38*(R+=n*W),f+=38*(A+=n*F),c+=38*(T+=n*K),d+=38*(B+=n*Y),p+=38*(O+=n*H),g+=38*(M+=n*$),y+=38*(L+=n*V),b+=38*(j+=n*G),m+=38*(U+=n*J),v+=38*(I+=n*X),o=(n=(o+=38*(_+=n*N))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),o=(n=(o+=i-1+37*(i-1))+(i=1)+65535)-65536*(i=Math.floor(n/65536)),a=(n=a+i+65535)-65536*(i=Math.floor(n/65536)),s=(n=s+i+65535)-65536*(i=Math.floor(n/65536)),u=(n=u+i+65535)-65536*(i=Math.floor(n/65536)),h=(n=h+i+65535)-65536*(i=Math.floor(n/65536)),l=(n=l+i+65535)-65536*(i=Math.floor(n/65536)),f=(n=f+i+65535)-65536*(i=Math.floor(n/65536)),c=(n=c+i+65535)-65536*(i=Math.floor(n/65536)),d=(n=d+i+65535)-65536*(i=Math.floor(n/65536)),p=(n=p+i+65535)-65536*(i=Math.floor(n/65536)),g=(n=g+i+65535)-65536*(i=Math.floor(n/65536)),y=(n=y+i+65535)-65536*(i=Math.floor(n/65536)),b=(n=b+i+65535)-65536*(i=Math.floor(n/65536)),m=(n=m+i+65535)-65536*(i=Math.floor(n/65536)),v=(n=v+i+65535)-65536*(i=Math.floor(n/65536)),w=(n=w+i+65535)-65536*(i=Math.floor(n/65536)),o+=i-1+37*(i-1),e[0]=o,e[1]=a,e[2]=s,e[3]=u,e[4]=h,e[5]=l,e[6]=f,e[7]=c,e[8]=d,e[9]=p,e[10]=g,e[11]=y,e[12]=b,e[13]=m,e[14]=v,e[15]=w}function z(e,t){D(e,t,t)}function q(e,r){var n,i=t();for(n=0;n<16;n++)i[n]=r[n];for(n=253;n>=0;n--)z(i,i),2!==n&&4!==n&&D(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}function W(e,r){var n,i=t();for(n=0;n<16;n++)i[n]=r[n];for(n=250;n>=0;n--)z(i,i),1!==n&&D(i,i,r);for(n=0;n<16;n++)e[n]=i[n]}function F(e,r,n){var i,o,a=new Uint8Array(32),u=new Float64Array(80),h=t(),l=t(),f=t(),c=t(),d=t(),p=t();for(o=0;o<31;o++)a[o]=r[o];for(a[31]=127&r[31]|64,a[0]&=248,C(u,n),o=0;o<16;o++)l[o]=u[o],c[o]=h[o]=f[o]=0;for(h[0]=c[0]=1,o=254;o>=0;--o)M(h,l,i=a[o>>>3]>>>(7&o)&1),M(f,c,i),N(d,h,f),P(h,h,f),N(f,l,c),P(l,l,c),z(c,d),z(p,h),D(h,f,h),D(f,l,d),N(d,h,f),P(h,h,f),z(l,h),P(f,c,p),D(h,f,s),N(h,h,c),D(f,f,h),D(h,c,p),D(c,l,u),z(l,d),M(h,l,i),M(f,c,i);for(o=0;o<16;o++)u[o+16]=h[o],u[o+32]=f[o],u[o+48]=l[o],u[o+64]=c[o];var g=u.subarray(32),y=u.subarray(16);return q(g,g),D(y,y,g),L(e,y),0}function K(e,t){return F(e,t,i)}function Y(e,t){return r(t,32),K(e,t)}function H(e,t,r){var i=new Uint8Array(32);return F(i,r,t),m(e,n,i,v)}k.prototype.blocks=function(e,t,r){for(var n,i,o,a,s,u,h,l,f,c,d,p,g,y,b,m,v,w,_,E=this.fin?0:2048,S=this.h[0],k=this.h[1],x=this.h[2],R=this.h[3],A=this.h[4],T=this.h[5],B=this.h[6],O=this.h[7],M=this.h[8],L=this.h[9],j=this.r[0],U=this.r[1],I=this.r[2],C=this.r[3],N=this.r[4],P=this.r[5],D=this.r[6],z=this.r[7],q=this.r[8],W=this.r[9];r>=16;)c=f=0,c+=(S+=8191&(n=255&e[t+0]|(255&e[t+1])<<8))*j,c+=(k+=8191&(n>>>13|(i=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*W),c+=(x+=8191&(i>>>10|(o=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*q),c+=(R+=8191&(o>>>7|(a=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*z),f=(c+=(A+=8191&(a>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*D))>>>13,c&=8191,c+=(T+=s>>>1&8191)*(5*P),c+=(B+=8191&(s>>>14|(u=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*N),c+=(O+=8191&(u>>>11|(h=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*C),c+=(M+=8191&(h>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*I),d=f+=(c+=(L+=l>>>5|E)*(5*U))>>>13,d+=S*U,d+=k*j,d+=x*(5*W),d+=R*(5*q),f=(d+=A*(5*z))>>>13,d&=8191,d+=T*(5*D),d+=B*(5*P),d+=O*(5*N),d+=M*(5*C),f+=(d+=L*(5*I))>>>13,d&=8191,p=f,p+=S*I,p+=k*U,p+=x*j,p+=R*(5*W),f=(p+=A*(5*q))>>>13,p&=8191,p+=T*(5*z),p+=B*(5*D),p+=O*(5*P),p+=M*(5*N),g=f+=(p+=L*(5*C))>>>13,g+=S*C,g+=k*I,g+=x*U,g+=R*j,f=(g+=A*(5*W))>>>13,g&=8191,g+=T*(5*q),g+=B*(5*z),g+=O*(5*D),g+=M*(5*P),y=f+=(g+=L*(5*N))>>>13,y+=S*N,y+=k*C,y+=x*I,y+=R*U,f=(y+=A*j)>>>13,y&=8191,y+=T*(5*W),y+=B*(5*q),y+=O*(5*z),y+=M*(5*D),b=f+=(y+=L*(5*P))>>>13,b+=S*P,b+=k*N,b+=x*C,b+=R*I,f=(b+=A*U)>>>13,b&=8191,b+=T*j,b+=B*(5*W),b+=O*(5*q),b+=M*(5*z),m=f+=(b+=L*(5*D))>>>13,m+=S*D,m+=k*P,m+=x*N,m+=R*C,f=(m+=A*I)>>>13,m&=8191,m+=T*U,m+=B*j,m+=O*(5*W),m+=M*(5*q),v=f+=(m+=L*(5*z))>>>13,v+=S*z,v+=k*D,v+=x*P,v+=R*N,f=(v+=A*C)>>>13,v&=8191,v+=T*I,v+=B*U,v+=O*j,v+=M*(5*W),w=f+=(v+=L*(5*q))>>>13,w+=S*q,w+=k*z,w+=x*D,w+=R*P,f=(w+=A*N)>>>13,w&=8191,w+=T*C,w+=B*I,w+=O*U,w+=M*j,_=f+=(w+=L*(5*W))>>>13,_+=S*W,_+=k*q,_+=x*z,_+=R*D,f=(_+=A*P)>>>13,_&=8191,_+=T*N,_+=B*C,_+=O*I,_+=M*U,S=c=8191&(f=(f=((f+=(_+=L*j)>>>13)<<2)+f|0)+(c&=8191)|0),k=d+=f>>>=13,x=p&=8191,R=g&=8191,A=y&=8191,T=b&=8191,B=m&=8191,O=v&=8191,M=w&=8191,L=_&=8191,t+=16,r-=16;this.h[0]=S,this.h[1]=k,this.h[2]=x,this.h[3]=R,this.h[4]=A,this.h[5]=T,this.h[6]=B,this.h[7]=O,this.h[8]=M,this.h[9]=L},k.prototype.finish=function(e,t){var r,n,i,o,a=new Uint16Array(10);if(this.leftover){for(o=this.leftover,this.buffer[o++]=1;o<16;o++)this.buffer[o]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(r=this.h[1]>>>13,this.h[1]&=8191,o=2;o<10;o++)this.h[o]+=r,r=this.h[o]>>>13,this.h[o]&=8191;for(this.h[0]+=5*r,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,a[0]=this.h[0]+5,r=a[0]>>>13,a[0]&=8191,o=1;o<10;o++)a[o]=this.h[o]+r,r=a[o]>>>13,a[o]&=8191;for(a[9]-=8192,n=(1^r)-1,o=0;o<10;o++)a[o]&=n;for(n=~n,o=0;o<10;o++)this.h[o]=this.h[o]&n|a[o];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),i=this.h[0]+this.pad[0],this.h[0]=65535&i,o=1;o<8;o++)i=(this.h[o]+this.pad[o]|0)+(i>>>16)|0,this.h[o]=65535&i;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},k.prototype.update=function(e,t,r){var n,i;if(this.leftover){for((i=16-this.leftover)>r&&(i=r),n=0;n=16&&(i=r-r%16,this.blocks(e,t,i),t+=i,r-=i),r){for(n=0;n=128;){for(E=0;E<16;E++)S=8*E+V,O[E]=r[S+0]<<24|r[S+1]<<16|r[S+2]<<8|r[S+3],M[E]=r[S+4]<<24|r[S+5]<<16|r[S+6]<<8|r[S+7];for(E=0;E<80;E++)if(i=L,o=j,a=U,s=I,u=C,h=N,l=P,c=z,d=q,p=W,g=F,y=K,b=Y,m=H,R=65535&(x=$),A=x>>>16,T=65535&(k=D),B=k>>>16,R+=65535&(x=(K>>>14|C<<18)^(K>>>18|C<<14)^(C>>>9|K<<23)),A+=x>>>16,T+=65535&(k=(C>>>14|K<<18)^(C>>>18|K<<14)^(K>>>9|C<<23)),B+=k>>>16,R+=65535&(x=K&Y^~K&H),A+=x>>>16,T+=65535&(k=C&N^~C&P),B+=k>>>16,R+=65535&(x=G[2*E+1]),A+=x>>>16,T+=65535&(k=G[2*E]),B+=k>>>16,k=O[E%16],A+=(x=M[E%16])>>>16,T+=65535&k,B+=k>>>16,T+=(A+=(R+=65535&x)>>>16)>>>16,R=65535&(x=_=65535&R|A<<16),A=x>>>16,T=65535&(k=w=65535&T|(B+=T>>>16)<<16),B=k>>>16,R+=65535&(x=(z>>>28|L<<4)^(L>>>2|z<<30)^(L>>>7|z<<25)),A+=x>>>16,T+=65535&(k=(L>>>28|z<<4)^(z>>>2|L<<30)^(z>>>7|L<<25)),B+=k>>>16,A+=(x=z&q^z&W^q&W)>>>16,T+=65535&(k=L&j^L&U^j&U),B+=k>>>16,f=65535&(T+=(A+=(R+=65535&x)>>>16)>>>16)|(B+=T>>>16)<<16,v=65535&R|A<<16,R=65535&(x=g),A=x>>>16,T=65535&(k=s),B=k>>>16,A+=(x=_)>>>16,T+=65535&(k=w),B+=k>>>16,j=i,U=o,I=a,C=s=65535&(T+=(A+=(R+=65535&x)>>>16)>>>16)|(B+=T>>>16)<<16,N=u,P=h,D=l,L=f,q=c,W=d,F=p,K=g=65535&R|A<<16,Y=y,H=b,$=m,z=v,E%16==15)for(S=0;S<16;S++)k=O[S],R=65535&(x=M[S]),A=x>>>16,T=65535&k,B=k>>>16,k=O[(S+9)%16],R+=65535&(x=M[(S+9)%16]),A+=x>>>16,T+=65535&k,B+=k>>>16,w=O[(S+1)%16],R+=65535&(x=((_=M[(S+1)%16])>>>1|w<<31)^(_>>>8|w<<24)^(_>>>7|w<<25)),A+=x>>>16,T+=65535&(k=(w>>>1|_<<31)^(w>>>8|_<<24)^w>>>7),B+=k>>>16,w=O[(S+14)%16],A+=(x=((_=M[(S+14)%16])>>>19|w<<13)^(w>>>29|_<<3)^(_>>>6|w<<26))>>>16,T+=65535&(k=(w>>>19|_<<13)^(_>>>29|w<<3)^w>>>6),B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,O[S]=65535&T|B<<16,M[S]=65535&R|A<<16;R=65535&(x=z),A=x>>>16,T=65535&(k=L),B=k>>>16,k=e[0],A+=(x=t[0])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[0]=L=65535&T|B<<16,t[0]=z=65535&R|A<<16,R=65535&(x=q),A=x>>>16,T=65535&(k=j),B=k>>>16,k=e[1],A+=(x=t[1])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[1]=j=65535&T|B<<16,t[1]=q=65535&R|A<<16,R=65535&(x=W),A=x>>>16,T=65535&(k=U),B=k>>>16,k=e[2],A+=(x=t[2])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[2]=U=65535&T|B<<16,t[2]=W=65535&R|A<<16,R=65535&(x=F),A=x>>>16,T=65535&(k=I),B=k>>>16,k=e[3],A+=(x=t[3])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[3]=I=65535&T|B<<16,t[3]=F=65535&R|A<<16,R=65535&(x=K),A=x>>>16,T=65535&(k=C),B=k>>>16,k=e[4],A+=(x=t[4])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[4]=C=65535&T|B<<16,t[4]=K=65535&R|A<<16,R=65535&(x=Y),A=x>>>16,T=65535&(k=N),B=k>>>16,k=e[5],A+=(x=t[5])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[5]=N=65535&T|B<<16,t[5]=Y=65535&R|A<<16,R=65535&(x=H),A=x>>>16,T=65535&(k=P),B=k>>>16,k=e[6],A+=(x=t[6])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[6]=P=65535&T|B<<16,t[6]=H=65535&R|A<<16,R=65535&(x=$),A=x>>>16,T=65535&(k=D),B=k>>>16,k=e[7],A+=(x=t[7])>>>16,T+=65535&k,B+=k>>>16,B+=(T+=(A+=(R+=65535&x)>>>16)>>>16)>>>16,e[7]=D=65535&T|B<<16,t[7]=$=65535&R|A<<16,V+=128,n-=128}return n}function X(e,t,r){var n,i=new Int32Array(8),o=new Int32Array(8),a=new Uint8Array(256),s=r;for(i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225,o[0]=4089235720,o[1]=2227873595,o[2]=4271175723,o[3]=1595750129,o[4]=2917565137,o[5]=725511199,o[6]=4215389547,o[7]=327033209,J(i,o,t,r),r%=128,n=0;n=0;--i)Q(e,t,n=r[i/8|0]>>(7&i)&1),Z(t,e),Z(e,e),Q(e,t,n)}function re(e,r){var n=[t(),t(),t(),t()];B(n[0],l),B(n[1],f),B(n[2],a),D(n[3],l,f),te(e,n,r)}function ne(e,n,i){var o,a=new Uint8Array(64),s=[t(),t(),t(),t()];for(i||r(n,32),X(a,n,32),a[0]&=248,a[31]&=127,a[31]|=64,re(s,a),ee(e,s),o=0;o<32;o++)n[o+32]=e[o];return 0}var ie=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function oe(e,t){var r,n,i,o;for(n=63;n>=32;--n){for(r=0,i=n-32,o=n-12;i>4)*ie[i],r=t[i]>>8,t[i]&=255;for(i=0;i<32;i++)t[i]-=r*ie[i];for(n=0;n<32;n++)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function ae(e){var t,r=new Float64Array(64);for(t=0;t<64;t++)r[t]=e[t];for(t=0;t<64;t++)e[t]=0;oe(e,r)}function se(e,r,n,i){var o,a,s=new Uint8Array(64),u=new Uint8Array(64),h=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];X(s,i,32),s[0]&=248,s[31]&=127,s[31]|=64;var c=n+64;for(o=0;o>7&&P(e[0],o,e[0]),D(e[3],e[0],e[1]),0)}(d,i))return-1;for(s=0;s=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(ce);return ne(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(pe(e),e.length!==ce)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),r=0;re.replace("'",""),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.derivePath=e.isValidPath=e.getPublicKey=e.getMasterKeyFromSeed=void 0;const t=Ts,r=Bs.exports,n=Os;e.getMasterKeyFromSeed=e=>{const r=t("sha512","ed25519 seed").update(X.from(e,"hex")).digest();return{key:r.slice(0,32),chainCode:r.slice(32)}};e.getPublicKey=(e,t=!0)=>{const n=r.sign.keyPair.fromSeed(e).secretKey.subarray(32),i=X.alloc(1,0);return t?X.concat([i,X.from(n)]):X.from(n)},e.isValidPath=e=>!!n.pathRegex.test(e)&&!e.split("/").slice(1).map(n.replaceDerive).some(isNaN),e.derivePath=(r,i,o=2147483648)=>{if(!e.isValidPath(r))throw new Error("Invalid derivation path");const{key:a,chainCode:s}=e.getMasterKeyFromSeed(i);return r.split("/").slice(1).map(n.replaceDerive).map((e=>parseInt(e,10))).reduce(((e,r)=>(({key:e,chainCode:r},n)=>{const i=X.allocUnsafe(4);i.writeUInt32BE(n,0);const o=X.concat([X.alloc(1,0),e,i]),a=t("sha512",r).update(o).digest();return{key:a.slice(0,32),chainCode:a.slice(32)}})(e,r+o)),{key:a,chainCode:s})}}(Ue);var Ms=t(Ue);let Ls=(e={})=>{let t,{sk:r,keepPrivate:n=!1,seed:i=null}=e;if(r)t=Us(r);else{let e=Ns(i);t=e.vk,r=e.sk}return{sign:e=>Ps(r,e),verify:(e,r)=>Ds(t,e,r),vk:t,sk:n?void 0:r}};function js(e=null){var t=null;return t=null==e?I.sign.keyPair():I.sign.keyPair.fromSeed(e),{sk:new Uint8Array(t.secretKey.slice(0,32)),vk:new Uint8Array(t.secretKey.slice(32,64))}}function Us(e){return Cs(Is(e)).vk}function Is(e){return js(O(e))}function Cs(e){return{vk:B(e.vk),sk:B(e.sk)}}function Ns(e=null){return Cs(js(e))}function Ps(e,t){var r=Is(e),n=M(r.sk,r.vk);return B(I.sign.detached(t,n))}function Ds(e,t,r){var n=O(e),i=O(r);try{return I.sign.detached.verify(t,i,n)}catch(e){return!1}}var zs=Object.freeze({__proto__:null,create_wallet:Ls,generate_keys:js,get_vk:Us,format_to_keys:Is,keys_to_format:Cs,new_wallet:Ns,new_wallet_bip39:function(e,t=0){return function(e,t=0){let r,n;void 0!==e?r=e:(n=C.exports.generateMnemonic(256),r=C.exports.mnemonicToSeedSync(n).toString("hex"));const i="m/44'/789'/"+t+"'/0'/0'",{key:o,chainCode:a}=Ms.derivePath(i,r,2147483648),s=o.toString("hex"),u=Ms.getPublicKey(o,!1).toString("hex");if(u!==Us(s))throw Error("Bip32 public key does not match with Lamden public key!");return{sk:s,vk:u,derivationIndex:t,seed:void 0!==e?null:r,mnemonic:void 0!==e?null:n}}(e,t)},sign:Ps,verify:Ds});class qs{constructor(){this._events={}}on(e,t){this._events[e]||(this._events[e]=[]),this._events[e].push(t)}removeListener(e,t){if(!this._events[e])throw new Error(`Can't remove a listener. Event "${e}" doesn't exits.`);this._events[e]=this._events[e].filter((e=>e!==t))}emit(e,t){if(!this._events[e])return;this._events[e].forEach((e=>{e(t)}))}}var Ws={exports:{}};!function(e,t){var r=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r)return r;throw new Error("unable to locate global object")}();e.exports=t=r.fetch,r.fetch&&(t.default=r.fetch.bind(r)),t.Headers=r.Headers,t.Request=r.Request,t.Response=r.Response}(Ws,Ws.exports);var Fs,Ks=Ws.exports,Ys={exports:{}};Fs=Ys,function(e){var t,r=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,n=Math.ceil,i=Math.floor,o="[BigNumber Error] ",a=o+"Number primitive has more than 15 significant digits: ",s=1e14,u=14,h=9007199254740991,l=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],f=1e7,c=1e9;function d(e){var t=0|e;return e>0||e===t?t:t-1}function p(e){for(var t,r,n=1,i=e.length,o=e[0]+"";nh^r?1:-1;for(s=(u=i.length)<(h=o.length)?u:h,a=0;ao[a]^r?1:-1;return u==h?0:u>h^r?1:-1}function y(e,t,r,n){if(er||e!==i(e))throw Error(o+(n||"Argument")+("number"==typeof e?er?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function b(e){var t=e.c.length-1;return d(e.e/u)==t&&e.c[t]%2!=0}function m(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function v(e,t,r){var n,i;if(t<0){for(i=r+".";++t;i+=r);e=i+e}else if(++t>(n=e.length)){for(i=r,t-=n;--t;i+=r);e+=i}else tN?g.c=g.e=null:e.e=10;f/=10,l++);return void(l>N?g.c=g.e=null:(g.e=l,g.c=[e]))}p=String(e)}else{if(!r.test(p=String(e)))return E(g,p,c);g.s=45==p.charCodeAt(0)?(p=p.slice(1),-1):1}(l=p.indexOf("."))>-1&&(p=p.replace(".","")),(f=p.search(/e/i))>0?(l<0&&(l=f),l+=+p.slice(f+1),p=p.substring(0,f)):l<0&&(l=p.length)}else{if(y(t,2,W.length,"Base"),10==t)return $(g=new F(e),L+g.e+1,j);if(p=String(e),c="number"==typeof e){if(0*e!=0)return E(g,p,c,t);if(g.s=1/e<0?(p=p.slice(1),-1):1,F.DEBUG&&p.replace(/^0\.0*|\./,"").length>15)throw Error(a+e)}else g.s=45===p.charCodeAt(0)?(p=p.slice(1),-1):1;for(n=W.slice(0,t),l=f=0,d=p.length;fl){l=d;continue}}else if(!s&&(p==p.toUpperCase()&&(p=p.toLowerCase())||p==p.toLowerCase()&&(p=p.toUpperCase()))){s=!0,f=-1,l=0;continue}return E(g,String(e),c,t)}c=!1,(l=(p=_(p,t,10,g.s)).indexOf("."))>-1?p=p.replace(".",""):l=p.length}for(f=0;48===p.charCodeAt(f);f++);for(d=p.length;48===p.charCodeAt(--d););if(p=p.slice(f,++d)){if(d-=f,c&&F.DEBUG&&d>15&&(e>h||e!==i(e)))throw Error(a+g.s*e);if((l=l-f-1)>N)g.c=g.e=null;else if(l=I)?m(u,a):v(u,a,"0");else if(o=(e=$(new F(e),t,r)).e,s=(u=p(e.c)).length,1==n||2==n&&(t<=o||o<=U)){for(;ss){if(--t>0)for(u+=".";t--;u+="0");}else if((t+=o-s)>0)for(o+1==s&&(u+=".");t--;u+="0");return e.s<0&&i?"-"+u:u}function Y(e,t){for(var r,n=1,i=new F(e[0]);n=10;i/=10,n++);return(r=n+r*u-1)>N?e.c=e.e=null:r=10;c/=10,a++);if((h=t-a)<0)h+=u,f=t,g=(d=y[p=0])/b[a-f-1]%10|0;else if((p=n((h+1)/u))>=y.length){if(!o)break e;for(;y.length<=p;y.push(0));d=g=0,a=1,f=(h%=u)-u+1}else{for(d=c=y[p],a=1;c>=10;c/=10,a++);g=(f=(h%=u)-u+a)<0?0:d/b[a-f-1]%10|0}if(o=o||t<0||null!=y[p+1]||(f<0?d:d%b[a-f-1]),o=r<4?(g||o)&&(0==r||r==(e.s<0?3:2)):g>5||5==g&&(4==r||o||6==r&&(h>0?f>0?d/b[a-f]:0:y[p-1])%10&1||r==(e.s<0?8:7)),t<1||!y[0])return y.length=0,o?(t-=e.e+1,y[0]=b[(u-t%u)%u],e.e=-t||0):y[0]=e.e=0,e;if(0==h?(y.length=p,c=1,p--):(y.length=p+1,c=b[u-h],y[p]=f>0?i(d/b[a-f]%b[f])*c:0),o)for(;;){if(0==p){for(h=1,f=y[0];f>=10;f/=10,h++);for(f=y[0]+=c,c=1;f>=10;f/=10,c++);h!=c&&(e.e++,y[0]==s&&(y[0]=1));break}if(y[p]+=c,y[p]!=s)break;y[p--]=0,c=1}for(h=y.length;0===y[--h];y.pop());}e.e>N?e.c=e.e=null:e.e=I?m(t,r):v(t,r,"0"),e.s<0?"-"+t:t)}return F.clone=e,F.ROUND_UP=0,F.ROUND_DOWN=1,F.ROUND_CEIL=2,F.ROUND_FLOOR=3,F.ROUND_HALF_UP=4,F.ROUND_HALF_DOWN=5,F.ROUND_HALF_EVEN=6,F.ROUND_HALF_CEIL=7,F.ROUND_HALF_FLOOR=8,F.EUCLID=9,F.config=F.set=function(e){var t,r;if(null!=e){if("object"!=typeof e)throw Error(o+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(y(r=e[t],0,c,t),L=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(y(r=e[t],0,8,t),j=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((r=e[t])&&r.pop?(y(r[0],-c,0,t),y(r[1],0,c,t),U=r[0],I=r[1]):(y(r,-c,c,t),U=-(I=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if((r=e[t])&&r.pop)y(r[0],-c,-1,t),y(r[1],1,c,t),C=r[0],N=r[1];else{if(y(r,-c,c,t),!r)throw Error(o+t+" cannot be zero: "+r);C=-(N=r<0?-r:r)}if(e.hasOwnProperty(t="CRYPTO")){if((r=e[t])!==!!r)throw Error(o+t+" not true or false: "+r);if(r){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw P=!r,Error(o+"crypto unavailable");P=r}else P=r}if(e.hasOwnProperty(t="MODULO_MODE")&&(y(r=e[t],0,9,t),D=r),e.hasOwnProperty(t="POW_PRECISION")&&(y(r=e[t],0,c,t),z=r),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(r=e[t]))throw Error(o+t+" not an object: "+r);q=r}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(r=e[t])||/^.$|[+-.\s]|(.).*\1/.test(r))throw Error(o+t+" invalid: "+r);W=r}}return{DECIMAL_PLACES:L,ROUNDING_MODE:j,EXPONENTIAL_AT:[U,I],RANGE:[C,N],CRYPTO:P,MODULO_MODE:D,POW_PRECISION:z,FORMAT:q,ALPHABET:W}},F.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!F.DEBUG)return!0;var t,r,n=e.c,a=e.e,h=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===h||-1===h)&&a>=-c&&a<=c&&a===i(a)){if(0===n[0]){if(0===a&&1===n.length)return!0;break e}if((t=(a+1)%u)<1&&(t+=u),String(n[0]).length==t){for(t=0;t=s||r!==i(r))break e;if(0!==r)return!0}}}else if(null===n&&null===a&&(null===h||1===h||-1===h))return!0;throw Error(o+"Invalid BigNumber: "+e)},F.maximum=F.max=function(){return Y(arguments,O.lt)},F.minimum=F.min=function(){return Y(arguments,O.gt)},F.random=(S=9007199254740992,k=Math.random()*S&2097151?function(){return i(Math.random()*S)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,r,a,s,h,f=0,d=[],p=new F(M);if(null==e?e=L:y(e,0,c),s=n(e/u),P)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(s*=2));f>>11))>=9e15?(r=crypto.getRandomValues(new Uint32Array(2)),t[f]=r[0],t[f+1]=r[1]):(d.push(h%1e14),f+=2);f=s/2}else{if(!crypto.randomBytes)throw P=!1,Error(o+"crypto unavailable");for(t=crypto.randomBytes(s*=7);f=9e15?crypto.randomBytes(7).copy(t,f):(d.push(h%1e14),f+=7);f=s/7}if(!P)for(;f=10;h/=10,f++);fr-1&&(null==a[i+1]&&(a[i+1]=0),a[i+1]+=a[i]/r|0,a[i]%=r)}return a.reverse()}return function(r,n,i,o,a){var s,u,h,l,f,c,d,g,y=r.indexOf("."),b=L,m=j;for(y>=0&&(l=z,z=0,r=r.replace(".",""),c=(g=new F(n)).pow(r.length-y),z=l,g.c=t(v(p(c.c),c.e,"0"),10,i,e),g.e=g.c.length),h=l=(d=t(r,n,i,a?(s=W,e):(s=e,W))).length;0==d[--l];d.pop());if(!d[0])return s.charAt(0);if(y<0?--h:(c.c=d,c.e=h,c.s=o,d=(c=w(c,g,b,m,i)).c,f=c.r,h=c.e),y=d[u=h+b+1],l=i/2,f=f||u<0||null!=d[u+1],f=m<4?(null!=y||f)&&(0==m||m==(c.s<0?3:2)):y>l||y==l&&(4==m||f||6==m&&1&d[u-1]||m==(c.s<0?8:7)),u<1||!d[0])r=f?v(s.charAt(1),-b,s.charAt(0)):s.charAt(0);else{if(d.length=u,f)for(--i;++d[--u]>i;)d[u]=0,u||(++h,d=[1].concat(d));for(l=d.length;!d[--l];);for(y=0,r="";y<=l;r+=s.charAt(d[y++]));r=v(r,h,s.charAt(0))}return r}}(),w=function(){function e(e,t,r){var n,i,o,a,s=0,u=e.length,h=t%f,l=t/f|0;for(e=e.slice();u--;)s=((i=h*(o=e[u]%f)+(n=l*o+(a=e[u]/f|0)*h)%f*f+s)/r|0)+(n/f|0)+l*a,e[u]=i%r;return s&&(e=[s].concat(e)),e}function t(e,t,r,n){var i,o;if(r!=n)o=r>n?1:-1;else for(i=o=0;it[i]?1:-1;break}return o}function r(e,t,r,n){for(var i=0;r--;)e[r]-=i,i=e[r]1;e.splice(0,1));}return function(n,o,a,h,l){var f,c,p,g,y,b,m,v,w,_,E,S,k,x,R,A,T,B=n.s==o.s?1:-1,O=n.c,M=o.c;if(!(O&&O[0]&&M&&M[0]))return new F(n.s&&o.s&&(O?!M||O[0]!=M[0]:M)?O&&0==O[0]||!M?0*B:B/0:NaN);for(w=(v=new F(B)).c=[],B=a+(c=n.e-o.e)+1,l||(l=s,c=d(n.e/u)-d(o.e/u),B=B/u|0),p=0;M[p]==(O[p]||0);p++);if(M[p]>(O[p]||0)&&c--,B<0)w.push(1),g=!0;else{for(x=O.length,A=M.length,p=0,B+=2,(y=i(l/(M[0]+1)))>1&&(M=e(M,y,l),O=e(O,y,l),A=M.length,x=O.length),k=A,E=(_=O.slice(0,A)).length;E=l/2&&R++;do{if(y=0,(f=t(M,_,A,E))<0){if(S=_[0],A!=E&&(S=S*l+(_[1]||0)),(y=i(S/R))>1)for(y>=l&&(y=l-1),m=(b=e(M,y,l)).length,E=_.length;1==t(b,_,m,E);)y--,r(b,A=10;B/=10,p++);$(v,a+(v.e=p+c*u-1)+1,h,g)}else v.e=c,v.r=+g;return v}}(),x=/^(-?)0([xbo])(?=\w[\w.]*$)/i,R=/^([^.]+)\.$/,A=/^\.([^.]+)$/,T=/^-?(Infinity|NaN)$/,B=/^\s*\+(?=[\w.])|^\s+|\s+$/g,E=function(e,t,r,n){var i,a=r?t:t.replace(B,"");if(T.test(a))e.s=isNaN(a)?null:a<0?-1:1;else{if(!r&&(a=a.replace(x,(function(e,t,r){return i="x"==(r=r.toLowerCase())?16:"b"==r?2:8,n&&n!=i?e:t})),n&&(i=n,a=a.replace(R,"$1").replace(A,"0.$1")),t!=a))return new F(a,i);if(F.DEBUG)throw Error(o+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},O.absoluteValue=O.abs=function(){var e=new F(this);return e.s<0&&(e.s=1),e},O.comparedTo=function(e,t){return g(this,new F(e,t))},O.decimalPlaces=O.dp=function(e,t){var r,n,i,o=this;if(null!=e)return y(e,0,c),null==t?t=j:y(t,0,8),$(new F(o),e+o.e+1,t);if(!(r=o.c))return null;if(n=((i=r.length-1)-d(this.e/u))*u,i=r[i])for(;i%10==0;i/=10,n--);return n<0&&(n=0),n},O.dividedBy=O.div=function(e,t){return w(this,new F(e,t),L,j)},O.dividedToIntegerBy=O.idiv=function(e,t){return w(this,new F(e,t),0,1)},O.exponentiatedBy=O.pow=function(e,t){var r,a,s,h,l,f,c,d,p=this;if((e=new F(e)).c&&!e.isInteger())throw Error(o+"Exponent not an integer: "+V(e));if(null!=t&&(t=new F(t)),l=e.e>14,!p.c||!p.c[0]||1==p.c[0]&&!p.e&&1==p.c.length||!e.c||!e.c[0])return d=new F(Math.pow(+V(p),l?2-b(e):+V(e))),t?d.mod(t):d;if(f=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new F(NaN);(a=!f&&p.isInteger()&&t.isInteger())&&(p=p.mod(t))}else{if(e.e>9&&(p.e>0||p.e<-1||(0==p.e?p.c[0]>1||l&&p.c[1]>=24e7:p.c[0]<8e13||l&&p.c[0]<=9999975e7)))return h=p.s<0&&b(e)?-0:0,p.e>-1&&(h=1/h),new F(f?1/h:h);z&&(h=n(z/u+2))}for(l?(r=new F(.5),f&&(e.s=1),c=b(e)):c=(s=Math.abs(+V(e)))%2,d=new F(M);;){if(c){if(!(d=d.times(p)).c)break;h?d.c.length>h&&(d.c.length=h):a&&(d=d.mod(t))}if(s){if(0===(s=i(s/2)))break;c=s%2}else if($(e=e.times(r),e.e+1,1),e.e>14)c=b(e);else{if(0==(s=+V(e)))break;c=s%2}p=p.times(p),h?p.c&&p.c.length>h&&(p.c.length=h):a&&(p=p.mod(t))}return a?d:(f&&(d=M.div(d)),t?d.mod(t):h?$(d,z,j,void 0):d)},O.integerValue=function(e){var t=new F(this);return null==e?e=j:y(e,0,8),$(t,t.e+1,e)},O.isEqualTo=O.eq=function(e,t){return 0===g(this,new F(e,t))},O.isFinite=function(){return!!this.c},O.isGreaterThan=O.gt=function(e,t){return g(this,new F(e,t))>0},O.isGreaterThanOrEqualTo=O.gte=function(e,t){return 1===(t=g(this,new F(e,t)))||0===t},O.isInteger=function(){return!!this.c&&d(this.e/u)>this.c.length-2},O.isLessThan=O.lt=function(e,t){return g(this,new F(e,t))<0},O.isLessThanOrEqualTo=O.lte=function(e,t){return-1===(t=g(this,new F(e,t)))||0===t},O.isNaN=function(){return!this.s},O.isNegative=function(){return this.s<0},O.isPositive=function(){return this.s>0},O.isZero=function(){return!!this.c&&0==this.c[0]},O.minus=function(e,t){var r,n,i,o,a=this,h=a.s;if(t=(e=new F(e,t)).s,!h||!t)return new F(NaN);if(h!=t)return e.s=-t,a.plus(e);var l=a.e/u,f=e.e/u,c=a.c,p=e.c;if(!l||!f){if(!c||!p)return c?(e.s=-t,e):new F(p?a:NaN);if(!c[0]||!p[0])return p[0]?(e.s=-t,e):new F(c[0]?a:3==j?-0:0)}if(l=d(l),f=d(f),c=c.slice(),h=l-f){for((o=h<0)?(h=-h,i=c):(f=l,i=p),i.reverse(),t=h;t--;i.push(0));i.reverse()}else for(n=(o=(h=c.length)<(t=p.length))?h:t,h=t=0;t0)for(;t--;c[r++]=0);for(t=s-1;n>h;){if(c[--n]=0;){for(r=0,y=S[i]%w,b=S[i]/w|0,o=i+(a=l);o>i;)r=((c=y*(c=E[--a]%w)+(h=b*c+(p=E[a]/w|0)*y)%w*w+m[o]+r)/v|0)+(h/w|0)+b*p,m[o--]=c%v;m[o]=r}return r?++n:m.splice(0,1),H(e,m,n)},O.negated=function(){var e=new F(this);return e.s=-e.s||null,e},O.plus=function(e,t){var r,n=this,i=n.s;if(t=(e=new F(e,t)).s,!i||!t)return new F(NaN);if(i!=t)return e.s=-t,n.minus(e);var o=n.e/u,a=e.e/u,h=n.c,l=e.c;if(!o||!a){if(!h||!l)return new F(i/0);if(!h[0]||!l[0])return l[0]?e:new F(h[0]?n:0*i)}if(o=d(o),a=d(a),h=h.slice(),i=o-a){for(i>0?(a=o,r=l):(i=-i,r=h),r.reverse();i--;r.push(0));r.reverse()}for((i=h.length)-(t=l.length)<0&&(r=l,l=h,h=r,t=i),i=0;t;)i=(h[--t]=h[t]+l[t]+i)/s|0,h[t]=s===h[t]?0:h[t]%s;return i&&(h=[i].concat(h),++a),H(e,h,a)},O.precision=O.sd=function(e,t){var r,n,i,o=this;if(null!=e&&e!==!!e)return y(e,1,c),null==t?t=j:y(t,0,8),$(new F(o),e,t);if(!(r=o.c))return null;if(n=(i=r.length-1)*u+1,i=r[i]){for(;i%10==0;i/=10,n--);for(i=r[0];i>=10;i/=10,n++);}return e&&o.e+1>n&&(n=o.e+1),n},O.shiftedBy=function(e){return y(e,-9007199254740991,h),this.times("1e"+e)},O.squareRoot=O.sqrt=function(){var e,t,r,n,i,o=this,a=o.c,s=o.s,u=o.e,h=L+4,l=new F("0.5");if(1!==s||!a||!a[0])return new F(!s||s<0&&(!a||a[0])?NaN:a?o:1/0);if(0==(s=Math.sqrt(+V(o)))||s==1/0?(((t=p(a)).length+u)%2==0&&(t+="0"),s=Math.sqrt(+t),u=d((u+1)/2)-(u<0||u%2),r=new F(t=s==1/0?"1e"+u:(t=s.toExponential()).slice(0,t.indexOf("e")+1)+u)):r=new F(s+""),r.c[0])for((s=(u=r.e)+h)<3&&(s=0);;)if(i=r,r=l.times(i.plus(w(o,i,h,1))),p(i.c).slice(0,s)===(t=p(r.c)).slice(0,s)){if(r.e0&&g>0){for(a=g%u||u,f=p.substr(0,a);a0&&(f+=l+p.slice(a)),d&&(f="-"+f)}n=c?f+(r.decimalSeparator||"")+((h=+r.fractionGroupSize)?c.replace(new RegExp("\\d{"+h+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):c):f}return(r.prefix||"")+n+(r.suffix||"")},O.toFraction=function(e){var t,r,n,i,a,s,h,f,c,d,g,y,b=this,m=b.c;if(null!=e&&(!(h=new F(e)).isInteger()&&(h.c||1!==h.s)||h.lt(M)))throw Error(o+"Argument "+(h.isInteger()?"out of range: ":"not an integer: ")+V(h));if(!m)return new F(b);for(t=new F(M),c=r=new F(M),n=f=new F(M),y=p(m),a=t.e=y.length-b.e-1,t.c[0]=l[(s=a%u)<0?u+s:s],e=!e||h.comparedTo(t)>0?a>0?t:c:h,s=N,N=1/0,h=new F(y),f.c[0]=0;d=w(h,t,0,1),1!=(i=r.plus(d.times(n))).comparedTo(e);)r=n,n=i,c=f.plus(d.times(i=c)),f=i,t=h.minus(d.times(i=t)),h=i;return i=w(e.minus(r),n,0,1),f=f.plus(i.times(c)),r=r.plus(i.times(n)),f.s=c.s=b.s,g=w(c,n,a*=2,j).minus(b).abs().comparedTo(w(f,r,a,j).minus(b).abs())<1?[c,n]:[f,r],N=s,g},O.toNumber=function(){return+V(this)},O.toPrecision=function(e,t){return null!=e&&y(e,1,c),K(this,e,t,2)},O.toString=function(e){var t,r=this,n=r.s,i=r.e;return null===i?n?(t="Infinity",n<0&&(t="-"+t)):t="NaN":(null==e?t=i<=U||i>=I?m(p(r.c),i):v(p(r.c),i,"0"):10===e?t=v(p((r=$(new F(r),L+i+1,j)).c),r.e,"0"):(y(e,2,W.length,"Base"),t=_(v(p(r.c),i,"0"),10,e,n,!0)),n<0&&r.c[0]&&(t="-"+t)),t},O.valueOf=O.toJSON=function(){return V(this)},O._isBigNumber=!0,null!=t&&F.set(t),F}(),t.default=t.BigNumber=t,Fs.exports?Fs.exports=t:(e||(e="undefined"!=typeof self&&self?self:window),e.BigNumber=t)}(e);var Hs=Ys.exports;function $s(e,t){const r=t=>{throw new Error(`Error encoding ${t} to ${e}`)},n=e=>{if(Math.floor(e)===e)return 0;try{return e.toString().split(".")[1].length}catch(e){return 0}},i=e=>e&&"object"==typeof e&&e.constructor===Array,o=e=>e&&"object"==typeof e&&e.constructor===Object,a=e=>e instanceof Date,s=e=>!i(e)&&!isNaN(l(e).toNumber()),u=e=>!!s(e)&&0!==n(e),h=e=>(s(e)||r(e),Hs.isBigNumber(e)||(e=new Hs(e)),{__fixed__:e.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm,"$1$2")}),l=e=>(Hs.isBigNumber(e)||(e=new Hs(e)),e),f=e=>(e=>"boolean"==typeof e)(e)?e:"true"===e||1===e||"false"!==e&&0!==e&&void r(e),c=e=>(e=>"string"==typeof e||e instanceof String)(e)?e:a(e)?e.toISOString():JSON.stringify(e),d=e=>(e=a(e)?e:new Date(e),a(e)||r(e),{__time__:[e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()]}),p=e=>{const t=a(e)?e.getTime():new Date(e).getTime(),r=parseInt(t/1e3/60/60/24);return{__delta__:[r,(t-24*r*60*60*1e3)/1e3]}},g=e=>{if(i(e))return b(e);try{e=JSON.parse(e)}catch(t){r(e)}if(i(e))return b(e);r(e)},y=e=>{if(o(e))return b(e);try{e=JSON.parse(e)}catch(t){r(e)}if(o(e))return b(e);r(e)};function b(e){let t=JSON.stringify(e,((e,t)=>"datetime"===e||"datetime.datetime"===e?$s("datetime.datetime",t):"timedelta"===e||"datetime.timedelta"===e?$s("datetime.timedelta",t):"__fixed__"!==e&&u(t)?h(t):t));return JSON.parse(t,((e,t)=>{const r=e=>1===Object.keys(e).length&&["datetime.datetime","datetime","datetime.timedelta","timedelta"].filter((t=>t===Object.keys(e)[0])).length>0;return t.constructor===Array&&t.map((e=>1===Object.keys(e).length&&r(t)?e[Object.keys(e)[0]]:e)),t.constructor===Object&&1===Object.keys(t).length&&r(t)?t[Object.keys(t)[0]]:t}))}const m={str:c,string:c,float:h,int:e=>{if(s(e))return parseInt(e);r(e)},bool:f,boolean:f,dict:y,list:g,Any:()=>t,"datetime.timedelta":p,"datetime.datetime":d,timedelta:p,datetime:d,number:e=>(s(e)||r(e),u(e)?(Hs.isBigNumber(e)||(e=new Hs(e)),{__fixed__:e.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm,"$1$2")}):(e=>!!s(e)&&0===n(e))(e)?parseInt(e):void 0),object:e=>{try{return g(e)}catch(t){return y(e)}},bigNumber:l};if(Object.keys(m).includes(e))return m[e](t);throw new Error(`Error: ${e} is not a valid encoder type.`)}Hs.config({RANGE:[-30,30],EXPONENTIAL_AT:1e9}),Hs.set({DECIMAL_PLACES:30,ROUNDING_MODE:Hs.ROUND_DOWN}),$s.BigNumber=Hs;const{validateTypes:Vs}=o;class Gs{constructor(e){if(!Vs.isObjectWithKeys(e))throw new Error("Expected Object and got Type: "+typeof e);if(!Vs.isArrayWithValues(e.hosts))throw new Error("HOSTS Required (Type: Array)");this.hosts=this.validateHosts(e.hosts)}vaidateProtocol(e){if(["https://","http://"].map((t=>e.includes(t))).includes(!0))return e;throw new Error("Host String must include http:// or https://")}validateHosts(e){return e.map((e=>this.vaidateProtocol(e.toLowerCase())))}get host(){return this.hosts[Math.floor(Math.random()*this.hosts.length)]}get url(){return this.host}send(e,t,r,n,i){let o="";Object.keys(r).includes("parms")&&(o=this.createParms(r.parms));let a={};if("POST"===e){let t={"Content-Type":"application/json"};a.method=e,a.headers=t,a.body=r}return Ks(`${n||this.url}${t}${o}`,a).then((async e=>{if(200===e.status){let t=await e.json();return i(t,void 0),t}{let t=!!Vs.isStringWithValue(e.statusText)&&e.statusText;return i(void 0,t),t}})).catch((e=>i(void 0,e.toString())))}createParms(e){if(0===Object.keys(e).length)return"";let t="?";return Object.keys(e).forEach((r=>{t=`${t}${r}=${e[r]}&`})),t.slice(0,-1)}async getContractInfo(e){const t=e=>{try{if(e.name)return e}catch(e){}return null};let r=`/contracts/${e}`;return this.send("GET",r,{},void 0,((e,r)=>t(e))).then((e=>t(e)))}async getVariable(e,t,r=""){let n={};Vs.isStringWithValue(r)&&(n.key=r);let i=`/contracts/${e}/${t}/`;const o=e=>{try{if(e.value)return e.value}catch(e){}return null};return this.send("GET",i,{parms:n},void 0,((e,t)=>o(e))).then((e=>o(e)))}async getContractMethods(e){const t=e=>{try{if(e.methods)return e.methods}catch(e){}return[]};let r=`/contracts/${e}/methods`;return this.send("GET",r,{},void 0,((e,r)=>t(e))).then((e=>t(e)))}async getContractVariables(e){const t=e=>{try{if(e.variables)return e}catch(e){}return{}};let r=`/contracts/${e}/variables`;return this.send("GET",r,{},void 0,((e,r)=>t(e))).then((e=>t(e)))}async pingServer(){const e=e=>{try{if(e.status)return!0}catch(e){}return!1};let t=await this.send("GET","/ping",{},void 0,((t,r)=>e(t)));return e(t)}async getCurrencyBalance(e){let t=await this.getVariable("currency","balances",e);return t?t.__fixed__?$s("bigNumber",t.__fixed__):$s("bigNumber",t.toString()):$s("bigNumber",0)}async contractExists(e){const t=e=>{try{if(e.name)return!0}catch(e){}return!1};let r=`/contracts/${e}`;return this.send("GET",r,{},void 0,((e,r)=>t(e))).then((e=>t(e)))}async sendTransaction(e,t,r){return this.send("POST","/",JSON.stringify(e),t,((e,t)=>t?r?void r(void 0,t):t:r?void r(e,void 0):e))}async getNonce(e,t){if(!Vs.isStringHex(e))return`${e} is not a hex string.`;let r=`/nonce/${e}`,n=this.host;return this.send("GET",r,{},n,((r,i)=>i?t?void t(void 0,`Unable to get nonce for ${e} on network ${n}`):`Unable to get nonce for ${e} on network ${n}`:(r.masternode=n,t?void t(r,void 0):r)))}checkTransaction(e,t){const r={hash:e};return this.send("GET","/tx",{parms:r},void 0,((e,r)=>r?t?void t(void 0,r):r:t?void t(e,void 0):e))}}const{validateTypes:Js}=o;class Xs{constructor(e){if(!Js.isObjectWithKeys(e))throw new Error("Expected Network Info Object and got Type: "+typeof e);if(!Js.isArrayWithValues(e.hosts))throw new Error("HOSTS Required (Type: Array)");this.type=Js.isStringWithValue(e.type)?e.type.toLowerCase():"custom",this.events=new qs,this.hosts=this.validateHosts(e.hosts),this.currencySymbol=Js.isStringWithValue(e.currencySymbol)?e.currencySymbol:"TAU",this.name=Js.isStringWithValue(e.name)?e.name:"lamden network",this.lamden=!!Js.isBoolean(e.lamden)&&e.lamden,this.blockExplorer=Js.isStringWithValue(e.blockExplorer)?e.blockExplorer:void 0,this.online=!1;try{this.API=new Gs(e)}catch(e){throw new Error(e)}}vaidateProtocol(e){if(["https://","http://"].map((t=>e.includes(t))).includes(!0))return e;throw new Error("Host String must include http:// or https://")}validateHosts(e){return e.map((e=>this.vaidateProtocol(e.toLowerCase())))}async ping(e){return this.online=await this.API.pingServer(),this.events.emit("online",this.online),Js.isFunction(e)&&e(this.online),this.online}get host(){return this.hosts[Math.floor(Math.random()*this.hosts.length)]}get url(){return this.host}getNetworkInfo(){return{name:this.name,lamden:this.lamden,type:this.type,hosts:this.hosts,url:this.url,online:this.online}}}const{validateTypes:Zs}=o;class Qs extends Xs{constructor(e,t,r){if(Zs.isSpecificClass(e,"Network")?super(e.getNetworkInfo()):super(e),!Zs.isObjectWithKeys(t))throw new Error("txInfo object not found");if(!Zs.isStringHex(t.senderVk))throw new Error("Sender Public Key Required (Type: Hex String)");if(!Zs.isStringWithValue(t.contractName))throw new Error("Contract Name Required (Type: String)");if(!Zs.isStringWithValue(t.methodName))throw new Error("Method Required (Type: String)");if(!Zs.isInteger(t.stampLimit))throw new Error("Stamps Limit Required (Type: Integer)");if(this.uid=Zs.isStringWithValue(t.uid)?t.uid:void 0,this.sender=t.senderVk,this.contract=t.contractName,this.method=t.methodName,this.kwargs={},Zs.isObject(t.kwargs)&&(this.kwargs=t.kwargs),this.stampLimit=t.stampLimit,void 0!==t.nonce){if(!Zs.isInteger(t.nonce))throw new Error(`arg[6] Nonce is required to be an Integer, type ${typeof t.none} was given`);this.nonce=t.nonce}if(void 0!==t.processor){if(!Zs.isStringWithValue(t.processor))throw new Error(`arg[7] Processor is required to be a String, type ${typeof t.processor} was given`);this.processor=t.processor}this.signature,this.transactionSigned=!1,this.nonceResult={},this.txSendResult={errors:[]},this.txBlockResult={},this.txHash,this.txCheckResult={},this.txCheckAttempts=0,this.txCheckLimit=10,r&&(r.uid&&(this.uid=r.uid),Zs.isObjectWithKeys(r.txSendResult)&&(this.txSendResult=r.txSendResult),Zs.isObjectWithKeys(r.nonceResult)&&(this.nonceResult=r.nonceResult,Zs.isInteger(this.nonceResult.nonce)&&(this.nonce=this.nonceResult.nonce),Zs.isStringWithValue(this.nonceResult.processor)&&(this.processor=this.nonceResult.processor)),Zs.isObjectWithKeys(r.txSendResult)&&(this.txSendResult=r.txSendResult,this.txSendResult.hash&&(this.txHash=this.txSendResult.hash)),Zs.isObjectWithKeys(r.txBlockResult)&&(this.txBlockResult=r.txBlockResult),Zs.isObjectWithKeys(r.resultInfo)&&(this.resultInfo=r.resultInfo)),this.makePayload()}makePayload(){this.payload={contract:this.contract,function:this.method,kwargs:this.kwargs,nonce:this.nonce,processor:this.processor,sender:this.sender,stamps_supplied:this.stampLimit},this.sortedPayload=this.sortObject(this.payload)}makeTransaction(){this.tx={metadata:{signature:this.signature,timestamp:parseInt(+new Date/1e3)},payload:this.sortedPayload.orderedObj}}verifySignature(){if(!this.transactionSigned)throw new Error("Transaction has not be been signed. Use the sign() method first.");const e=Buffer.from(this.sortedPayload.json),t=new Uint8Array(e);return Ds(this.sender,t,this.signature)}sign(e,t){const r=Buffer.from(this.sortedPayload.json),n=new Uint8Array(r);this.signature=t?t.sign(n):Ps(e,n),this.transactionSigned=!0}sortObject(e){const t=(e=>{const t=e=>Object.prototype.toString.call(e),r=e=>"[object Object]"===t(e),n=e=>(Object.keys(e).forEach((i=>{var o;o=e[i],"[object Array]"===t(o)&&(e[i]=e[i].map((e=>r(e)?n(e):e))),r(e[i])&&(e[i]=n(e[i]))})),(e=>{const t={};return Object.keys(e).sort().forEach((r=>t[r]=e[r])),t})(e));if(!r(e))throw new TypeError("Not a valid Object");try{e=JSON.parse(JSON.stringify(e))}catch(e){throw new TypeError("Not a valid JSON Object")}return n(e)})(e);return{orderedObj:t,json:JSON.stringify(t)}}async getNonce(e){let t=(new Date).toUTCString();if(this.nonceResult=await this.API.getNonce(this.sender),void 0===this.nonceResult.nonce)throw new Error(this.nonceResult);return this.nonceResult.timestamp=t,this.nonce=this.nonceResult.nonce,this.processor=this.nonceResult.processor,this.nonceMasternode=this.nonceResult.masternode,this.makePayload(),e?e(this.nonceResult):this.nonceResult}async send(e,t,r){if(!Zs.isStringWithValue(e)&&!this.transactionSigned)throw new Error("Transation Not Signed: Private key needed or call sign() first");let n=(new Date).toUTCString();try{!isNaN(this.nonce)&&Zs.isStringWithValue(this.processor)||await this.getNonce(),Zs.isStringWithValue(e)&&this.sign(e),this.makeTransaction();let t=r;!t&&this.nonceMasternode&&(t=this.nonceMasternode);let n=await this.API.sendTransaction(this.tx,t);!n||Zs.isStringWithValue(n)?this.txSendResult.errors=[n||"Unknown Transaction Error"]:n.error?this.txSendResult.errors=[n.error]:this.txSendResult=n}catch(e){this.txSendResult.errors=[e.message]}return this.txSendResult.timestamp=n,this.handleMasterNodeResponse(this.txSendResult,t)}checkForTransactionResult(e){return new Promise((t=>{let r=setTimeout(async function n(){this.txCheckAttempts=this.txCheckAttempts+1;let i=await this.API.checkTransaction(this.txHash),o=!1,a=(new Date).toUTCString();"string"!=typeof i&&i?i.error?"Transaction not found."===i.error?this.txCheckAttempts0&&(Zs.isArray(this.txCheckResult.errors)||(this.txCheckResult.errors=[]),this.txCheckResult.errors.push("This transaction returned a non-zero status code")),this.txCheckResult.timestamp=a,clearTimeout(r),t(this.handleMasterNodeResponse(this.txCheckResult,e)))}.bind(this),1e3)}))}handleMasterNodeResponse(e,t){return Zs.isStringWithValue(e.hash)&&Zs.isStringWithValue(e.success)?(this.txHash=e.hash,this.setPendingBlockInfo()):(this.setBlockResultInfo(e),this.txBlockResult=e),this.events.emit("response",e,this.resultInfo.subtitle),Zs.isFunction(t)&&t(e),e}setPendingBlockInfo(){return this.resultInfo={title:"Transaction Pending",subtitle:"Your transaction was submitted and is being processed",message:`Tx Hash: ${this.txHash}`,type:"success"},this.resultInfo}setBlockResultInfo(e){let t=!1,r="returned an error and ",n=Zs.isNumber(e.status)?e.status:void 0,i=e.stampsUsed||e.stamps_used||0,o="";return Zs.isArrayWithValues(e.errors)&&(t=!0,o=`This transaction returned ${e.errors.length} errors.`,e.result&&e.result.includes("AssertionError")&&e.errors.push(e.result)),n&&t&&(r=`returned status code ${n} and `),this.resultInfo={title:"Transaction "+(t?"Failed":"Successful"),subtitle:`Your transaction ${t?`${r} `:""}used ${i} stamps`,message:o,type:""+(t?"error":"success"),errorInfo:t?e.errors:void 0,returnResult:e.result||"",stampsUsed:i,statusCode:n},this.resultInfo}getResultInfo(){return this.resultInfo}getTxInfo(){return{senderVk:this.sender,contractName:this.contract,methodName:this.method,kwargs:this.kwargs,stampLimit:this.stampLimit}}getAllInfo(){return{uid:this.uid,txHash:this.txHash,signed:this.transactionSigned,tx:this.tx,signature:this.signature,networkInfo:this.getNetworkInfo(),txInfo:this.getTxInfo(),txSendResult:this.txSendResult,txBlockResult:this.txBlockResult,resultInfo:this.getResultInfo(),nonceResult:this.nonceResult}}}const{validateTypes:eu}=o;const{validateTypes:tu,assertTypes:ru}=o;globalThis.Buffer=Ne.Buffer;var nu={TransactionBuilder:Qs,TransactionBatcher:class extends Xs{constructor(e){eu.isSpecificClass(e,"Network")?super(e.getNetworkInfo()):super(e),this.txBatches={},this.overflow=[],this.nonceResults={},this.running=!1}addTransaction(e){this.running?this.overflow.push(e):(this.validateTransactionInfo(e),this.txBatches[e.senderVk]||(this.txBatches[e.senderVk]=[]),this.txBatches[e.senderVk].push(e))}addTransactionList(e){e.forEach((e=>this.addTransaction(e)))}processOverflow(){const e=this.overflow;this.overflow=[],e.forEach((e=>this.addTransaction(e)))}hasTransactions(){let e=Object.keys(this.txBatches).map((e=>this.txBatches[e].length));return e.filter((e=>0===e)),e.length>0}validateTransactionInfo(e){try{new Qs(e)}catch(e){return!1}return!0}async getStartingNonce(e,t){let r=(new Date).toUTCString(),n=await this.API.getNonce(e);if(void 0===n.nonce)throw new Error(n);return n.timestamp=r,this.nonceResults[e]=n,t&&t(n),n}async sendAllBatches(e){if(this.running)return;let t=[];this.running=!0,await Promise.all(Object.keys(this.txBatches).map((r=>{const n=this.txBatches[r].splice(0,15);return n.length<=15&&delete this.txBatches[r],new Promise((async i=>{if(0===n.length&&i(),!e[r])throw new Error(`Cannot sign batch for ${r}. No signing key provided.`);let o=await this.getStartingNonce(r),a=this.setBatchNonces(o,n);this.signBatch(a,e[r]),this.sendBatch(a).then((e=>{t=[...t,...e],i()}))}))})));try{return Promise.all(t)}catch(e){}finally{this.running=!1,this.processOverflow()}}setBatchNonces(e,t){return t.map(((t,r)=>(t.nonce=e.nonce+r,t.processor=e.processor,new Qs({hosts:[e.masternode]},t)))).sort(((e,t)=>e.nonce-t.nonce))}signBatch(e,t){e.forEach((e=>e.sign(t)))}sendBatch(e){let t=[];return new Promise((r=>{e.forEach(((n,i)=>{setTimeout((()=>{t[i]=n.send().then((()=>n)),(n=>{n+1===e.length&&r(t)})(i)}),1200*i)}))}))}},Masternode_API:Gs,Network:Xs,wallet:zs,Keystore:class{constructor(e){this.KEYSTORE_VERSION="1.0",this.password=null,this.encryptedData=null,this.keyList=(()=>{let e=[],t=this,r=[];const n=t=>{e.push(t),i()},i=()=>{r=[],e.forEach((e=>{let t=Ls({sk:e.sk,keepPrivate:!0});t={...t,...e},delete t.sk,r.push(t)}))};return{getWallets:()=>r,getWallet:e=>r.find((t=>t.vk===e)),addKey:n,clearKeys:()=>{e=[],i()},numOfKeys:()=>e.length,deleteKey:t=>{e.splice(t,1),i()},createKeystore:(r,n)=>JSON.stringify({data:x(r,{version:t.KEYSTORE_VERSION,keyList:e}),w:n?A("n1ahcKc0lb",n):""}),decryptKeystore:(e,r)=>{let i=R(e,r);if(!i)throw new Error("Incorrect Keystore Password.");ru.isArray(i.keyList),i.keyList.forEach((e=>ru.isStringWithValue(e.sk))),i.keyList.forEach((e=>n(e))),t.version=i.version}}})(),e&&(e.key&&this.addKey(e.key),e.keyList&&this.addKeys(e.keyList),e.keystoreData&&this.addKeystoreData(e.keystoreData))}addKeys(e){ru.isArray(e),e.forEach((e=>this.addKey(e)))}addKey(e){ru.isObjectWithKeys(e),ru.isStringWithValue(e.sk),tu.isStringWithValue(e.vk)&&delete e.vk,this.keyList.addKey(e)}addKeystoreData(e){tu.isString(e)&&(e=JSON.parse(e)),this.validateKeyStore(e)&&(this.encryptedData=e)}getPasswordHint(e){if(!this.encryptedData&&!e)throw new Error("No keystore data found.");return e?tu.isString(e)&&(e=JSON.parse(e)):e=this.encryptedData,e.w?T("n1ahcKc0lb",e.w):""}deleteKey(e){if(ru.isInteger(e),0!==this.keyList.numOfKeys()){if(e<0||e>=this.keyList.numOfKeys())throw new Error("Key index out of range.");this.keyList.deleteKey(e)}}clearKeys(){this.keyList.clearKeys()}get wallets(){return this.keyList.getWallets()}getWallet(e){return this.keyList.getWallet(e)}validateKeyStore(e){ru.isObjectWithKeys(e);try{let t=JSON.parse(e.data);if(!t.ct||!t.iv||!t.s)throw new Error("This is not a valid keystore file.")}catch(e){throw new Error("This is not a valid keystore file.")}return!0}createKeystore(e,t){return ru.isStringWithValue(e),t&&ru.isStringWithValue(t),this.keyList.createKeystore(e,t)}decryptKeystore(e,t){if(t&&this.addKeystoreData(t),!this.encryptedData)throw new Error("No keystoreData to decrypt.");try{this.keyList.decryptKeystore(e,this.encryptedData.data)}catch(e){throw new Error("Incorrect Keystore Password.")}}},Encoder:$s,utils:L};export{nu as default}; diff --git a/dist/lamden.js b/dist/lamden.js deleted file mode 100644 index 83aef17..0000000 --- a/dist/lamden.js +++ /dev/null @@ -1,6633 +0,0 @@ -'use strict'; - -var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; -var inited = false; -function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; -} - -function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; - - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); - - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; - - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') -} - -function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } - - parts.push(output); - - return parts.join('') -} - -function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; -} - -var toString = {}.toString; - -var isArray = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -var INSPECT_MAX_BYTES = 50; - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ -Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; - -function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff -} - -function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length); - } - that.length = length; - } - - return that -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) -} - -Buffer.poolSize = 8192; // not used by this implementation - -// TODO: Legacy, not needed anymore. Remove in next major version. -Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr -}; - -function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) -}; - -if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; -} - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } -} - -function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) -}; - -function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) -}; -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) -}; - -function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - - var actual = that.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that -} - -function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that -} - -function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that -} - -function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len); - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') -} - -function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 -} -Buffer.isBuffer = isBuffer; -function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) -} - -Buffer.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -}; - -Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer -}; - -function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } -} -Buffer.byteLength = byteLength; - -function slowToString (encoding, start, end) { - var loweredCase = false; - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } -} - -// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect -// Buffer instances. -Buffer.prototype._isBuffer = true; - -function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this -}; - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this -}; - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this -}; - -Buffer.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -}; - -Buffer.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -}; - -Buffer.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' -}; - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - - if (this === target) return 0 - - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -}; - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -}; - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -}; - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -}; - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8'; - - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } -}; - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -}; - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000; - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length; - - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - - var newBuf; - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - return newBuf -}; - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val -}; - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val -}; - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] -}; - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) -}; - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] -}; - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -}; - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -}; - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val -}; - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; - - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - - return val -}; - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -}; - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val -}; - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -}; - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -}; - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) -}; - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) -}; - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) -}; - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) -}; - -function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength -}; - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } - - return offset + byteLength -}; - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 -}; - -function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 -}; - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 -}; - -function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 -}; - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 -}; - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength -}; - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } - - return offset + byteLength -}; - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 -}; - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 -}; - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 -}; - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 -}; - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 -}; - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -}; - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -}; - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -}; - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -}; - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } - - return len -}; - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - - if (!val) val = 0; - - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this -}; - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - -function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str -} - -function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray -} - - -function base64ToBytes (str) { - return toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i -} - -function isnan (val) { - return val !== val // eslint-disable-line no-self-compare -} - - -// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) -} - -function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) -} - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; -} - -function getCjsExportFromNamespace (n) { - return n && n['default'] || n; -} - -var dist = createCommonjsModule(function (module, exports) { -(function (global, factory) { - factory(exports) ; -}(commonjsGlobal, (function (exports) { - class ValidateTypes { - constructor() {} - - getType(value) { - return Object.prototype.toString.call(value); - } - - getClassName(value) { - try { - return value.constructor.name; - } catch (e) {} - - return this.getType(value); - } //Validation functions - - - isObject(value) { - if (this.getType(value) === "[object Object]") return true; - return false; - } - - isFunction(value) { - if (this.getType(value) === "[object Function]") return true; - return false; - } - - isString(value) { - if (this.getType(value) === "[object String]") return true; - return false; - } - - isBoolean(value) { - if (this.getType(value) === "[object Boolean]") return true; - return false; - } - - isArray(value) { - if (this.getType(value) === "[object Array]") return true; - return false; - } - - isNumber(value) { - if (this.getType(value) === "[object Number]") return true; - return false; - } - - isInteger(value) { - if (this.getType(value) === "[object Number]" && Number.isInteger(value)) return true; - return false; - } - - isRegEx(value) { - if (this.getType(value) === "[object RegExp]") return true; - return false; - } - - isStringHex(value) { - if (!this.isStringWithValue(value)) return false; - let hexRegEx = /([0-9]|[a-f])/gim; - return (value.match(hexRegEx) || []).length === value.length; - } - - hasKeys(value, keys) { - if (keys.map(key => key in value).includes(false)) return false; - return true; - } - - isStringWithValue(value) { - if (this.isString(value) && value !== '') return true; - return false; - } - - isObjectWithKeys(value) { - if (this.isObject(value) && Object.keys(value).length > 0) return true; - return false; - } - - isArrayWithValues(value) { - if (this.isArray(value) && value.length > 0) return true; - return false; - } - - isSpecificClass(value, className) { - if (!this.isObject(value)) return false; - if (this.getClassName(value) !== className) return false; - return true; - } - - } - - class AssertTypes { - constructor() { - this.validate = new ValidateTypes(); - } //Validation functions - - - isObject(value) { - if (!this.validate.isObject(value)) { - throw new TypeError(`Expected type [object Object] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isFunction(value) { - if (!this.validate.isFunction(value)) { - throw new TypeError(`Expected type [object Function] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isString(value) { - if (!this.validate.isString(value)) { - throw new TypeError(`Expected type [object String] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isBoolean(value) { - if (!this.validate.isBoolean(value)) { - throw new TypeError(`Expected type [object Boolean] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isArray(value) { - if (!this.validate.isArray(value)) { - throw new TypeError(`Expected type [object Array] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isNumber(value) { - if (!this.validate.isNumber(value)) { - throw new TypeError(`Expected type [object Number] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isInteger(value) { - if (!this.validate.isInteger(value)) { - throw new TypeError(`Expected "${value}" to be an integer but got non-integer value`); - } - - return true; - } - - isRegEx(value) { - if (!this.validate.isRegEx(value)) { - throw new TypeError(`Expected type [object RegExp] but got ${this.validate.getType(value)}`); - } - - return true; - } - - isStringHex(value) { - if (!this.validate.isStringHex(value)) { - throw new TypeError(`Expected "${value}" to be hex but got non-hex value`); - } - - return true; - } - - hasKeys(value, keys) { - if (!this.validate.hasKeys(value, keys)) { - throw new TypeError(`Provided object does not contain all keys ${JSON.stringify(keys)}`); - } - - return true; - } - - isStringWithValue(value) { - if (!this.validate.isStringWithValue(value)) { - throw new TypeError(`Expected "${value}" to be [object String] and not empty`); - } - - return true; - } - - isObjectWithKeys(value) { - if (!this.validate.isObjectWithKeys(value)) { - throw new TypeError(`Expected "${value}" to be [object Object] and have keys`); - } - - return true; - } - - isArrayWithValues(value) { - if (!this.validate.isArrayWithValues(value)) { - throw new TypeError(`Expected "${value}" to be [object Array] and not empty`); - } - - return true; - } - - isSpecificClass(value, className) { - if (!this.validate.isSpecificClass(value, className)) { - throw new TypeError(`Expected Object Class to be "${className}" but got ${this.validate.getClassName(value)}`); - } - - return true; - } - - } - - const validateTypes = new ValidateTypes(); - const assertTypes = new AssertTypes(); - - exports.assertTypes = assertTypes; - exports.validateTypes = validateTypes; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); -}); - -var validators = unwrapExports(dist); - -const nodeCryptoJs = require("node-cryptojs-aes"); -const { CryptoJS, JsonFormatter } = nodeCryptoJs; -const validators$1 = require('types-validate-assert'); -const { validateTypes, assertTypes } = validators$1; - -/** - * Encrypt a Javascript object with a string password - * The object passed must pass JSON.stringify or the method will fail. - * - * @param {string} password A password to encrypt the object with - * @param {Object} obj A javascript object (must be JSON compatible) - * @return {string} Encrypted string - */ -function encryptObject ( password, obj ){ - assertTypes.isStringWithValue(password); - assertTypes.isObject(obj); - - const encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), password, { format: JsonFormatter }).toString(); - return encrypted; -} -/** - * Decrypt an Object using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} objString A javascript object as JSON string - * @return {string} Encrypted string -*/ -function decryptObject ( password, objString ) { - assertTypes.isStringWithValue(password); - assertTypes.isStringWithValue(objString); - - try{ - const decrypt = CryptoJS.AES.decrypt(objString, password, { format: JsonFormatter }); - return JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt)); - } catch (e){ - return false; - } -} -/** - * Encrypt a string using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} string A string to be password encrypted - * @return {string} Encrypted string -*/ -function encryptStrHash( password, string ){ - assertTypes.isStringWithValue(password); - assertTypes.isString(string); - - const encrypt = CryptoJS.AES.encrypt(string, password).toString(); - return encrypt; -} -/** - * Decrypt a string using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} encryptedString A string to decrypt - * @return {string} Decrypted string -*/ -function decryptStrHash ( password, encryptedString ){ - assertTypes.isStringWithValue(password); - assertTypes.isStringWithValue(encryptedString); - - try{ - const decrypted = CryptoJS.AES.decrypt(encryptedString, password); - return CryptoJS.enc.Utf8.stringify(decrypted) === '' ? false : CryptoJS.enc.Utf8.stringify(decrypted); - } catch (e) { - return false; - } -} -function buf2hex(buffer) { - return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); -} -function hex2buf(hexString) { - var bytes = new Uint8Array(Math.ceil(hexString.length / 2)); - for (var i = 0; i < bytes.length; i++) - bytes[i] = parseInt(hexString.substr(i * 2, 2), 16); - return bytes; -} -function str2buf(string) { - var buf = new Buffer.from(string); - return new Uint8Array(buf); -} -function concatUint8Arrays(array1, array2) { - var arr = new Uint8Array(array1.length + array2.length); - arr.set(array1); - arr.set(array2, array1.length); - return arr; -} -function ab2str(buf) { - return String.fromCharCode.apply(null, new Uint8Array(buf)); -} -function str2ab(str) { - var buf = new ArrayBuffer(str.length); - var bufView = new Uint8Array(buf); - for (var i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - return buf; -} -function str2hex(str) { - var hex = ''; - for (var i = 0; i < str.length; i++) { - hex += '' + str.charCodeAt(i).toString(16); - } - return hex; -} -function hex2str(hexx) { - var hex = hexx.toString(); //force conversion - var str = ''; - for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2) - str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - return str; -} -function randomString(length) { - var text = ""; - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (var i = 0; i < length; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; -} -function isStringHex(string = '') { - let hexRegEx = /([0-9]|[a-f])/gim; - return typeof string === 'string' && - (string.match(hexRegEx) || []).length === string.length; -} - -function isLamdenKey( string ){ - if (validateTypes.isStringHex(string) && string.length === 64) return true; - return false; -} - -var utils = /*#__PURE__*/Object.freeze({ - __proto__: null, - encryptObject: encryptObject, - decryptObject: decryptObject, - encryptStrHash: encryptStrHash, - decryptStrHash: decryptStrHash, - buf2hex: buf2hex, - hex2buf: hex2buf, - str2buf: str2buf, - concatUint8Arrays: concatUint8Arrays, - ab2str: ab2str, - str2ab: str2ab, - str2hex: str2hex, - hex2str: hex2str, - randomString: randomString, - isStringHex: isStringHex, - isLamdenKey: isLamdenKey -}); - -const nacl = require('tweetnacl'); -const bip39 = require('bip39'); -const bip32 = require('ed25519-hd-key'); - -/** - * Create a wallet object for signing and verifying messages - * - * @param {Object} [args={}] Args Object - * @param {string} [args.sk=undefined] A 32 character long hex representation of a signing key (private key) to create wallet from - * @param {Uint8Array(length: 32)} [args.seed=null] A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be avoided by everyday users - * @param {boolean} [args.keepPrivate=false] No direct access to the sk. Will still allow the wallet to sign messages - * @return {Object} Wallet Object with sign and verify methods - */ -let create_wallet = (args = {}) => { - let { sk = undefined, keepPrivate = false, seed = null } = args; - - let vk; - - if (sk) { - vk = get_vk(sk); - }else{ - let keyPair = new_wallet(seed); - vk = keyPair.vk; - sk = keyPair.sk; - } - - const wallet = () => { - return { - sign: (msg) => sign(sk, msg), - verify: (msg, sig) => verify(vk, msg, sig), - vk, - sk: !keepPrivate ? sk : undefined - } - }; - - return wallet() -}; - -/** - * @param Uint8Array(length: 32) seed - * seed: A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be - * avoided by everyday users - * - * @return {Uint8Array(length: 32), Uint8Array(length: 32)} { vk, sk } - * sk: Signing Key (SK) represents 32 byte signing key - * vk: Verify Key (VK) represents a 32 byte verify key - */ -function generate_keys(seed = null) { - var kp = null; - if (seed == null) { - kp = nacl.sign.keyPair(); - } - else { - kp = nacl.sign.keyPair.fromSeed(seed); - } - // In the JS implementation of the NaCL library the sk is the first 32 bytes of the secretKey - // and the vk is the last 32 bytes of the secretKey as well as the publicKey - // { - // 'publicKey': , - // 'secretKey': - // } - return { - sk: new Uint8Array(kp['secretKey'].slice(0, 32)), - vk: new Uint8Array(kp['secretKey'].slice(32, 64)) - }; -} -/** - * @param String sk - * sk: A 64 character long hex representation of a signing key (private key) - * - * @return String vk - * vk: A 64 character long hex representation of a verify key (public key) - */ -function get_vk(sk) { - var kp = format_to_keys(sk); - var kpf = keys_to_format(kp); - return kpf.vk; -} -/** - * @param String sk - * sk: A 64 character long hex representation of a signing key (private key) - * - * @return {Uint8Array(length: 32), Uint8Array(length: 32)} { vk, sk } - * sk: Signing Key (SK) represents 32 byte signing key - * vk: Verify Key (VK) represents a 32 byte verify key - */ -function format_to_keys(sk) { - var skf = hex2buf(sk); - var kp = generate_keys(skf); - return kp; -} -/** - * @param Object kp - * kp: Object containing the properties sk and vk - * sk: Signing Key (SK) represents 32 byte signing key - * vk: Verify Key (VK) represents a 32 byte verify key - * - * @return {string, string} { sk, vk } - * sk: Signing Key (SK) represented as a 64 character hex string - * vk: Verify Key (VK) represented as a 64 character hex string - */ -function keys_to_format(kp) { - return { - vk: buf2hex(kp.vk), - sk: buf2hex(kp.sk) - }; -} -/** - * @param Uint8Array(length: 32) seed - * seed: A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be - * avoided by everyday users - * - * @return {string, string} { sk, vk } - * sk: Signing Key (SK) represented as a 64 character hex string - * vk: Verify Key (VK) represented as a 64 character hex string - */ -function new_wallet(seed = null) { - const keys = generate_keys(seed); - return keys_to_format(keys); -} - -/** - * - * @param mnemonic 24 word seed phrase - * @param derivationIndex bip32 derivation key index - * @returns {{derivationIndex: number, vk: string, sk: string, mnemonic: string}} - * derivationIndex: bip32 derivation key index - * vk: Verify Key (VK) represented as a 64 character hex string - * sk: Signing Key (SK) represented as a 64 character hex string - * mnemonic: 24 word seed phrase - - */ -function generate_keys_bip39(mnemonic = undefined, derivationIndex = 0) { - let finalMnemonic; - - if (mnemonic !== undefined){ - finalMnemonic = mnemonic; - }else { - finalMnemonic = bip39.generateMnemonic(256); - } - - const seed = bip39.mnemonicToSeedSync(finalMnemonic).toString('hex'); - - const derivationPath = "m/44'/789'/" + derivationIndex + "'/0'/0'"; - const { key, chainCode } = bip32.derivePath(derivationPath, seed, 0x80000000); - - const privateKey = key.toString('hex'); - const publicKey = bip32.getPublicKey(key, false).toString('hex'); - - if (publicKey !== get_vk(privateKey)){ - throw Error('Bip32 public key does not match with Lamden public key!') - } - - return { - sk: privateKey, - vk: publicKey, - derivationIndex: derivationIndex, - mnemonic: finalMnemonic - } -} - -/** - * @param mnemonic 24 word seed phrase - * @param derivationIndex bip32 derivation key index - * - * @return {{derivationIndex: number, vk: string, sk: string, mnemonic: (string|undefined)}} { sk, vk, derivationIndex, mnemonic } - * sk: Signing Key (SK) represented as a 64 character hex string - * vk: Verify Key (VK) represented as a 64 character hex string - * derivationIndex: Bip32 derivation index - * mnemonic: 24 word seed phrase - */ -function new_wallet_bip39(mnemonic = undefined, derivationIndex = 0) { - return generate_keys_bip39(mnemonic, derivationIndex); -} - -/** - * @param String sk - * @param Uint8Array msg - * sk: A 64 character long hex representation of a signing key (private key) - * msg: A Uint8Array of bytes representing the message you would like to sign - * - * @return String sig - * sig: A 128 character long hex string representing the message's signature - */ -function sign(sk, msg) { - var kp = format_to_keys(sk); - // This is required due to the secretKey required to sign a transaction - // in the js implementation of NaCL being the combination of the sk and - // vk for some stupid reason. That being said, we still want the sk and - // vk objects to exist in 32-byte string format (same as cilantro's - // python implementation) when presented to the user. - var jsnacl_sk = concatUint8Arrays(kp.sk, kp.vk); - return buf2hex(nacl.sign.detached(msg, jsnacl_sk)); -} -/** - * @param String vk - * @param Uint8Array msg - * @param String sig - * vk: A 64 character long hex representation of a verify key (public key) - * msg: A Uint8Array (bytes) representation of a message that has been signed - * sig: A 128 character long hex representation of a nacl signature - * - * @return Bool result - * result: true if verify checked out, false if not - */ -function verify(vk, msg, sig) { - var vkb = hex2buf(vk); - var sigb = hex2buf(sig); - try { - return nacl.sign.detached.verify(msg, sigb, vkb); - } - catch (_a) { - return false; - } -} - -var wallet = /*#__PURE__*/Object.freeze({ - __proto__: null, - create_wallet: create_wallet, - generate_keys: generate_keys, - get_vk: get_vk, - format_to_keys: format_to_keys, - keys_to_format: keys_to_format, - new_wallet: new_wallet, - new_wallet_bip39: new_wallet_bip39, - sign: sign, - verify: verify -}); - -class EventEmitter { - constructor() { - this._events = {}; - } - - on(name, listener) { - if (!this._events[name]) { - this._events[name] = []; - } - - this._events[name].push(listener); - } - - removeListener(name, listenerToRemove) { - if (!this._events[name]) { - throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`); - } - - const filterListeners = (listener) => listener !== listenerToRemove; - this._events[name] = this._events[name].filter(filterListeners); - } - - emit(name, data) { - if (!this._events[name]) return - - const fireCallbacks = (callback) => { - callback(data); - }; - - this._events[name].forEach(fireCallbacks); - } - } - -/* - * bignumber.js v9.0.0 - * A JavaScript library for arbitrary-precision arithmetic. - * https://github.com/MikeMcl/bignumber.js - * Copyright (c) 2019 Michael Mclaughlin - * 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 - - -var BigNumber = clone(); - -var bignumber = /*#__PURE__*/Object.freeze({ - __proto__: null, - BigNumber: BigNumber, - 'default': BigNumber -}); - -var BigNumber$1 = getCjsExportFromNamespace(bignumber); - -BigNumber$1.config({ RANGE: [-30, 30], EXPONENTIAL_AT: 1e+9 }); -BigNumber$1.set({ DECIMAL_PLACES: 30, ROUNDING_MODE: BigNumber$1.ROUND_DOWN }); // equivalent - -function Encoder (type, value) { - const throwError = (val) => { - throw new Error(`Error encoding ${val} to ${type}`) - }; - const countDecimals = (n) => { - if(Math.floor(n) === n) return 0; - try{ - return n.toString().split(".")[1].length - }catch (e){ - return 0 - } - }; - const isString = (val) => typeof val === 'string' || val instanceof String; - const isArray = (val) => val && typeof val === 'object' && val.constructor === Array; - const isObject = (val) => val && typeof val === 'object' && val.constructor === Object; - const isDate = (val) => val instanceof Date; - const isBoolean = (val) => typeof val === 'boolean'; - - const isNumber = (val) => { - if (isArray(val)) return false - return !isNaN(encodeBigNumber(val).toNumber()) - }; - - const isInteger = (val) => { - if (!isNumber(val)) return false - if (countDecimals(val) === 0) return true - return false - }; - const encodeInt = (val) => { - if (!isNumber(val)) throwError(val); - else return parseInt(val) - }; - const isFloat = (val) => { - if (!isNumber(val)) return false - if (countDecimals(val) === 0) return false - return true - }; - const encodeFloat = (val) => { - if(!isNumber(val)) throwError(val); - if (!BigNumber$1.isBigNumber(val)) val = new BigNumber$1(val); - - return {"__fixed__": val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, '$1$2')} - }; - const encodeNumber = (val) => { - if(!isNumber(val)) throwError(val); - if (isFloat(val)) { - if (!BigNumber$1.isBigNumber(val)) val = new BigNumber$1(val); - return {"__fixed__": val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, '$1$2')} - } - if (isInteger(val)) return parseInt(val) - }; - const encodeBigNumber = (val) => { - if (!BigNumber$1.isBigNumber(val)) val = new BigNumber$1(val); - return val - }; - - const encodeBool = (val) => { - if (isBoolean(val)) return val - if (val === 'true' || val === 1) return true - if (val === 'false' || val === 0) return false - throwError(val); - }; - const encodeStr = (val) => { - if (isString(val)) return val - if (isDate(val)) return val.toISOString() - return JSON.stringify(val) - }; - const encodeDateTime = (val) => { - val = !isDate(val) ? new Date(val) : val; - if (!isDate(val)) throwError(val); - return {'__time__': [ - val.getUTCFullYear(), - val.getUTCMonth(), - val.getUTCDate(), - val.getUTCHours(), - val.getUTCMinutes(), - val.getUTCSeconds(), - val.getUTCMilliseconds() - ]} - }; - const encodeTimeDelta = (val) => { - const time = isDate(val) ? val.getTime() : new Date(val).getTime(); - const days = parseInt(time / 1000 / 60 / 60 / 24); - const seconds = (time - (days * 24 * 60 * 60 * 1000)) / 1000; - return {'__delta__':[days, seconds]} - }; - - const encodeList = (val) => { - if (isArray(val)) return parseObject(val) - try{ - val = JSON.parse(val); - }catch(e){ - throwError(val); - } - if (isArray(val)) return parseObject(val) - throwError(val); - }; - - const encodeDict = (val) => { - if (isObject(val)) return parseObject(val) - try{ - val = JSON.parse(val); - }catch(e){ - throwError(val); - } - if (isObject(val)) return parseObject(val) - throwError(val); - }; - - const encodeObject = (val) => { - try { - return encodeList(val) - }catch(e){ - return encodeDict(val) - } - }; - - function parseObject (obj) { - const encode = (k, v) => { - if (k === "datetime" || k === "datetime.datetime" ) return Encoder("datetime.datetime", v) - if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v) - if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v) - return v - }; - - const fixDatetime = (k, v) => { - const isDatetimeObject = (val) => { - let datetimeTypes = ['datetime.datetime', 'datetime', 'datetime.timedelta', 'timedelta']; - return Object.keys(val).length === 1 && datetimeTypes.filter(f => f === Object.keys(val)[0]).length > 0 - - }; - - if (v.constructor === Array) { - v.map(val => { - if (Object.keys(val).length === 1 && isDatetimeObject(v)) return val[Object.keys(val)[0]] - //if (isFloat(val)) return encodeFloat(val) - return val - }); - } - if (v.constructor === Object) { - if (Object.keys(v).length === 1 && isDatetimeObject(v)) return v[Object.keys(v)[0]] - } - - //if (isFloat(v)) return encodeFloat(v) - - return v - }; - - let encodeValues = JSON.stringify(obj, encode); - return JSON.parse(encodeValues, fixDatetime) - } - - const encoder = { - str: encodeStr, - string: encodeStr, - float: encodeFloat, - int: encodeInt, - bool: encodeBool, - boolean: encodeBool, - dict: encodeDict, - list: encodeList, - Any: () => value, - "datetime.timedelta": encodeTimeDelta, - "datetime.datetime": encodeDateTime, - timedelta: encodeTimeDelta, - datetime: encodeDateTime, - number: encodeNumber, - object: encodeObject, - bigNumber: encodeBigNumber, - }; - - if (Object.keys(encoder).includes(type)) return encoder[type](value) - else throw new Error(`Error: ${type} is not a valid encoder type.`) -} - -Encoder.BigNumber = BigNumber$1; - -var encoder = { - Encoder -}; -var encoder_1 = encoder.Encoder; - -const { validateTypes: validateTypes$1 } = validators; -const fetch = require('node-fetch').default; - -class LamdenMasterNode_API{ - constructor(networkInfoObj){ - if (!validateTypes$1.isObjectWithKeys(networkInfoObj)) throw new Error(`Expected Object and got Type: ${typeof networkInfoObj}`) - if (!validateTypes$1.isArrayWithValues(networkInfoObj.hosts)) throw new Error(`HOSTS Required (Type: Array)`) - - this.hosts = this.validateHosts(networkInfoObj.hosts); - } - //This will throw an error if the protocol wasn't included in the host string - vaidateProtocol(host){ - let protocols = ['https://', 'http://']; - if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host - throw new Error('Host String must include http:// or https://') - } - validateHosts(hosts){ - return hosts.map(host => this.vaidateProtocol(host.toLowerCase())) - } - - get host() {return this.hosts[Math.floor(Math.random() * this.hosts.length)]} - get url() {return this.host} - - send(method, path, data, overrideURL, callback){ - let parms = ''; - if (Object.keys(data).includes('parms')) { - parms = this.createParms(data.parms); - } - - let options = {}; - if (method === 'POST'){ - let headers = {'Content-Type': 'application/json'}; - options.method = method; - options.headers = headers; - options.body = data; - } - - return fetch(`${overrideURL ? overrideURL : this.url}${path}${parms}`, options) - .then(async (res) => { - if (res.status === 200){ - let json = await res.json(); - callback(json, undefined); - return json - }else{ - let error = validateTypes$1.isStringWithValue(res.statusText) ? res.statusText : false; - callback(undefined, error); - return error - } - }) - .catch(err => { - return callback(undefined, err.toString()) - }) - } - - createParms(parms){ - if (Object.keys(parms).length === 0) return '' - let parmString = '?'; - Object.keys(parms).forEach(key => { - parmString = `${parmString}${key}=${parms[key]}&`; - }); - return parmString.slice(0, -1); - } - - async getContractInfo(contractName){ - const returnInfo = (res) => { - try{ - if (res.name) return res - } catch (e){} - return null; - }; - let path = `/contracts/${contractName}`; - return this.send('GET', path, {}, undefined, (res, err) => returnInfo(res)) - .then(res => returnInfo(res)) - } - - async getVariable(contract, variable, key = ''){ - let parms = {}; - if (validateTypes$1.isStringWithValue(key)) parms.key = key; - - let path = `/contracts/${contract}/${variable}/`; - - const returnValue = (res) => { - try{ - if (res.value) return res.value - } catch (e){} - return null; - }; - return this.send('GET', path, {parms}, undefined, (res, err) => returnValue(res)) - .then(res => returnValue(res)) - } - - async getContractMethods(contract){ - const getMethods = (res) => { - try{ - if (res.methods) return res.methods - } catch (e){} - return []; - }; - let path = `/contracts/${contract}/methods`; - return this.send('GET', path, {}, undefined, (res, err) => getMethods(res)) - .then(res => getMethods(res)) - } - - async getContractVariables(contract){ - const getVariables = (res) => { - try{ - if (res.variables) return res - } catch (e){} - return {}; - }; - let path = `/contracts/${contract}/variables`; - return this.send('GET', path, {}, undefined, (res, err) => getVariables(res)) - .then(res => getVariables(res)) - } - - async pingServer(){ - const getStatus = (res) => { - try { - if (res.status) return true; - } catch (e) {} - return false - }; - let response = await this.send('GET', '/ping', {}, undefined, (res, err) => getStatus(res)); - return getStatus(response) - - } - - async getCurrencyBalance(vk){ - let balanceRes = await this.getVariable('currency', 'balances', vk); - if (!balanceRes) return encoder_1('bigNumber', 0); - if (balanceRes.__fixed__) return encoder_1('bigNumber', balanceRes.__fixed__) - return encoder_1('bigNumber', balanceRes.toString()); - } - - async contractExists(contractName){ - const exists = (res) => { - try { - if (res.name) return true; - } catch (e) {} - return false - }; - let path = `/contracts/${contractName}`; - return this.send('GET', path, {}, undefined, (res, err) => exists(res)) - .then(res => exists(res)) - } - - async sendTransaction(data, url = undefined, callback){ - return this.send('POST', '/', JSON.stringify(data), url, (res, err) => { - if (err){ - if (callback) { - callback(undefined, err); - return; - } - else return err - } - if (callback) { - callback(res, undefined); - return - } - return res; - }) - } - - async getNonce(sender, callback){ - if (!validateTypes$1.isStringHex(sender)) return `${sender} is not a hex string.` - let path = `/nonce/${sender}`; - let url = this.host; - return this.send('GET', path, {}, url, (res, err) => { - if (err){ - if (callback) { - callback(undefined, `Unable to get nonce for ${sender} on network ${url}`); - return - } - return `Unable to get nonce for ${sender} on network ${url}` - } - res.masternode = url; - if (callback) { - callback(res, undefined); - return - } - else return res; - }) - } - - async checkTransaction(hash, callback){ - const parms = {hash}; - return this.send('GET', '/tx', {parms}, undefined, (res, err) => { - if (err){ - if (callback) { - callback(undefined, err); - return; - } - else return err - } - if (callback) { - callback(res, undefined); - return - } - return res; - }) - } -} - -const { validateTypes: validateTypes$2 } = validators; - -class Network { - // Constructor needs an Object with the following information to build Class. - // - // networkInfo: { - // hosts: list of masternode hostname/ip urls, - // type: "testnet", "mainnet" or "custom" - // }, - constructor(networkInfoObj){ - //Reject undefined or missing info - if (!validateTypes$2.isObjectWithKeys(networkInfoObj)) throw new Error(`Expected Network Info Object and got Type: ${typeof networkInfoObj}`) - if (!validateTypes$2.isArrayWithValues(networkInfoObj.hosts)) throw new Error(`HOSTS Required (Type: Array)`) - - this.type = validateTypes$2.isStringWithValue(networkInfoObj.type) ? networkInfoObj.type.toLowerCase() : "custom"; - this.events = new EventEmitter(); - this.hosts = this.validateHosts(networkInfoObj.hosts); - this.currencySymbol = validateTypes$2.isStringWithValue(networkInfoObj.currencySymbol) ? networkInfoObj.currencySymbol : 'TAU'; - this.name = validateTypes$2.isStringWithValue(networkInfoObj.name) ? networkInfoObj.name : 'lamden network'; - this.lamden = validateTypes$2.isBoolean(networkInfoObj.lamden) ? networkInfoObj.lamden : false; - this.blockExplorer = validateTypes$2.isStringWithValue(networkInfoObj.blockExplorer) ? networkInfoObj.blockExplorer : undefined; - - this.online = false; - try{ - this.API = new LamdenMasterNode_API(networkInfoObj); - } catch (e) { - throw new Error(e) - } - } - //This will throw an error if the protocol wasn't included in the host string - vaidateProtocol(host){ - let protocols = ['https://', 'http://']; - if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host - throw new Error('Host String must include http:// or https://') - } - validateHosts(hosts){ - return hosts.map(host => this.vaidateProtocol(host.toLowerCase())) - } - //Check if the network is online - //Emits boolean as 'online' event - //Also returns status as well as passes status to a callback - async ping(callback = undefined){ - this.online = await this.API.pingServer(); - this.events.emit('online', this.online); - if (validateTypes$2.isFunction(callback)) callback(this.online); - return this.online - } - get host() {return this.hosts[Math.floor(Math.random() * this.hosts.length)]} - get url() {return this.host} - getNetworkInfo(){ - return { - name: this.name, - lamden: this.lamden, - type: this.type, - hosts: this.hosts, - url: this.url, - online: this.online, - } - } -} - -const { validateTypes: validateTypes$3 } = validators; - -class TransactionBuilder extends Network { - // Constructor needs an Object with the following information to build Class. - // - // arg[0] (networkInfo): { //Can also accpet a Lamden "Network Class" - // host: masternode webserver hostname/ip, - // type: "testnet", "mainnet" or "mockchain" - // } - // arg[1] (txInfo): { - // uid: [Optional] unique ID for tracking purposes, - // senderVk: public key of the transaction sender, - // contractName: name of lamden smart contract, - // methodName: name of method to call in contractName, - // kwargs: key/values of args to pass to methodName - // example: kwargs.to = "270add00fc708791c97aeb5255107c770434bd2ab71c2e103fbee75e202aa15e" - // kwargs.amount = 1000 - // stampLimit: the max amount of stamps the tx should use. tx could use less. if tx needs more the tx will fail. - // nonce: [Optional] send() will attempt to retrieve this info automatically - // processor [Optional] send() will attempt to retrieve this info automatically - // } - // arg[2] (txData): [Optional] state hydrating data - constructor(networkInfo, txInfo, txData) { - if (validateTypes$3.isSpecificClass(networkInfo, 'Network')) - super(networkInfo.getNetworkInfo()); - else super(networkInfo); - - //Validate arguments - if(!validateTypes$3.isObjectWithKeys(txInfo)) throw new Error(`txInfo object not found`) - if(!validateTypes$3.isStringHex(txInfo.senderVk)) throw new Error(`Sender Public Key Required (Type: Hex String)`) - if(!validateTypes$3.isStringWithValue(txInfo.contractName)) throw new Error(`Contract Name Required (Type: String)`) - if(!validateTypes$3.isStringWithValue(txInfo.methodName)) throw new Error(`Method Required (Type: String)`) - if(!validateTypes$3.isInteger(txInfo.stampLimit)) throw new Error(`Stamps Limit Required (Type: Integer)`) - - //Store variables in self for reference - this.uid = validateTypes$3.isStringWithValue(txInfo.uid) ? txInfo.uid : undefined; - this.sender = txInfo.senderVk; - this.contract = txInfo.contractName; - this.method = txInfo.methodName; - this.kwargs = {}; - if(validateTypes$3.isObject(txInfo.kwargs)) this.kwargs = txInfo.kwargs; - this.stampLimit = txInfo.stampLimit; - - //validate and set nonce and processor if user provided them - if (typeof txInfo.nonce !== 'undefined'){ - if(!validateTypes$3.isInteger(txInfo.nonce)) throw new Error(`arg[6] Nonce is required to be an Integer, type ${typeof txInfo.none} was given`) - this.nonce = txInfo.nonce; - } - if (typeof txInfo.processor !== 'undefined'){ - if(!validateTypes$3.isStringWithValue(txInfo.processor)) throw new Error(`arg[7] Processor is required to be a String, type ${typeof txInfo.processor} was given`) - this.processor = txInfo.processor; - } - - this.signature; - this.transactionSigned = false; - - //Transaction result information - this.nonceResult = {}; - this.txSendResult = {errors:[]}; - this.txBlockResult = {}; - this.txHash; - this.txCheckResult = {}; - this.txCheckAttempts = 0; - this.txCheckLimit = 10; - - //Hydrate other items if passed - if (txData){ - if (txData.uid) this.uid = txData.uid; - if (validateTypes$3.isObjectWithKeys(txData.txSendResult)) this.txSendResult = txData.txSendResult; - if (validateTypes$3.isObjectWithKeys(txData.nonceResult)){ - this.nonceResult = txData.nonceResult; - if (validateTypes$3.isInteger(this.nonceResult.nonce)) this.nonce = this.nonceResult.nonce; - if (validateTypes$3.isStringWithValue(this.nonceResult.processor)) this.processor = this.nonceResult.processor; - } - if (validateTypes$3.isObjectWithKeys(txData.txSendResult)){ - this.txSendResult = txData.txSendResult; - if (this.txSendResult.hash) this.txHash = this.txSendResult.hash; - } - if (validateTypes$3.isObjectWithKeys(txData.txBlockResult)) this.txBlockResult = txData.txBlockResult; - if (validateTypes$3.isObjectWithKeys(txData.resultInfo)) this.resultInfo = txData.resultInfo; - } - //Create Capnp messages and transactionMessages - this.makePayload(); - } - makePayload(){ - this.payload = { - contract: this.contract, - function: this.method, - kwargs: this.kwargs, - nonce: this.nonce, - processor: this.processor, - sender: this.sender, - stamps_supplied: this.stampLimit - }; - this.sortedPayload = this.sortObject(this.payload); - } - makeTransaction(){ - this.tx = { - metadata: { - signature: this.signature, - timestamp: parseInt(+new Date / 1000), - }, - payload: this.sortedPayload.orderedObj - }; - } - verifySignature(){ - //Verify the signature is correct - if (!this.transactionSigned) throw new Error('Transaction has not be been signed. Use the sign() method first.') - const stringBuffer = Buffer.from(this.sortedPayload.json); - const stringArray = new Uint8Array(stringBuffer); - return verify(this.sender, stringArray, this.signature) - } - sign(sk = undefined, userWallet = undefined){ - const stringBuffer = Buffer.from(this.sortedPayload.json); - const stringArray = new Uint8Array(stringBuffer); - if (userWallet) this.signature = userWallet.sign(stringArray); - else this.signature = sign(sk, stringArray); - this.transactionSigned = true; - } - sortObject(object){ - const processObj = (obj) => { - const getType = (value) => { - return Object.prototype.toString.call(value) - }; - const isArray = (value) => { - if(getType(value) === "[object Array]") return true; - return false; - }; - const isObject = (value) => { - if(getType(value) === "[object Object]") return true; - return false; - }; - - const sortObjKeys = (unsorted) => { - const sorted = {}; - Object.keys(unsorted).sort().forEach(key => sorted[key] = unsorted[key]); - return sorted - }; - - const formatKeys = (unformatted) => { - Object.keys(unformatted).forEach(key => { - if (isArray(unformatted[key])) unformatted[key] = unformatted[key].map(item => { - if (isObject(item)) return formatKeys(item) - return item - }); - if (isObject(unformatted[key])) unformatted[key] = formatKeys(unformatted[key]); - }); - return sortObjKeys(unformatted) - }; - - if (!isObject(obj)) throw new TypeError('Not a valid Object') - try{ - obj = JSON.parse(JSON.stringify(obj)); - } catch (e) { - throw new TypeError('Not a valid JSON Object') - } - return formatKeys(obj) - }; - const orderedObj = processObj(object); - return { - orderedObj, - json: JSON.stringify(orderedObj) - } - } - async getNonce(callback = undefined) { - let timestamp = new Date().toUTCString(); - this.nonceResult = await this.API.getNonce(this.sender); - if (typeof this.nonceResult.nonce === 'undefined'){ - throw new Error(this.nonceResult) - } - this.nonceResult.timestamp = timestamp; - this.nonce = this.nonceResult.nonce; - this.processor = this.nonceResult.processor; - this.nonceMasternode = this.nonceResult.masternode; - //Create payload object - this.makePayload(); - - if (!callback) return this.nonceResult; - return callback(this.nonceResult) - } - async send(sk = undefined, masternode = undefined, callback = undefined) { - //Error if transaction is not signed and no sk provided to the send method to sign it before sending - if (!validateTypes$3.isStringWithValue(sk) && !this.transactionSigned){ - throw new Error(`Transation Not Signed: Private key needed or call sign() first`); - } - - let timestamp = new Date().toUTCString(); - - try{ - //If the nonce isn't set attempt to get it - if (isNaN(this.nonce) || !validateTypes$3.isStringWithValue(this.processor)) await this.getNonce(); - //if the sk is provided then sign the transaction - if (validateTypes$3.isStringWithValue(sk)) this.sign(sk); - //Serialize transaction - this.makeTransaction(); - //Send transaction to the masternode - let masternodeURL = masternode; - if (!masternodeURL && this.nonceMasternode) masternodeURL = this.nonceMasternode; - let response = await this.API.sendTransaction(this.tx, masternodeURL); - //Set error if txSendResult doesn't exist - if (!response || validateTypes$3.isStringWithValue(response)){ - this.txSendResult.errors = [response || "Unknown Transaction Error"]; - }else{ - if (response.error) this.txSendResult.errors = [response.error]; - else this.txSendResult = response; - } - } catch (e){ - this.txSendResult.errors = [e.message]; - } - this.txSendResult.timestamp = timestamp; - return this.handleMasterNodeResponse(this.txSendResult, callback) - } - checkForTransactionResult(callback = undefined){ - return new Promise((resolve) => { - let timerId = setTimeout(async function checkTx() { - this.txCheckAttempts = this.txCheckAttempts + 1; - let res = await this.API.checkTransaction(this.txHash); - let checkAgain = false; - let timestamp = new Date().toUTCString(); - if (typeof res === 'string' || !res) { - if (this.txCheckAttempts < this.txCheckLimit){ - checkAgain = true; - }else{ - this.txCheckResult.errors = [ - `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, - res - ]; - } - }else{ - if (res.error){ - if (res.error === 'Transaction not found.'){ - if (this.txCheckAttempts < this.txCheckLimit){ - checkAgain = true; - }else{ - this.txCheckResult.errors = [res.error, `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`]; - } - }else{ - this.txCheckResult.errors = [res.error]; - } - }else{ - this.txCheckResult = res; - } - } - if (checkAgain) timerId = setTimeout(checkTx.bind(this), 1000); - else{ - if (validateTypes$3.isNumber(this.txCheckResult.status)){ - if (this.txCheckResult.status > 0){ - if (!validateTypes$3.isArray(this.txCheckResult.errors)) this.txCheckResult.errors = []; - this.txCheckResult.errors.push('This transaction returned a non-zero status code'); - } - } - this.txCheckResult.timestamp = timestamp; - clearTimeout(timerId); - resolve(this.handleMasterNodeResponse(this.txCheckResult, callback)); - } - }.bind(this), 1000); - }) - } - handleMasterNodeResponse(result, callback = undefined){ - //Check to see if this is a successful transacation submission - if (validateTypes$3.isStringWithValue(result.hash) && validateTypes$3.isStringWithValue(result.success)){ - this.txHash = result.hash; - this.setPendingBlockInfo(); - }else{ - this.setBlockResultInfo(result); - this.txBlockResult = result; - } - this.events.emit('response', result, this.resultInfo.subtitle); - if (validateTypes$3.isFunction(callback)) callback(result); - return result - } - setPendingBlockInfo(){ - this.resultInfo = { - title: 'Transaction Pending', - subtitle: 'Your transaction was submitted and is being processed', - message: `Tx Hash: ${this.txHash}`, - type: 'success', - }; - return this.resultInfo; - } - setBlockResultInfo(result){ - let erroredTx = false; - let errorText = `returned an error and `; - let statusCode = validateTypes$3.isNumber(result.status) ? result.status : undefined; - let stamps = (result.stampsUsed || result.stamps_used) || 0; - let message = ''; - if(validateTypes$3.isArrayWithValues(result.errors)){ - erroredTx = true; - message = `This transaction returned ${result.errors.length} errors.`; - if (result.result){ - if (result.result.includes('AssertionError')) result.errors.push(result.result); - } - } - if (statusCode && erroredTx) errorText = `returned status code ${statusCode} and `; - - this.resultInfo = { - title: `Transaction ${erroredTx ? 'Failed' : 'Successful'}`, - subtitle: `Your transaction ${erroredTx ? `${errorText} ` : ''}used ${stamps} stamps`, - message, - type: `${erroredTx ? 'error' : 'success'}`, - errorInfo: erroredTx ? result.errors : undefined, - returnResult: result.result || "", - stampsUsed: stamps, - statusCode - }; - return this.resultInfo; - } - getResultInfo(){ - return this.resultInfo; - } - getTxInfo(){ - return { - senderVk: this.sender, - contractName: this.contract, - methodName: this.method, - kwargs: this.kwargs, - stampLimit: this.stampLimit - } - } - getAllInfo(){ - return { - uid: this.uid, - txHash: this.txHash, - signed: this.transactionSigned, - tx: this.tx, - signature: this.signature, - networkInfo: this.getNetworkInfo(), - txInfo: this.getTxInfo(), - txSendResult: this.txSendResult, - txBlockResult: this.txBlockResult, - resultInfo: this.getResultInfo(), - nonceResult: this.nonceResult - } - } -} - -const { validateTypes: validateTypes$4 } = validators; - -class TransactionBatcher extends Network { - constructor(networkInfo) { - if (validateTypes$4.isSpecificClass(networkInfo, 'Network')) - super(networkInfo.getNetworkInfo()); - else super(networkInfo); - - this.txBatches = {}; - this.overflow = []; - this.nonceResults = {}; - this.running = false; - } - addTransaction(txInfo){ - if (this.running) { - this.overflow.push(txInfo); - return - } - this.validateTransactionInfo(txInfo); - if (!this.txBatches[txInfo.senderVk]) this.txBatches[txInfo.senderVk] = []; - this.txBatches[txInfo.senderVk].push(txInfo); - } - addTransactionList(txList){ - txList.forEach(txInfo => this.addTransaction(txInfo)); - } - processOverflow(){ - const overflow = this.overflow; - this.overflow = []; - overflow.forEach(txInfo => this.addTransaction(txInfo)); - } - hasTransactions(){ - let test = Object.keys(this.txBatches).map(senderVk => this.txBatches[senderVk].length); - test.filter(f => f === 0); - if (test.length > 0 ) return true - return false - } - validateTransactionInfo(txInfo){ - try{ - new TransactionBuilder(txInfo); - }catch(e){ - return false - } - return true - } - async getStartingNonce(senderVk, callback = undefined){ - let timestamp = new Date().toUTCString(); - let response = await this.API.getNonce(senderVk); - if (typeof response.nonce === 'undefined'){ - throw new Error(response) - } - response.timestamp = timestamp; - this.nonceResults[senderVk] = response; - - if (callback) callback(response); - return response; - } - async sendAllBatches(keyDict){ - if (this.running) return - let sentTransactions = []; - this.running = true; - - await Promise.all(Object.keys(this.txBatches).map((senderVk) => { - const senderBatch = this.txBatches[senderVk].splice(0,15); - if (senderBatch.length <= 15) delete this.txBatches[senderVk]; - - return new Promise(async (resolver) => { - if (senderBatch.length === 0 ) resolver(); - - if (!keyDict[senderVk]) throw new Error(`Cannot sign batch for ${senderVk}. No signing key provided.`) - let nonceResponse = await this.getStartingNonce(senderVk); - let txBatch = this.setBatchNonces(nonceResponse, senderBatch); - this.signBatch(txBatch, keyDict[senderVk]); - this.sendBatch(txBatch).then(sentList => { - sentTransactions = [...sentTransactions, ...sentList]; - resolver(); - }); - }) - })); - - try{ - return Promise.all(sentTransactions) - }catch (e){} - finally{ - this.running = false; - this.processOverflow(); - } - } - setBatchNonces(nonceResult, txList){ - return txList.map((txInfo, index) => { - txInfo.nonce = nonceResult.nonce + index; - txInfo.processor = nonceResult.processor; - return new TransactionBuilder({hosts: [nonceResult.masternode]}, txInfo) - }).sort((a, b) => a.nonce - b.nonce) - } - signBatch(txBatch, key){ - txBatch.forEach(txBuilder => txBuilder.sign(key)); - } - sendBatch(txBatch){ - let resolvedTransactions = []; - return new Promise(resolver => { - const resolve = (index) => { - if ((index + 1) === txBatch.length) resolver(resolvedTransactions); - }; - txBatch.forEach((txBuilder, index) => { - const delayedSend = () => { - resolvedTransactions[index] = txBuilder.send().then(() => {return txBuilder}); - resolve(index); - }; - setTimeout(delayedSend, 1200 * index); - }); - }) - } -} - -const { validateTypes: validateTypes$5, assertTypes: assertTypes$1 } = validators; - -class Keystore { - /** - * Lamden Keystores - * - * This Class will create a lamden keystore instance - * - * @param {Object|undefined} arg constructor argument - * @param {String|undefined} arg.key Create an instance and load it with one private key - * @param {String|undefined} arg.keyList Create an instance and load it with an array of private keys - * @param {String|undefined} arg.keystoreData Create an instance from an existing keystore file data - * @return {Keystore} - */ - constructor(arg = undefined) { - this.KEYSTORE_VERSION = "1.0"; - this.password = null; - this.encryptedData = null; - - this.keyList = (() => { - let keyList = []; - let outerClass = this; - let wallets = []; - - const addKey = (key) => { - keyList.push(key); - createWallets(); - }; - const deleteKey = (position) => { - keyList.splice(position, 1); - createWallets(); - }; - const clearKeys = () => { - keyList = []; - createWallets(); - }; - const numOfKeys = () => keyList.length; - const createWallets = () => { - wallets = []; - keyList.forEach(keyInfo => { - let newWallet = create_wallet({sk: keyInfo.sk, keepPrivate: true}); - newWallet = {...newWallet, ...keyInfo}; - delete newWallet.sk; - wallets.push(newWallet); - }); - }; - const createKeystore = (password, hint = undefined) => { - return JSON.stringify({ - data: encryptObject(password, {version: outerClass.KEYSTORE_VERSION, keyList}), - w: !hint ? "" : encryptStrHash('n1ahcKc0lb', hint), - }); - }; - const decryptKeystore = (password, data) => { - let decrypted = decryptObject(password, data); - if (decrypted) { - assertTypes$1.isArray(decrypted.keyList); - decrypted.keyList.forEach(keyInfo => assertTypes$1.isStringWithValue(keyInfo.sk)); - decrypted.keyList.forEach(keyInfo => addKey(keyInfo)); - outerClass.version = decrypted.version; - } else { - throw new Error("Incorrect Keystore Password.") - } - }; - - return { - getWallets: () => wallets, - getWallet: (vk) => wallets.find(wallet => wallet.vk === vk), - addKey, - clearKeys, - numOfKeys, - deleteKey, - createKeystore, - decryptKeystore - } - })(); - - if (arg){ - if (arg.key) this.addKey(arg.key); - if (arg.keyList) this.addKeys(arg.keyList); - if (arg.keystoreData) this.addKeystoreData(arg.keystoreData); - } - } - /** - * Add a list of keys to add to the keystore - * @param {Array.} keyList An array of 32 character long Lamden private keys - */ - addKeys(keyList){ - assertTypes$1.isArray(keyList); - keyList.forEach(key => this.addKey(key)); - } - /** - * Add a key to the keystore - * @param {string} key A 32 character long Lamden private key - */ - addKey(keyInfo){ - assertTypes$1.isObjectWithKeys(keyInfo); - assertTypes$1.isStringWithValue(keyInfo.sk); - if (validateTypes$5.isStringWithValue(keyInfo.vk)) delete keyInfo.vk; - this.keyList.addKey(keyInfo); - } - /** - * Load the keystore with the data from an existing keystore - * @param {string} keystoreData The contents of an existing encrypted keystore file - */ - addKeystoreData(keystoreData){ - if (validateTypes$5.isString(keystoreData)) keystoreData = JSON.parse(keystoreData); - if(this.validateKeyStore(keystoreData)){ - this.encryptedData = keystoreData; - } - } - /** - * Returns the password hint in a keystore file - * @param {String|undefined} keystoreData The contents of an existing encrypted keystore file if one wasn't supplied to the constructor - */ - getPasswordHint(keystoreData = undefined){ - if (!this.encryptedData && !keystoreData) throw new Error("No keystore data found.") - - if (keystoreData) { - if (validateTypes$5.isString(keystoreData)) keystoreData = JSON.parse(keystoreData); - } - else keystoreData = this.encryptedData; - - if (keystoreData.w) return decryptStrHash('n1ahcKc0lb', keystoreData.w); - else return "" - } - /** - * Removes a specific key from the keyList - * @param {Number} keyIndex The index of the key you want to remove - */ - deleteKey(keyIndex){ - assertTypes$1.isInteger(keyIndex); - if (this.keyList.numOfKeys() === 0) return - if (keyIndex < 0 || keyIndex >= this.keyList.numOfKeys()) throw new Error("Key index out of range.") - this.keyList.deleteKey(keyIndex); - } - /** - * Clears all keys from the keystore - */ - clearKeys(){ - this.keyList.clearKeys(); - } - /** - * Clears all keys from the keystore - * @return {Array.} An array of wallet objects - */ - get wallets() { - return this.keyList.getWallets() - } - /** - * Load the keystore with the data from an existing keystore - * @param {String} vk A 32 character long Lamden public key - * @return {Object} A wallet object - */ - getWallet(vk) { - return this.keyList.getWallet(vk) - } - /** - * Used to validate that a keystore is the proper Lamden Format (does not decrypt data) - * @param {String} keystoreData The contents of an existing encrypted keystore file - * @return {Boolean} valid - * @throws {Error} This is not a valid keystore file. - */ - validateKeyStore(keystoreData){ - assertTypes$1.isObjectWithKeys(keystoreData); - try{ - let encryptedData = JSON.parse(keystoreData.data); - if (!encryptedData.ct || !encryptedData.iv || !encryptedData.s){ - throw new Error("This is not a valid keystore file.") - } - } catch (e) { - throw new Error("This is not a valid keystore file.") - } - return true; - } - /** - * Create a Keystore text string from the keys contained in the Keystore instance - * @param {String} password A password to encrypt the data - * @param {String|undefined} hint An optional password hint. Not stored in clear text (obsured) but not encrypted with the password. - * @return {String} A JSON stringified object containing the encrypted data - * @throws {Error} Any errors from the encyption process - */ - createKeystore(password, hint = undefined) { - assertTypes$1.isStringWithValue(password); - if (hint){ - assertTypes$1.isStringWithValue(hint); - } - return this.keyList.createKeystore(password, hint) - } - /** - * Decrypt a keystore into a useable array of wallets. Any decrypted keys will be added to existing keys in the keystore. - * @param {String} password A password to encrypt the data - * @param {String|undefined} keystoreData The encrypted contents from a keystore file if not passed into the constructor. - * @throws {Error} Any errors from the encyption process - */ - decryptKeystore(password, keystoreData = undefined){ - if (keystoreData) this.addKeystoreData(keystoreData); - if (!this.encryptedData) throw new Error ("No keystoreData to decrypt.") - try{ - this.keyList.decryptKeystore(password, this.encryptedData.data); - }catch (e){ - throw new Error("Incorrect Keystore Password.") - } - } -} - -var index = { - TransactionBuilder, - TransactionBatcher, - Masternode_API: LamdenMasterNode_API, - Network, - wallet, - Keystore, - Encoder: encoder_1, - utils -}; - -module.exports = index; diff --git a/package-lock.json b/package-lock.json index df6e18a..1825336 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { "name": "lamden-js", - "version": "1.6.1", + "version": "2.0.0", "lockfileVersion": 2, "requires": true, "packages": { "": { - "version": "1.6.1", + "version": "2.0.0", "license": "MIT", "dependencies": { "assert": "1.4.1", @@ -19,15 +19,19 @@ }, "devDependencies": { "@babel/core": "^7.8.4", + "@rollup/plugin-alias": "^3.1.8", + "@rollup/plugin-commonjs": "^21.0.1", + "@rollup/plugin-node-resolve": "^13.0.6", + "buffer": "^6.0.3", "dotenv": "^8.2.0", "expect.js": "^0.3.1", + "koa": "^2.13.4", + "koa-static": "^5.0.0", "mocha": "^7.2.0", - "rollup": "^1.31.1", - "rollup-plugin-babel": "^4.3.3", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-node-builtins": "^2.0.0", - "rollup-plugin-node-globals": "^1.4.0", - "rollup-plugin-node-resolve": "^5.2.0" + "rollup": "^2.60.0", + "rollup-plugin-polyfill-node": "^0.7.0", + "rollup-plugin-terser": "^7.0.2", + "selenium-webdriver": "^3.6.0" } }, "node_modules/@babel/code-frame": { @@ -63,17 +67,12 @@ }, "engines": { "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" } }, "node_modules/@babel/core/node_modules/debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "deprecated": "Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)", "dev": true, "dependencies": { "ms": "^2.1.1" @@ -117,15 +116,6 @@ "@babel/types": "^7.8.3" } }, - "node_modules/@babel/helper-module-imports": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.8.3.tgz", - "integrity": "sha512-R0Bx3jippsbAEtzkpZ/6FIiuzOURPcMjHp+Z6xPe6DtApDJx+w7UYyOLanZqO8+wKR9G10s/FmHXvxaMd9s6Kg==", - "dev": true, - "dependencies": { - "@babel/types": "^7.8.3" - } - }, "node_modules/@babel/helper-split-export-declaration": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", @@ -135,6 +125,15 @@ "@babel/types": "^7.8.3" } }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.15.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", + "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helpers": { "version": "7.8.4", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.8.4.tgz", @@ -263,7 +262,6 @@ "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", - "deprecated": "Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)", "dev": true, "dependencies": { "ms": "^2.1.1" @@ -286,10 +284,173 @@ "to-fast-properties": "^2.0.0" } }, + "node_modules/@rollup/plugin-alias": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@rollup/plugin-alias/-/plugin-alias-3.1.8.tgz", + "integrity": "sha512-tf7HeSs/06wO2LPqKNY3Ckbvy0JRe7Jyn98bXnt/gfrxbe+AJucoNJlsEVi9sdgbQtXemjbakCpO/76JVgnHpA==", + "dev": true, + "dependencies": { + "slash": "^3.0.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-21.0.1.tgz", + "integrity": "sha512-EA+g22lbNJ8p5kuZJUYyhhDK7WgJckW5g4pNN7n4mAFUM96VuwUnNT3xr2Db2iCZPI1pJPbGyfT5mS9T1dHfMg==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "commondir": "^1.0.1", + "estree-walker": "^2.0.1", + "glob": "^7.1.6", + "is-reference": "^1.2.1", + "magic-string": "^0.25.7", + "resolve": "^1.17.0" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/@rollup/plugin-commonjs/node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dev": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.4" + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + }, + "node_modules/@rollup/plugin-inject": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-inject/-/plugin-inject-4.0.3.tgz", + "integrity": "sha512-lzMXmj0LZjd67MI+M8H9dk/oCxR0TYqYAdZ6ZOejWQLSUtud+FUPu4NCMAO8KyWWAalFo8ean7yFHCMvCNsCZw==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "estree-walker": "^2.0.1", + "magic-string": "^0.25.7" + } + }, + "node_modules/@rollup/plugin-inject/node_modules/estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "node_modules/@rollup/plugin-inject/node_modules/magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "dependencies": { + "sourcemap-codec": "^1.4.4" + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-13.0.6.tgz", + "integrity": "sha512-sFsPDMPd4gMqnh2gS0uIxELnoRUp5kBl5knxD2EO0778G1oOJv4G1vyT2cpWz75OU2jDVcXhjVUuTAczGyFNKA==", + "dev": true, + "dependencies": { + "@rollup/pluginutils": "^3.1.0", + "@types/resolve": "1.17.1", + "builtin-modules": "^3.1.0", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.19.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/@rollup/plugin-node-resolve/node_modules/@types/resolve": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", + "integrity": "sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@rollup/plugin-node-resolve/node_modules/resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "dependencies": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + }, + "node_modules/@rollup/pluginutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", + "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "dev": true, + "dependencies": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/@rollup/pluginutils/node_modules/estree-walker": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", + "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", + "dev": true + }, "node_modules/@types/estree": { - "version": "0.0.42", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.42.tgz", - "integrity": "sha512-K1DPVvnBCPxzD+G51/cxVIoc2X8uUVl1zpJeE6iKcgHMj4+tbat5Xu4TjV7v2QSDbIeAfLi2hIk+u2+s0MlpUQ==", + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", "dev": true }, "node_modules/@types/node": { @@ -298,25 +459,17 @@ "integrity": "sha512-uvilvAQbdJvnSBFcKJ2td4016urcGvsiR+N4dHGU87ml8O2Vl6l+ErOi9w0kXSPiwJ1AYlIW+0pDXDWWMOiWbw==", "dev": true }, - "node_modules/@types/resolve": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", - "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "node_modules/accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", "dev": true, "dependencies": { - "@types/node": "*" - } - }, - "node_modules/acorn": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.2.0.tgz", - "integrity": "sha512-apwXVmYVpQ34m/i71vrApRrRKCWQnZZF1+npOD0WV5xZFfwWOmKGQ2RWlfdy9vWITsenisM8M0Qeq8agcFHNiQ==", - "dev": true, - "bin": { - "acorn": "bin/acorn" + "mime-types": "~2.1.24", + "negotiator": "0.6.2" }, "engines": { - "node": ">=0.4.0" + "node": ">= 0.6" } }, "node_modules/ansi-colors": { @@ -371,24 +524,6 @@ "sprintf-js": "~1.0.2" } }, - "node_modules/asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "dev": true, - "dependencies": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - } - }, - "node_modules/asn1.js/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - }, "node_modules/assert": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", @@ -403,6 +538,12 @@ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "dev": true }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true + }, "node_modules/bignumber.js": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", @@ -436,12 +577,6 @@ "resolved": "https://registry.npmjs.org/@types/node/-/node-11.11.6.tgz", "integrity": "sha512-Exw4yUWMBXM3X+8oqzJNRqZSwUAaS4+7NdvHqQuFi/d+synz++xmX3QIf+BFqneW8N31R8Ky+sikfZUXq07ggQ==" }, - "node_modules/bn.js": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.1.3.tgz", - "integrity": "sha512-GkTiFpjFtUzU9CbMeJ5iazkCzGL3jrhzerzZIuqLABjbwRaFt33I9tUdSNryIptM+RxDet6OKm2WnLXzW51KsQ==", - "dev": true - }, "node_modules/brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -464,132 +599,26 @@ "node": ">=8" } }, - "node_modules/brorand": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", - "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", - "dev": true - }, "node_modules/browser-stdout": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", "dev": true }, - "node_modules/browserify-aes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", - "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", - "dev": true, - "dependencies": { - "buffer-xor": "^1.0.3", - "cipher-base": "^1.0.0", - "create-hash": "^1.1.0", - "evp_bytestokey": "^1.0.3", - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/browserify-cipher": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", - "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", - "dev": true, - "dependencies": { - "browserify-aes": "^1.0.4", - "browserify-des": "^1.0.0", - "evp_bytestokey": "^1.0.0" - } - }, - "node_modules/browserify-des": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", - "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", - "dev": true, - "dependencies": { - "cipher-base": "^1.0.1", - "des.js": "^1.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "node_modules/browserify-rsa": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", - "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", - "dev": true, - "dependencies": { - "bn.js": "^5.0.0", - "randombytes": "^2.0.1" - } - }, - "node_modules/browserify-sign": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", - "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", - "dev": true, - "dependencies": { - "bn.js": "^5.1.1", - "browserify-rsa": "^4.0.1", - "create-hash": "^1.2.0", - "create-hmac": "^1.1.7", - "elliptic": "^6.5.3", - "inherits": "^2.0.4", - "parse-asn1": "^5.1.5", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" - } - }, - "node_modules/browserify-sign/node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "node_modules/browserify-sign/node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", "dev": true, "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" } }, - "node_modules/browserify-sign/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/buffer-es6": { - "version": "4.9.3", - "resolved": "https://registry.npmjs.org/buffer-es6/-/buffer-es6-4.9.3.tgz", - "integrity": "sha1-8mNHuC33b9N+GLy1KIxJcM/VxAQ=", - "dev": true - }, - "node_modules/buffer-xor": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", - "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "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==", "dev": true }, "node_modules/builtin-modules": { @@ -601,6 +630,19 @@ "node": ">=6" } }, + "node_modules/cache-content-type": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-content-type/-/cache-content-type-1.0.1.tgz", + "integrity": "sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==", + "dev": true, + "dependencies": { + "mime-types": "^2.1.18", + "ylru": "^1.2.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -712,6 +754,16 @@ "node": ">=6" } }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true, + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, "node_modules/color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", @@ -727,12 +779,45 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, + "node_modules/content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "dev": true, + "dependencies": { + "safe-buffer": "5.1.2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", @@ -742,20 +827,23 @@ "safe-buffer": "~5.1.1" } }, - "node_modules/create-ecdh": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", - "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", + "node_modules/cookies": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.8.0.tgz", + "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", "dev": true, "dependencies": { - "bn.js": "^4.1.0", - "elliptic": "^6.5.3" + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" } }, - "node_modules/create-ecdh/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "dev": true }, "node_modules/create-hash": { @@ -783,33 +871,10 @@ "sha.js": "^2.4.8" } }, - "node_modules/crypto-browserify": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", - "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", - "dev": true, - "dependencies": { - "browserify-cipher": "^1.0.0", - "browserify-sign": "^4.0.0", - "create-ecdh": "^4.0.0", - "create-hash": "^1.1.0", - "create-hmac": "^1.1.0", - "diffie-hellman": "^5.0.0", - "inherits": "^2.0.1", - "pbkdf2": "^3.0.3", - "public-encrypt": "^4.0.0", - "randombytes": "^2.0.0", - "randomfill": "^1.0.3" - }, - "engines": { - "node": "*" - } - }, "node_modules/debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "deprecated": "Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)", "dev": true, "dependencies": { "ms": "^2.1.1" @@ -824,6 +889,21 @@ "node": ">=0.10.0" } }, + "node_modules/deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", + "dev": true + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/define-properties": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", @@ -836,16 +916,27 @@ "node": ">= 0.4" } }, - "node_modules/des.js": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", - "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", "dev": true, - "dependencies": { - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0" + "engines": { + "node": ">= 0.8" } }, + "node_modules/destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "dev": true + }, "node_modules/diff": { "version": "3.5.0", "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", @@ -855,23 +946,6 @@ "node": ">=0.3.1" } }, - "node_modules/diffie-hellman": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", - "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", - "dev": true, - "dependencies": { - "bn.js": "^4.1.0", - "miller-rabin": "^4.0.0", - "randombytes": "^2.0.0" - } - }, - "node_modules/diffie-hellman/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - }, "node_modules/dotenv": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz", @@ -912,31 +986,10 @@ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==" }, - "node_modules/elliptic": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", - "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", - "dev": true, - "dependencies": { - "bn.js": "^4.11.9", - "brorand": "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - "inherits": "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - } - }, - "node_modules/elliptic/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - }, - "node_modules/elliptic/node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", "dev": true }, "node_modules/emoji-regex": { @@ -945,6 +998,15 @@ "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/es-abstract": { "version": "1.17.5", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.5.tgz", @@ -965,9 +1027,6 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/es-to-primitive": { @@ -982,11 +1041,14 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, "node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -1009,12 +1071,6 @@ "node": ">=4" } }, - "node_modules/estree-walker": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", - "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", - "dev": true - }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -1024,16 +1080,6 @@ "node": ">=0.10.0" } }, - "node_modules/evp_bytestokey": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", - "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", - "dev": true, - "dependencies": { - "md5.js": "^1.3.4", - "safe-buffer": "^5.1.1" - } - }, "node_modules/expect.js": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/expect.js/-/expect.js-0.3.1.tgz", @@ -1068,7 +1114,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/flat/-/flat-4.1.0.tgz", "integrity": "sha512-Px/TiLIznH7gEDlPXcUD4KnBusa6kR6ayRUVcnEAbreRIuhkqow/mun59BuRXwoYk7ZQOLW1ZM05ilIvK38hFw==", - "deprecated": "Fixed a prototype pollution security issue in 4.1.0, please upgrade to ^4.1.1 or ^5.0.1.", "dev": true, "dependencies": { "is-buffer": "~2.0.3" @@ -1077,6 +1122,15 @@ "flat": "cli.js" } }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -1087,9 +1141,7 @@ "version": "2.1.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.1.3.tgz", "integrity": "sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ==", - "deprecated": "\"Please update to latest v2.3 or v2.2\"", "dev": true, - "hasInstallScript": true, "optional": true, "os": [ "darwin" @@ -1191,10 +1243,25 @@ } }, "node_modules/has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", "dev": true, + "dependencies": { + "has-symbols": "^1.0.2" + }, "engines": { "node": ">= 0.4" }, @@ -1236,37 +1303,7 @@ "node_modules/hash-base/node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, - "node_modules/hash.js": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", - "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", - "dev": true, - "dependencies": { - "inherits": "^2.0.3", - "minimalistic-assert": "^1.0.1" - } - }, - "node_modules/hash.js/node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" }, "node_modules/he": { "version": "1.2.0", @@ -1277,17 +1314,62 @@ "he": "bin/he" } }, - "node_modules/hmac-drbg": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", - "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "node_modules/http-assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", + "dev": true, + "dependencies": { + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", "dev": true, "dependencies": { - "hash.js": "^1.0.3", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.1" + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-errors/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true, + "engines": { + "node": ">= 0.6" } }, + "node_modules/http-errors/node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "dev": true + }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps=", + "dev": true + }, "node_modules/inflight": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", @@ -1331,9 +1413,15 @@ "dev": true, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.0.tgz", + "integrity": "sha512-vd15qHsaqrRL7dtH6QNuy0ndJmRDrS9HAM1CAiSifNUFv4x1a0CCVsj18hJ1mShxIG6T2i1sO78MkP56r0nYRw==", + "dev": true, + "dependencies": { + "has": "^1.0.3" } }, "node_modules/is-date-object": { @@ -1343,9 +1431,6 @@ "dev": true, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-extglob": { @@ -1366,6 +1451,21 @@ "node": ">=4" } }, + "node_modules/is-generator-function": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz", + "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", + "dev": true, + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -1393,21 +1493,6 @@ "node": ">=0.12.0" } }, - "node_modules/is-reference": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz", - "integrity": "sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw==", - "dev": true, - "dependencies": { - "@types/estree": "0.0.39" - } - }, - "node_modules/is-reference/node_modules/@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", - "dev": true - }, "node_modules/is-regex": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.0.tgz", @@ -1418,9 +1503,6 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/is-symbol": { @@ -1433,17 +1515,55 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, + "node_modules/jest-worker": { + "version": "26.6.2", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", + "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", + "dev": true, + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^7.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, + "node_modules/jest-worker/node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -1490,6 +1610,166 @@ "node": ">=6" } }, + "node_modules/jszip": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.7.1.tgz", + "integrity": "sha512-ghL0tz1XG9ZEmRMcEN2vt7xabrDdqHHeykgARpmZ0BiIctWxM47Vt63ZO2dnp4QYt/xJVLLy5Zv1l/xRdh2byg==", + "dev": true, + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "set-immediate-shim": "~1.0.1" + } + }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "dev": true, + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa": { + "version": "2.13.4", + "resolved": "https://registry.npmjs.org/koa/-/koa-2.13.4.tgz", + "integrity": "sha512-43zkIKubNbnrULWlHdN5h1g3SEKXOEzoAlRsHOTFpnlDu8JlAOZSMJBLULusuXRequboiwJcj5vtYXKB3k7+2g==", + "dev": true, + "dependencies": { + "accepts": "^1.3.5", + "cache-content-type": "^1.0.0", + "content-disposition": "~0.5.2", + "content-type": "^1.0.4", + "cookies": "~0.8.0", + "debug": "^4.3.2", + "delegates": "^1.0.0", + "depd": "^2.0.0", + "destroy": "^1.0.4", + "encodeurl": "^1.0.2", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.3.0", + "http-errors": "^1.6.3", + "is-generator-function": "^1.0.7", + "koa-compose": "^4.1.0", + "koa-convert": "^2.0.0", + "on-finished": "^2.3.0", + "only": "~0.0.2", + "parseurl": "^1.3.2", + "statuses": "^1.5.0", + "type-is": "^1.6.16", + "vary": "^1.1.2" + }, + "engines": { + "node": "^4.8.4 || ^6.10.1 || ^7.10.1 || >= 8.1.4" + } + }, + "node_modules/koa-compose": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "dev": true + }, + "node_modules/koa-convert": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/koa-convert/-/koa-convert-2.0.0.tgz", + "integrity": "sha512-asOvN6bFlSnxewce2e/DK3p4tltyfC4VM7ZwuTuepI7dEQVcvpyFuBcEARu1+Hxg8DIwytce2n7jrZtRlPrARA==", + "dev": true, + "dependencies": { + "co": "^4.6.0", + "koa-compose": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/koa-send": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/koa-send/-/koa-send-5.0.1.tgz", + "integrity": "sha512-tmcyQ/wXXuxpDxyNXv5yNNkdAMdFRqwtegBXUaowiQzUKqJehttS0x2j0eOZDQAyloAth5w6wwBImnFzkUz3pQ==", + "dev": true, + "dependencies": { + "debug": "^4.1.1", + "http-errors": "^1.7.3", + "resolve-path": "^1.4.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/koa-send/node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/koa-send/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/koa-static": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/koa-static/-/koa-static-5.0.0.tgz", + "integrity": "sha512-UqyYyH5YEXaJrf9S8E23GoJFQZXkBVJ9zYYMPGz919MSX1KuvAcycIuS0ci150HCoPf4XQVhQ84Qf8xRPWxFaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.1.0", + "koa-send": "^5.0.0" + }, + "engines": { + "node": ">= 7.6.0" + } + }, + "node_modules/koa/node_modules/debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/koa/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, + "dependencies": { + "immediate": "~3.0.5" + } + }, "node_modules/locate-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", @@ -1521,15 +1801,6 @@ "node": ">=8" } }, - "node_modules/magic-string": { - "version": "0.25.6", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.6.tgz", - "integrity": "sha512-3a5LOMSGoCTH5rbqobC2HuDNRtE2glHZ8J7pK+QZYppyWA36yuNpsX994rIY2nCuyP7CZYy7lQq/X2jygiZ89g==", - "dev": true, - "dependencies": { - "sourcemap-codec": "^1.4.4" - } - }, "node_modules/md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -1540,36 +1811,41 @@ "safe-buffer": "^5.1.2" } }, - "node_modules/miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", "dev": true, - "dependencies": { - "bn.js": "^4.0.0", - "brorand": "^1.0.1" - }, - "bin": { - "miller-rabin": "bin/miller-rabin" + "engines": { + "node": ">= 0.6" } }, - "node_modules/miller-rabin/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "dev": true + "node_modules/mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", + "dev": true, + "engines": { + "node": ">= 0.6" + } }, - "node_modules/minimalistic-crypto-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", - "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", - "dev": true + "node_modules/mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dev": true, + "dependencies": { + "mime-db": "1.51.0" + }, + "engines": { + "node": ">= 0.6" + } }, "node_modules/minimatch": { "version": "3.0.4", @@ -1638,10 +1914,6 @@ }, "engines": { "node": ">= 8.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mochajs" } }, "node_modules/ms": { @@ -1650,6 +1922,15 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, + "node_modules/negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/node-cryptojs-aes": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-cryptojs-aes/-/node-cryptojs-aes-0.4.0.tgz", @@ -1689,10 +1970,7 @@ "version": "1.7.0", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.7.0.tgz", "integrity": "sha512-a7pEHdh1xKIAgTySUGgLMx/xwDZskN1Ud6egYYN3EdRW4ZMPNEDUTF+hwy2LUC+Bl+SyLXANnwz/jyh/qutKUw==", - "dev": true, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } + "dev": true }, "node_modules/object-keys": { "version": "1.1.1", @@ -1729,20 +2007,44 @@ }, "engines": { "node": ">= 0.8" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "node_modules/on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "dependencies": { "wrappy": "1" } }, + "node_modules/only": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/only/-/only-0.0.2.tgz", + "integrity": "sha1-Kv3oTQPlC5qO3EROMGEKcCle37Q=", + "dev": true + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/p-limit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", @@ -1753,9 +2055,6 @@ }, "engines": { "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-locate": { @@ -1779,17 +2078,19 @@ "node": ">=6" } }, - "node_modules/parse-asn1": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", - "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", "dev": true, - "dependencies": { - "asn1.js": "^5.2.0", - "browserify-aes": "^1.0.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" + "engines": { + "node": ">= 0.8" } }, "node_modules/path-exists": { @@ -1838,35 +2139,12 @@ "dev": true, "engines": { "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/process-es6": { - "version": "0.11.6", - "resolved": "https://registry.npmjs.org/process-es6/-/process-es6-0.11.6.tgz", - "integrity": "sha1-xrs4n5qVH4K9TrFpYAEFvS/5x3g=", - "dev": true - }, - "node_modules/public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "dev": true, - "dependencies": { - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" } }, - "node_modules/public-encrypt/node_modules/bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "dev": true }, "node_modules/randombytes": { @@ -1877,16 +2155,27 @@ "safe-buffer": "^5.1.0" } }, - "node_modules/randomfill": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", - "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "node_modules/readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "dev": true, "dependencies": { - "randombytes": "^2.0.5", - "safe-buffer": "^5.1.0" + "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" } }, + "node_modules/readable-stream/node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + }, "node_modules/readdirp": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.2.0.tgz", @@ -1921,142 +2210,151 @@ "dev": true, "dependencies": { "path-parse": "^1.0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/ripemd160": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", - "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", - "dependencies": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1" - } - }, - "node_modules/rollup": { - "version": "1.31.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.31.1.tgz", - "integrity": "sha512-2JREN1YdrS/kpPzEd33ZjtuNbOuBC3ePfuZBdKEybvqcEcszW1ckyVqzcEiEe0nE8sqHK+pbJg+PsAgRJ8+1dg==", + "node_modules/resolve-path": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/resolve-path/-/resolve-path-1.4.0.tgz", + "integrity": "sha1-xL2p9e+y/OZSR4c6s2u02DT+Fvc=", "dev": true, "dependencies": { - "@types/estree": "*", - "@types/node": "*", - "acorn": "^7.1.0" + "http-errors": "~1.6.2", + "path-is-absolute": "1.0.1" }, - "bin": { - "rollup": "dist/bin/rollup" + "engines": { + "node": ">= 0.8" } }, - "node_modules/rollup-plugin-babel": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/rollup-plugin-babel/-/rollup-plugin-babel-4.3.3.tgz", - "integrity": "sha512-tKzWOCmIJD/6aKNz0H1GMM+lW1q9KyFubbWzGiOG540zxPPifnEAHTZwjo0g991Y+DyOZcLqBgqOdqazYE5fkw==", - "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-babel.", + "node_modules/resolve-path/node_modules/depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", "dev": true, - "dependencies": { - "@babel/helper-module-imports": "^7.0.0", - "rollup-pluginutils": "^2.8.1" - }, - "peerDependencies": { - "@babel/core": "7 || ^7.0.0-rc.2", - "rollup": ">=0.60.0 <2" + "engines": { + "node": ">= 0.6" } }, - "node_modules/rollup-plugin-commonjs": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-commonjs/-/rollup-plugin-commonjs-10.1.0.tgz", - "integrity": "sha512-jlXbjZSQg8EIeAAvepNwhJj++qJWNJw1Cl0YnOqKtP5Djx+fFGkp3WRh+W0ASCaFG5w1jhmzDxgu3SJuVxPF4Q==", - "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-commonjs.", + "node_modules/resolve-path/node_modules/http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", "dev": true, "dependencies": { - "estree-walker": "^0.6.1", - "is-reference": "^1.1.2", - "magic-string": "^0.25.2", - "resolve": "^1.11.0", - "rollup-pluginutils": "^2.8.1" + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" }, - "peerDependencies": { - "rollup": ">=1.12.0" + "engines": { + "node": ">= 0.6" } }, - "node_modules/rollup-plugin-node-builtins": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-builtins/-/rollup-plugin-node-builtins-2.0.0.tgz", - "integrity": "sha1-xvKR4WfpVg6+qH+/3Bq7RLCnweY=", + "node_modules/resolve-path/node_modules/inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "node_modules/resolve-path/node_modules/setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + }, + "node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "dev": true, "dependencies": { - "buffer-es6": "^4.9.2", - "crypto-browserify": "^3.11.0", - "process-es6": "^0.11.2" + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" } }, - "node_modules/rollup-plugin-node-globals": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-globals/-/rollup-plugin-node-globals-1.4.0.tgz", - "integrity": "sha512-xRkB+W/m1KLIzPUmG0ofvR+CPNcvuCuNdjVBVS7ALKSxr3EDhnzNceGkGi1m8MToSli13AzKFYH4ie9w3I5L3g==", - "dev": true, + "node_modules/ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", "dependencies": { - "acorn": "^5.7.3", - "buffer-es6": "^4.9.3", - "estree-walker": "^0.5.2", - "magic-string": "^0.22.5", - "process-es6": "^0.11.6", - "rollup-pluginutils": "^2.3.1" + "hash-base": "^3.0.0", + "inherits": "^2.0.1" } }, - "node_modules/rollup-plugin-node-globals/node_modules/acorn": { - "version": "5.7.4", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", - "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", + "node_modules/rollup": { + "version": "2.60.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.60.0.tgz", + "integrity": "sha512-cHdv9GWd58v58rdseC8e8XIaPUo8a9cgZpnCMMDGZFDZKEODOiPPEQFXLriWr/TjXzhPPmG5bkAztPsOARIcGQ==", "dev": true, "bin": { - "acorn": "bin/acorn" + "rollup": "dist/bin/rollup" }, "engines": { - "node": ">=0.4.0" + "node": ">=10.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" } }, - "node_modules/rollup-plugin-node-globals/node_modules/estree-walker": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.5.2.tgz", - "integrity": "sha512-XpCnW/AE10ws/kDAs37cngSkvgIR8aN3G0MS85m7dUpuK2EREo9VJ00uvw6Dg/hXEpfsE1I1TvJOJr+Z+TL+ig==", - "dev": true + "node_modules/rollup-plugin-polyfill-node": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-polyfill-node/-/rollup-plugin-polyfill-node-0.7.0.tgz", + "integrity": "sha512-iJLZDfvxcQh3SpC0OiYlZG9ik26aRM29hiC2sARbAPXYunB8rzW8GtVaWuJgiCtX1hNAo/OaYvVXfPp15fMs7g==", + "dev": true, + "dependencies": { + "@rollup/plugin-inject": "^4.0.0" + } }, - "node_modules/rollup-plugin-node-globals/node_modules/magic-string": { - "version": "0.22.5", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.22.5.tgz", - "integrity": "sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w==", + "node_modules/rollup-plugin-terser": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz", + "integrity": "sha512-w3iIaU4OxcF52UUXiZNsNeuXIMDvFrr+ZXK6bFZ0Q60qyVfq4uLptoS4bbq3paG3x216eQllFZX7zt6TIImguQ==", "dev": true, "dependencies": { - "vlq": "^0.2.2" + "@babel/code-frame": "^7.10.4", + "jest-worker": "^26.2.1", + "serialize-javascript": "^4.0.0", + "terser": "^5.0.0" } }, - "node_modules/rollup-plugin-node-resolve": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-5.2.0.tgz", - "integrity": "sha512-jUlyaDXts7TW2CqQ4GaO5VJ4PwwaV8VUGA7+km3n6k6xtOEacf61u0VXwN80phY/evMcaS+9eIeJ9MOyDxt5Zw==", - "deprecated": "This package has been deprecated and is no longer maintained. Please use @rollup/plugin-node-resolve.", + "node_modules/rollup-plugin-terser/node_modules/@babel/code-frame": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.0.tgz", + "integrity": "sha512-IF4EOMEV+bfYwOmNxGzSnjR2EmQod7f1UXOpZM3l4i4o4QNwzjtJAu/HxdjHq0aYBvdqMuQEY1eg0nqW9ZPORA==", "dev": true, "dependencies": { - "@types/resolve": "0.0.8", - "builtin-modules": "^3.1.0", - "is-module": "^1.0.0", - "resolve": "^1.11.1", - "rollup-pluginutils": "^2.8.1" + "@babel/highlight": "^7.16.0" }, - "peerDependencies": { - "rollup": ">=1.11.0" + "engines": { + "node": ">=6.9.0" } }, - "node_modules/rollup-pluginutils": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", - "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", + "node_modules/rollup-plugin-terser/node_modules/@babel/highlight": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.0.tgz", + "integrity": "sha512-t8MH41kUQylBtu2+4IQA3atqevA2lRgqA2wyVB/YiWmsDSuylZZuXOUy9ric30hfzauEFfdsuk/eXTRrGrfd0g==", "dev": true, "dependencies": { - "estree-walker": "^0.6.1" + "@babel/helper-validator-identifier": "^7.15.7", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/rollup/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/safe-buffer": { @@ -2064,12 +2362,28 @@ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "node_modules/sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true }, + "node_modules/selenium-webdriver": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-3.6.0.tgz", + "integrity": "sha512-WH7Aldse+2P5bbFBO4Gle/nuQOdVwpHMTL6raL3uuBj/vPG07k6uzt3aiahu352ONBr5xXh0hDlM3LhtXPOC4Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "jszip": "^3.1.3", + "rimraf": "^2.5.4", + "tmp": "0.0.30", + "xml2js": "^0.4.17" + }, + "engines": { + "node": ">= 6.9.0" + } + }, "node_modules/semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", @@ -2079,12 +2393,36 @@ "semver": "bin/semver" } }, + "node_modules/serialize-javascript": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", + "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", + "dev": true, + "dependencies": { + "randombytes": "^2.1.0" + } + }, "node_modules/set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "node_modules/set-immediate-shim": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", + "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, "node_modules/sha.js": { "version": "2.4.11", "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", @@ -2097,6 +2435,15 @@ "sha.js": "bin.js" } }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, "node_modules/source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", @@ -2106,6 +2453,25 @@ "node": ">=0.10.0" } }, + "node_modules/source-map-support": { + "version": "0.5.20", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.20.tgz", + "integrity": "sha512-n1lZZ8Ve4ksRqizaBQgxXDgKwttHDhyfQjA6YZZn8+AroHbsIz+JjwxQDxbp+7y5OYCI8t1Yk7etjD9CRd2hIw==", + "dev": true, + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/source-map-support/node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/sourcemap-codec": { "version": "1.4.8", "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", @@ -2118,6 +2484,15 @@ "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -2147,9 +2522,6 @@ "dependencies": { "define-properties": "^1.1.3", "es-abstract": "^1.17.5" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimleft": { @@ -2164,9 +2536,6 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimright": { @@ -2181,9 +2550,6 @@ }, "engines": { "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimstart": { @@ -2194,9 +2560,6 @@ "dependencies": { "define-properties": "^1.1.3", "es-abstract": "^1.17.5" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" } }, "node_modules/strip-ansi": { @@ -2232,6 +2595,44 @@ "node": ">=6" } }, + "node_modules/terser": { + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.9.0.tgz", + "integrity": "sha512-h5hxa23sCdpzcye/7b8YqbE5OwKca/ni0RQz1uRX3tGh8haaGHqcuSqbGRybuAKNdntZ0mDgFNXPJ48xQ2RXKQ==", + "dev": true, + "dependencies": { + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/terser/node_modules/source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/tmp": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.30.tgz", + "integrity": "sha1-ckGdSovn1s51FI/YsyTlk6cRwu0=", + "dev": true, + "dependencies": { + "os-tmpdir": "~1.0.1" + }, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", @@ -2253,11 +2654,42 @@ "node": ">=8.0" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "dev": true, + "engines": { + "node": ">=0.6.x" + } + }, "node_modules/tweetnacl": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.1.tgz", "integrity": "sha512-kcoMoKTPYnoeS50tzoqjPY3Uv9axeuuFAZY9M/9zFnhoVvRfxz9K29IMPD7jGmt2c8SW7i3gT9WqDl2+nV7p4A==" }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/types-validate-assert": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/types-validate-assert/-/types-validate-assert-1.0.1.tgz", @@ -2276,11 +2708,14 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, - "node_modules/vlq": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/vlq/-/vlq-0.2.3.tgz", - "integrity": "sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow==", - "dev": true + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "dev": true, + "engines": { + "node": ">= 0.8" + } }, "node_modules/which": { "version": "1.3.1", @@ -2364,6 +2799,28 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, + "node_modules/xml2js": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", + "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "dev": true, + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, "node_modules/y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", @@ -2446,6 +2903,15 @@ "engines": { "node": ">=6" } + }, + "node_modules/ylru": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ylru/-/ylru-1.2.1.tgz", + "integrity": "sha512-faQrqNMzcPCHGVC2aaOINk13K+aaBDUPjGWl0teOXywElLjyVAB6Oe2jj62jHYtwsU49jXhScYbvPENK+6zAvQ==", + "dev": true, + "engines": { + "node": ">= 4.0.0" + } } }, "dependencies": { @@ -2530,15 +2996,6 @@ "@babel/types": "^7.8.3" } }, - "@babel/helper-module-imports": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.8.3.tgz", - "integrity": "sha512-R0Bx3jippsbAEtzkpZ/6FIiuzOURPcMjHp+Z6xPe6DtApDJx+w7UYyOLanZqO8+wKR9G10s/FmHXvxaMd9s6Kg==", - "dev": true, - "requires": { - "@babel/types": "^7.8.3" - } - }, "@babel/helper-split-export-declaration": { "version": "7.8.3", "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.8.3.tgz", @@ -2548,6 +3005,12 @@ "@babel/types": "^7.8.3" } }, + "@babel/helper-validator-identifier": { + "version": "7.15.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz", + "integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==", + "dev": true + }, "@babel/helpers": { "version": "7.8.4", "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.8.4.tgz", @@ -2684,44 +3147,195 @@ "to-fast-properties": "^2.0.0" } }, - "@types/estree": { - "version": "0.0.42", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.42.tgz", - "integrity": "sha512-K1DPVvnBCPxzD+G51/cxVIoc2X8uUVl1zpJeE6iKcgHMj4+tbat5Xu4TjV7v2QSDbIeAfLi2hIk+u2+s0MlpUQ==", - "dev": true - }, - "@types/node": { - "version": "13.7.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.7.2.tgz", - "integrity": "sha512-uvilvAQbdJvnSBFcKJ2td4016urcGvsiR+N4dHGU87ml8O2Vl6l+ErOi9w0kXSPiwJ1AYlIW+0pDXDWWMOiWbw==", - "dev": true - }, - "@types/resolve": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz", - "integrity": "sha512-auApPaJf3NPfe18hSoJkp8EbZzer2ISk7o8mCC3M9he/a04+gbMF97NkpD2S8riMGvm4BMRI59/SZQSaLTKpsQ==", + "@rollup/plugin-alias": { + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/@rollup/plugin-alias/-/plugin-alias-3.1.8.tgz", + "integrity": "sha512-tf7HeSs/06wO2LPqKNY3Ckbvy0JRe7Jyn98bXnt/gfrxbe+AJucoNJlsEVi9sdgbQtXemjbakCpO/76JVgnHpA==", "dev": true, "requires": { - "@types/node": "*" + "slash": "^3.0.0" } }, - "acorn": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-7.2.0.tgz", - "integrity": "sha512-apwXVmYVpQ34m/i71vrApRrRKCWQnZZF1+npOD0WV5xZFfwWOmKGQ2RWlfdy9vWITsenisM8M0Qeq8agcFHNiQ==", - "dev": true - }, - "ansi-colors": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz", - "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==", - "dev": true - }, - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true + "@rollup/plugin-commonjs": { + "version": "21.0.1", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-21.0.1.tgz", + "integrity": "sha512-EA+g22lbNJ8p5kuZJUYyhhDK7WgJckW5g4pNN7n4mAFUM96VuwUnNT3xr2Db2iCZPI1pJPbGyfT5mS9T1dHfMg==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.1.0", + "commondir": "^1.0.1", + "estree-walker": "^2.0.1", + "glob": "^7.1.6", + "is-reference": "^1.2.1", + "magic-string": "^0.25.7", + "resolve": "^1.17.0" + }, + "dependencies": { + "estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "requires": { + "@types/estree": "*" + } + }, + "magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.4" + } + }, + "resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "requires": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + } + } + }, + "@rollup/plugin-inject": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-inject/-/plugin-inject-4.0.3.tgz", + "integrity": "sha512-lzMXmj0LZjd67MI+M8H9dk/oCxR0TYqYAdZ6ZOejWQLSUtud+FUPu4NCMAO8KyWWAalFo8ean7yFHCMvCNsCZw==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.1.0", + "estree-walker": "^2.0.1", + "magic-string": "^0.25.7" + }, + "dependencies": { + "estree-walker": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", + "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", + "dev": true + }, + "magic-string": { + "version": "0.25.7", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz", + "integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==", + "dev": true, + "requires": { + "sourcemap-codec": "^1.4.4" + } + } + } + }, + "@rollup/plugin-node-resolve": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-13.0.6.tgz", + "integrity": "sha512-sFsPDMPd4gMqnh2gS0uIxELnoRUp5kBl5knxD2EO0778G1oOJv4G1vyT2cpWz75OU2jDVcXhjVUuTAczGyFNKA==", + "dev": true, + "requires": { + "@rollup/pluginutils": "^3.1.0", + "@types/resolve": "1.17.1", + "builtin-modules": "^3.1.0", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.19.0" + }, + "dependencies": { + "@types/resolve": { + "version": "1.17.1", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", + "integrity": "sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw==", + "dev": true, + "requires": { + "@types/node": "*" + } + }, + "resolve": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz", + "integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==", + "dev": true, + "requires": { + "is-core-module": "^2.2.0", + "path-parse": "^1.0.6" + } + } + } + }, + "@rollup/pluginutils": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", + "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", + "dev": true, + "requires": { + "@types/estree": "0.0.39", + "estree-walker": "^1.0.1", + "picomatch": "^2.2.2" + }, + "dependencies": { + "estree-walker": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", + "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", + "dev": true + } + } + }, + "@types/estree": { + "version": "0.0.39", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", + "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", + "dev": true + }, + "@types/node": { + "version": "13.7.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.7.2.tgz", + "integrity": "sha512-uvilvAQbdJvnSBFcKJ2td4016urcGvsiR+N4dHGU87ml8O2Vl6l+ErOi9w0kXSPiwJ1AYlIW+0pDXDWWMOiWbw==", + "dev": true + }, + "accepts": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", + "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", + "dev": true, + "requires": { + "mime-types": "~2.1.24", + "negotiator": "0.6.2" + } + }, + "ansi-colors": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-3.2.3.tgz", + "integrity": "sha512-LEHHyuhlPY3TmuUYMh2oz89lTShfvgbmzaBcxve9t/9Wuy7Dwf4yoAKcND7KFT1HAQfqZ12qtc+DUrBMeKF9nw==", + "dev": true + }, + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true }, "ansi-styles": { "version": "3.2.1", @@ -2751,26 +3365,6 @@ "sprintf-js": "~1.0.2" } }, - "asn1.js": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", - "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", - "dev": true, - "requires": { - "bn.js": "^4.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "safer-buffer": "^2.1.0" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - } - } - }, "assert": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", @@ -2785,6 +3379,12 @@ "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", "dev": true }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "dev": true + }, "bignumber.js": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", @@ -2814,12 +3414,6 @@ } } }, - "bn.js": { - "version": "5.1.3", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.1.3.tgz", - "integrity": "sha512-GkTiFpjFtUzU9CbMeJ5iazkCzGL3jrhzerzZIuqLABjbwRaFt33I9tUdSNryIptM+RxDet6OKm2WnLXzW51KsQ==", - "dev": true - }, "brace-expansion": { "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", @@ -2839,117 +3433,26 @@ "fill-range": "^7.0.1" } }, - "brorand": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", - "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", - "dev": true - }, "browser-stdout": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==", "dev": true }, - "browserify-aes": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", - "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", "dev": true, "requires": { - "buffer-xor": "^1.0.3", - "cipher-base": "^1.0.0", - "create-hash": "^1.1.0", - "evp_bytestokey": "^1.0.3", - "inherits": "^2.0.1", - "safe-buffer": "^5.0.1" + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" } }, - "browserify-cipher": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", - "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", - "dev": true, - "requires": { - "browserify-aes": "^1.0.4", - "browserify-des": "^1.0.0", - "evp_bytestokey": "^1.0.0" - } - }, - "browserify-des": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", - "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", - "dev": true, - "requires": { - "cipher-base": "^1.0.1", - "des.js": "^1.0.0", - "inherits": "^2.0.1", - "safe-buffer": "^5.1.2" - } - }, - "browserify-rsa": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.1.0.tgz", - "integrity": "sha512-AdEER0Hkspgno2aR97SAf6vi0y0k8NuOpGnVH3O99rcA5Q6sh8QxcngtHuJ6uXwnfAXNM4Gn1Gb7/MV1+Ymbog==", - "dev": true, - "requires": { - "bn.js": "^5.0.0", - "randombytes": "^2.0.1" - } - }, - "browserify-sign": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.2.1.tgz", - "integrity": "sha512-/vrA5fguVAKKAVTNJjgSm1tRQDHUU6DbwO9IROu/0WAzC8PKhucDSh18J0RMvVeHAn5puMd+QHC2erPRNf8lmg==", - "dev": true, - "requires": { - "bn.js": "^5.1.1", - "browserify-rsa": "^4.0.1", - "create-hash": "^1.2.0", - "create-hmac": "^1.1.7", - "elliptic": "^6.5.3", - "inherits": "^2.0.4", - "parse-asn1": "^5.1.5", - "readable-stream": "^3.6.0", - "safe-buffer": "^5.2.0" - }, - "dependencies": { - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, - "readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", - "dev": true, - "requires": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - } - }, - "safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true - } - } - }, - "buffer-es6": { - "version": "4.9.3", - "resolved": "https://registry.npmjs.org/buffer-es6/-/buffer-es6-4.9.3.tgz", - "integrity": "sha1-8mNHuC33b9N+GLy1KIxJcM/VxAQ=", - "dev": true - }, - "buffer-xor": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", - "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "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==", "dev": true }, "builtin-modules": { @@ -2958,6 +3461,16 @@ "integrity": "sha512-k0KL0aWZuBt2lrxrcASWDfwOLMnodeQjodT/1SxEQAXsHANgo6ZC/VEaSEHCXt7aSTZ4/4H5LKa+tBXmW7Vtvw==", "dev": true }, + "cache-content-type": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-content-type/-/cache-content-type-1.0.1.tgz", + "integrity": "sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==", + "dev": true, + "requires": { + "mime-types": "^2.1.18", + "ylru": "^1.2.0" + } + }, "camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -3050,6 +3563,12 @@ } } }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, "color-convert": { "version": "1.9.3", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", @@ -3065,12 +3584,39 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", "dev": true }, + "commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, "concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, + "content-disposition": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", + "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", + "dev": true, + "requires": { + "safe-buffer": "5.1.2" + } + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true + }, "convert-source-map": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.7.0.tgz", @@ -3080,24 +3626,22 @@ "safe-buffer": "~5.1.1" } }, - "create-ecdh": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.4.tgz", - "integrity": "sha512-mf+TCx8wWc9VpuxfP2ht0iSISLZnt0JgWlrOKZiNqyUZWnjIaCIVNQArMHnCZKfEYRg6IM7A+NeJoN8gf/Ws0A==", + "cookies": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/cookies/-/cookies-0.8.0.tgz", + "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", "dev": true, "requires": { - "bn.js": "^4.1.0", - "elliptic": "^6.5.3" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - } + "depd": "~2.0.0", + "keygrip": "~1.1.0" } }, + "core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "dev": true + }, "create-hash": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", @@ -3123,25 +3667,6 @@ "sha.js": "^2.4.8" } }, - "crypto-browserify": { - "version": "3.12.0", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", - "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", - "dev": true, - "requires": { - "browserify-cipher": "^1.0.0", - "browserify-sign": "^4.0.0", - "create-ecdh": "^4.0.0", - "create-hash": "^1.1.0", - "create-hmac": "^1.1.0", - "diffie-hellman": "^5.0.0", - "inherits": "^2.0.1", - "pbkdf2": "^3.0.3", - "public-encrypt": "^4.0.0", - "randombytes": "^2.0.0", - "randomfill": "^1.0.3" - } - }, "debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", @@ -3157,6 +3682,18 @@ "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", "dev": true }, + "deep-equal": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=", + "dev": true + }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "dev": true + }, "define-properties": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", @@ -3166,15 +3703,23 @@ "object-keys": "^1.0.12" } }, - "des.js": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.1.tgz", - "integrity": "sha512-Q0I4pfFrv2VPd34/vfLrFOoRmlYj3OV50i7fskps1jZWK1kApMWWT9G6RRUeYedLcBDIhnSDaUvJMb3AhUlaEA==", - "dev": true, - "requires": { - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0" - } + "delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=", + "dev": true + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "dev": true + }, + "destroy": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "dev": true }, "diff": { "version": "3.5.0", @@ -3182,25 +3727,6 @@ "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", "dev": true }, - "diffie-hellman": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", - "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", - "dev": true, - "requires": { - "bn.js": "^4.1.0", - "miller-rabin": "^4.0.0", - "randombytes": "^2.0.0" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - } - } - }, "dotenv": { "version": "8.2.0", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-8.2.0.tgz", @@ -3240,34 +3766,11 @@ } } }, - "elliptic": { - "version": "6.5.4", - "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.4.tgz", - "integrity": "sha512-iLhC6ULemrljPZb+QutR5TQGB+pdW6KGD5RSegS+8sorOZT+rdQFbsQFJgvN3eRqNALqJer4oQ16YvJHlU8hzQ==", - "dev": true, - "requires": { - "bn.js": "^4.11.9", - "brorand": "^1.1.0", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.1", - "inherits": "^2.0.4", - "minimalistic-assert": "^1.0.1", - "minimalistic-crypto-utils": "^1.0.1" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - }, - "inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - } - } + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "dev": true }, "emoji-regex": { "version": "7.0.3", @@ -3275,6 +3778,12 @@ "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==", "dev": true }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "dev": true + }, "es-abstract": { "version": "1.17.5", "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.17.5.tgz", @@ -3305,6 +3814,12 @@ "is-symbol": "^1.0.2" } }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "dev": true + }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -3317,28 +3832,12 @@ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", "dev": true }, - "estree-walker": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.6.1.tgz", - "integrity": "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w==", - "dev": true - }, "esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", "dev": true }, - "evp_bytestokey": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", - "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", - "dev": true, - "requires": { - "md5.js": "^1.3.4", - "safe-buffer": "^5.1.1" - } - }, "expect.js": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/expect.js/-/expect.js-0.3.1.tgz", @@ -3372,6 +3871,12 @@ "is-buffer": "~2.0.3" } }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "dev": true + }, "fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -3454,11 +3959,20 @@ "dev": true }, "has-symbols": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.1.tgz", - "integrity": "sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.2.tgz", + "integrity": "sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==", "dev": true }, + "has-tostringtag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "dev": true, + "requires": { + "has-symbols": "^1.0.2" + } + }, "hash-base": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.1.0.tgz", @@ -3491,16 +4005,41 @@ } } }, - "hash.js": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", - "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "dev": true + }, + "http-assert": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", "dev": true, "requires": { - "inherits": "^2.0.3", - "minimalistic-assert": "^1.0.1" + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + } + }, + "http-errors": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "dev": true, + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" }, "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true + }, "inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -3509,22 +4048,17 @@ } } }, - "he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", "dev": true }, - "hmac-drbg": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", - "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", - "dev": true, - "requires": { - "hash.js": "^1.0.3", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.1" - } + "immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha1-nbHb0Pr43m++D13V5Wu2BigN5ps=", + "dev": true }, "inflight": { "version": "1.0.6", @@ -3562,6 +4096,15 @@ "integrity": "sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw==", "dev": true }, + "is-core-module": { + "version": "2.8.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.0.tgz", + "integrity": "sha512-vd15qHsaqrRL7dtH6QNuy0ndJmRDrS9HAM1CAiSifNUFv4x1a0CCVsj18hJ1mShxIG6T2i1sO78MkP56r0nYRw==", + "dev": true, + "requires": { + "has": "^1.0.3" + } + }, "is-date-object": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.2.tgz", @@ -3580,6 +4123,15 @@ "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", "dev": true }, + "is-generator-function": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.10.tgz", + "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", + "dev": true, + "requires": { + "has-tostringtag": "^1.0.0" + } + }, "is-glob": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", @@ -3601,23 +4153,6 @@ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true }, - "is-reference": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.1.4.tgz", - "integrity": "sha512-uJA/CDPO3Tao3GTrxYn6AwkM4nUPJiGGYu5+cB8qbC7WGFlrKZbiRo7SFKxUAEpFUfiHofWCXBUNhvYJMh+6zw==", - "dev": true, - "requires": { - "@types/estree": "0.0.39" - }, - "dependencies": { - "@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", - "dev": true - } - } - }, "is-regex": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.1.0.tgz", @@ -3636,12 +4171,46 @@ "has-symbols": "^1.0.1" } }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, "isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", "dev": true }, + "jest-worker": { + "version": "26.6.2", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-26.6.2.tgz", + "integrity": "sha512-KWYVV1c4i+jbMpaBC+U++4Va0cp8OisU185o73T1vo99hqi7w8tSJfUXYswwqqrjzwxa6KpRK54WhPvwf5w6PQ==", + "dev": true, + "requires": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^7.0.0" + }, + "dependencies": { + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true + }, + "supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "requires": { + "has-flag": "^4.0.0" + } + } + } + }, "js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -3673,6 +4242,138 @@ "minimist": "^1.2.0" } }, + "jszip": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.7.1.tgz", + "integrity": "sha512-ghL0tz1XG9ZEmRMcEN2vt7xabrDdqHHeykgARpmZ0BiIctWxM47Vt63ZO2dnp4QYt/xJVLLy5Zv1l/xRdh2byg==", + "dev": true, + "requires": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "set-immediate-shim": "~1.0.1" + } + }, + "keygrip": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "dev": true, + "requires": { + "tsscmp": "1.0.6" + } + }, + "koa": { + "version": "2.13.4", + "resolved": "https://registry.npmjs.org/koa/-/koa-2.13.4.tgz", + "integrity": "sha512-43zkIKubNbnrULWlHdN5h1g3SEKXOEzoAlRsHOTFpnlDu8JlAOZSMJBLULusuXRequboiwJcj5vtYXKB3k7+2g==", + "dev": true, + "requires": { + "accepts": "^1.3.5", + "cache-content-type": "^1.0.0", + "content-disposition": "~0.5.2", + "content-type": "^1.0.4", + "cookies": "~0.8.0", + "debug": "^4.3.2", + "delegates": "^1.0.0", + "depd": "^2.0.0", + "destroy": "^1.0.4", + "encodeurl": "^1.0.2", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.3.0", + "http-errors": "^1.6.3", + "is-generator-function": "^1.0.7", + "koa-compose": "^4.1.0", + "koa-convert": "^2.0.0", + "on-finished": "^2.3.0", + "only": "~0.0.2", + "parseurl": "^1.3.2", + "statuses": "^1.5.0", + "type-is": "^1.6.16", + "vary": "^1.1.2" + }, + "dependencies": { + "debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "koa-compose": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "dev": true + }, + "koa-convert": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/koa-convert/-/koa-convert-2.0.0.tgz", + "integrity": "sha512-asOvN6bFlSnxewce2e/DK3p4tltyfC4VM7ZwuTuepI7dEQVcvpyFuBcEARu1+Hxg8DIwytce2n7jrZtRlPrARA==", + "dev": true, + "requires": { + "co": "^4.6.0", + "koa-compose": "^4.1.0" + } + }, + "koa-send": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/koa-send/-/koa-send-5.0.1.tgz", + "integrity": "sha512-tmcyQ/wXXuxpDxyNXv5yNNkdAMdFRqwtegBXUaowiQzUKqJehttS0x2j0eOZDQAyloAth5w6wwBImnFzkUz3pQ==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "http-errors": "^1.7.3", + "resolve-path": "^1.4.0" + }, + "dependencies": { + "debug": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.2.tgz", + "integrity": "sha512-mOp8wKcvj7XxC78zLgw/ZA+6TSgkoE2C/ienthhRD298T7UNwAg9diBpLRxC0mOezLl4B0xV7M0cCO6P/O0Xhw==", + "dev": true, + "requires": { + "ms": "2.1.2" + } + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + } + } + }, + "koa-static": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/koa-static/-/koa-static-5.0.0.tgz", + "integrity": "sha512-UqyYyH5YEXaJrf9S8E23GoJFQZXkBVJ9zYYMPGz919MSX1KuvAcycIuS0ci150HCoPf4XQVhQ84Qf8xRPWxFaQ==", + "dev": true, + "requires": { + "debug": "^3.1.0", + "koa-send": "^5.0.0" + } + }, + "lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "dev": true, + "requires": { + "immediate": "~3.0.5" + } + }, "locate-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", @@ -3698,15 +4399,6 @@ "chalk": "^2.4.2" } }, - "magic-string": { - "version": "0.25.6", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.6.tgz", - "integrity": "sha512-3a5LOMSGoCTH5rbqobC2HuDNRtE2glHZ8J7pK+QZYppyWA36yuNpsX994rIY2nCuyP7CZYy7lQq/X2jygiZ89g==", - "dev": true, - "requires": { - "sourcemap-codec": "^1.4.4" - } - }, "md5.js": { "version": "1.3.5", "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", @@ -3717,36 +4409,33 @@ "safe-buffer": "^5.1.2" } }, - "miller-rabin": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", - "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", - "dev": true, - "requires": { - "bn.js": "^4.0.0", - "brorand": "^1.0.1" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - } - } + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "dev": true }, - "minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", "dev": true }, - "minimalistic-crypto-utils": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", - "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "mime-db": { + "version": "1.51.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.51.0.tgz", + "integrity": "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g==", "dev": true }, + "mime-types": { + "version": "2.1.34", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.34.tgz", + "integrity": "sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==", + "dev": true, + "requires": { + "mime-db": "1.51.0" + } + }, "minimatch": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", @@ -3809,6 +4498,12 @@ "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", "dev": true }, + "negotiator": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", + "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==", + "dev": true + }, "node-cryptojs-aes": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-cryptojs-aes/-/node-cryptojs-aes-0.4.0.tgz", @@ -3869,6 +4564,15 @@ "es-abstract": "^1.17.0-next.1" } }, + "on-finished": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "dev": true, + "requires": { + "ee-first": "1.1.1" + } + }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -3878,6 +4582,18 @@ "wrappy": "1" } }, + "only": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/only/-/only-0.0.2.tgz", + "integrity": "sha1-Kv3oTQPlC5qO3EROMGEKcCle37Q=", + "dev": true + }, + "os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=", + "dev": true + }, "p-limit": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", @@ -3902,18 +4618,17 @@ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true }, - "parse-asn1": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz", - "integrity": "sha512-RnZRo1EPU6JBnra2vGHj0yhp6ebyjBZpmUCLHWiFhxlzvBCCpAuZ7elsBp1PVAbQN0/04VD/19rfzlBSwLstMw==", - "dev": true, - "requires": { - "asn1.js": "^5.2.0", - "browserify-aes": "^1.0.0", - "evp_bytestokey": "^1.0.0", - "pbkdf2": "^3.0.3", - "safe-buffer": "^5.1.1" - } + "pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "dev": true + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "dev": true }, "path-exists": { "version": "3.0.0", @@ -3951,34 +4666,12 @@ "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==", "dev": true }, - "process-es6": { - "version": "0.11.6", - "resolved": "https://registry.npmjs.org/process-es6/-/process-es6-0.11.6.tgz", - "integrity": "sha1-xrs4n5qVH4K9TrFpYAEFvS/5x3g=", + "process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", "dev": true }, - "public-encrypt": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", - "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", - "dev": true, - "requires": { - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" - }, - "dependencies": { - "bn.js": { - "version": "4.11.9", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.9.tgz", - "integrity": "sha512-E6QoYqCKZfgatHTdHzs1RRKP7ip4vvm+EyRUeE2RF0NblwVvb0p6jSVeNTOFxPn26QXN2o6SMfNxKp6kU8zQaw==", - "dev": true - } - } - }, "randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -3987,14 +4680,27 @@ "safe-buffer": "^5.1.0" } }, - "randomfill": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", - "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "readable-stream": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz", + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==", "dev": true, "requires": { - "randombytes": "^2.0.5", - "safe-buffer": "^5.1.0" + "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": { + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "dev": true + } } }, "readdirp": { @@ -4027,142 +4733,183 @@ "path-parse": "^1.0.6" } }, - "ripemd160": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", - "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "resolve-path": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/resolve-path/-/resolve-path-1.4.0.tgz", + "integrity": "sha1-xL2p9e+y/OZSR4c6s2u02DT+Fvc=", + "dev": true, "requires": { - "hash-base": "^3.0.0", - "inherits": "^2.0.1" + "http-errors": "~1.6.2", + "path-is-absolute": "1.0.1" + }, + "dependencies": { + "depd": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "dev": true + }, + "http-errors": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "dev": true, + "requires": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "setprototypeof": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "dev": true + } } }, - "rollup": { - "version": "1.31.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.31.1.tgz", - "integrity": "sha512-2JREN1YdrS/kpPzEd33ZjtuNbOuBC3ePfuZBdKEybvqcEcszW1ckyVqzcEiEe0nE8sqHK+pbJg+PsAgRJ8+1dg==", + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", "dev": true, "requires": { - "@types/estree": "*", - "@types/node": "*", - "acorn": "^7.1.0" + "glob": "^7.1.3" } }, - "rollup-plugin-babel": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/rollup-plugin-babel/-/rollup-plugin-babel-4.3.3.tgz", - "integrity": "sha512-tKzWOCmIJD/6aKNz0H1GMM+lW1q9KyFubbWzGiOG540zxPPifnEAHTZwjo0g991Y+DyOZcLqBgqOdqazYE5fkw==", - "dev": true, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", "requires": { - "@babel/helper-module-imports": "^7.0.0", - "rollup-pluginutils": "^2.8.1" + "hash-base": "^3.0.0", + "inherits": "^2.0.1" } }, - "rollup-plugin-commonjs": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-commonjs/-/rollup-plugin-commonjs-10.1.0.tgz", - "integrity": "sha512-jlXbjZSQg8EIeAAvepNwhJj++qJWNJw1Cl0YnOqKtP5Djx+fFGkp3WRh+W0ASCaFG5w1jhmzDxgu3SJuVxPF4Q==", + "rollup": { + "version": "2.60.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.60.0.tgz", + "integrity": "sha512-cHdv9GWd58v58rdseC8e8XIaPUo8a9cgZpnCMMDGZFDZKEODOiPPEQFXLriWr/TjXzhPPmG5bkAztPsOARIcGQ==", "dev": true, "requires": { - "estree-walker": "^0.6.1", - "is-reference": "^1.1.2", - "magic-string": "^0.25.2", - "resolve": "^1.11.0", - "rollup-pluginutils": "^2.8.1" + "fsevents": "~2.3.2" + }, + "dependencies": { + "fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "optional": true + } } }, - "rollup-plugin-node-builtins": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-builtins/-/rollup-plugin-node-builtins-2.0.0.tgz", - "integrity": "sha1-xvKR4WfpVg6+qH+/3Bq7RLCnweY=", + "rollup-plugin-polyfill-node": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/rollup-plugin-polyfill-node/-/rollup-plugin-polyfill-node-0.7.0.tgz", + "integrity": "sha512-iJLZDfvxcQh3SpC0OiYlZG9ik26aRM29hiC2sARbAPXYunB8rzW8GtVaWuJgiCtX1hNAo/OaYvVXfPp15fMs7g==", "dev": true, "requires": { - "buffer-es6": "^4.9.2", - "crypto-browserify": "^3.11.0", - "process-es6": "^0.11.2" + "@rollup/plugin-inject": "^4.0.0" } }, - "rollup-plugin-node-globals": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-globals/-/rollup-plugin-node-globals-1.4.0.tgz", - "integrity": "sha512-xRkB+W/m1KLIzPUmG0ofvR+CPNcvuCuNdjVBVS7ALKSxr3EDhnzNceGkGi1m8MToSli13AzKFYH4ie9w3I5L3g==", + "rollup-plugin-terser": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-7.0.2.tgz", + "integrity": "sha512-w3iIaU4OxcF52UUXiZNsNeuXIMDvFrr+ZXK6bFZ0Q60qyVfq4uLptoS4bbq3paG3x216eQllFZX7zt6TIImguQ==", "dev": true, "requires": { - "acorn": "^5.7.3", - "buffer-es6": "^4.9.3", - "estree-walker": "^0.5.2", - "magic-string": "^0.22.5", - "process-es6": "^0.11.6", - "rollup-pluginutils": "^2.3.1" + "@babel/code-frame": "^7.10.4", + "jest-worker": "^26.2.1", + "serialize-javascript": "^4.0.0", + "terser": "^5.0.0" }, "dependencies": { - "acorn": { - "version": "5.7.4", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.4.tgz", - "integrity": "sha512-1D++VG7BhrtvQpNbBzovKNc1FLGGEE/oGe7b9xJm/RFHMBeUaUGpluV9RLjZa47YFdPcDAenEYuq9pQPcMdLJg==", - "dev": true - }, - "estree-walker": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-0.5.2.tgz", - "integrity": "sha512-XpCnW/AE10ws/kDAs37cngSkvgIR8aN3G0MS85m7dUpuK2EREo9VJ00uvw6Dg/hXEpfsE1I1TvJOJr+Z+TL+ig==", - "dev": true + "@babel/code-frame": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.16.0.tgz", + "integrity": "sha512-IF4EOMEV+bfYwOmNxGzSnjR2EmQod7f1UXOpZM3l4i4o4QNwzjtJAu/HxdjHq0aYBvdqMuQEY1eg0nqW9ZPORA==", + "dev": true, + "requires": { + "@babel/highlight": "^7.16.0" + } }, - "magic-string": { - "version": "0.22.5", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.22.5.tgz", - "integrity": "sha512-oreip9rJZkzvA8Qzk9HFs8fZGF/u7H/gtrE8EN6RjKJ9kh2HlC+yQ2QezifqTZfGyiuAV0dRv5a+y/8gBb1m9w==", + "@babel/highlight": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.16.0.tgz", + "integrity": "sha512-t8MH41kUQylBtu2+4IQA3atqevA2lRgqA2wyVB/YiWmsDSuylZZuXOUy9ric30hfzauEFfdsuk/eXTRrGrfd0g==", "dev": true, "requires": { - "vlq": "^0.2.2" + "@babel/helper-validator-identifier": "^7.15.7", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" } } } }, - "rollup-plugin-node-resolve": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/rollup-plugin-node-resolve/-/rollup-plugin-node-resolve-5.2.0.tgz", - "integrity": "sha512-jUlyaDXts7TW2CqQ4GaO5VJ4PwwaV8VUGA7+km3n6k6xtOEacf61u0VXwN80phY/evMcaS+9eIeJ9MOyDxt5Zw==", - "dev": true, - "requires": { - "@types/resolve": "0.0.8", - "builtin-modules": "^3.1.0", - "is-module": "^1.0.0", - "resolve": "^1.11.1", - "rollup-pluginutils": "^2.8.1" - } - }, - "rollup-pluginutils": { - "version": "2.8.2", - "resolved": "https://registry.npmjs.org/rollup-pluginutils/-/rollup-pluginutils-2.8.2.tgz", - "integrity": "sha512-EEp9NhnUkwY8aif6bxgovPHMoMoNr2FulJziTndpt5H9RdwC47GSGuII9XxpSdzVGM0GWrNPHV6ie1LTNJPaLQ==", - "dev": true, - "requires": { - "estree-walker": "^0.6.1" - } - }, "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==" }, - "safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", "dev": true }, + "selenium-webdriver": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/selenium-webdriver/-/selenium-webdriver-3.6.0.tgz", + "integrity": "sha512-WH7Aldse+2P5bbFBO4Gle/nuQOdVwpHMTL6raL3uuBj/vPG07k6uzt3aiahu352ONBr5xXh0hDlM3LhtXPOC4Q==", + "dev": true, + "requires": { + "jszip": "^3.1.3", + "rimraf": "^2.5.4", + "tmp": "0.0.30", + "xml2js": "^0.4.17" + } + }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", "dev": true }, + "serialize-javascript": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-4.0.0.tgz", + "integrity": "sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw==", + "dev": true, + "requires": { + "randombytes": "^2.1.0" + } + }, "set-blocking": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", "dev": true }, + "set-immediate-shim": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/set-immediate-shim/-/set-immediate-shim-1.0.1.tgz", + "integrity": "sha1-SysbJ+uAip+NzEgaWOXlb1mfP2E=", + "dev": true + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "dev": true + }, "sha.js": { "version": "2.4.11", "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", @@ -4172,12 +4919,36 @@ "safe-buffer": "^5.0.1" } }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "dev": true + }, "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", "dev": true }, + "source-map-support": { + "version": "0.5.20", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.20.tgz", + "integrity": "sha512-n1lZZ8Ve4ksRqizaBQgxXDgKwttHDhyfQjA6YZZn8+AroHbsIz+JjwxQDxbp+7y5OYCI8t1Yk7etjD9CRd2hIw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, "sourcemap-codec": { "version": "1.4.8", "resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz", @@ -4190,6 +4961,12 @@ "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", "dev": true }, + "statuses": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=", + "dev": true + }, "string_decoder": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", @@ -4274,6 +5051,34 @@ "has-flag": "^3.0.0" } }, + "terser": { + "version": "5.9.0", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.9.0.tgz", + "integrity": "sha512-h5hxa23sCdpzcye/7b8YqbE5OwKca/ni0RQz1uRX3tGh8haaGHqcuSqbGRybuAKNdntZ0mDgFNXPJ48xQ2RXKQ==", + "dev": true, + "requires": { + "commander": "^2.20.0", + "source-map": "~0.7.2", + "source-map-support": "~0.5.20" + }, + "dependencies": { + "source-map": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz", + "integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==", + "dev": true + } + } + }, + "tmp": { + "version": "0.0.30", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.30.tgz", + "integrity": "sha1-ckGdSovn1s51FI/YsyTlk6cRwu0=", + "dev": true, + "requires": { + "os-tmpdir": "~1.0.1" + } + }, "to-fast-properties": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", @@ -4289,11 +5094,33 @@ "is-number": "^7.0.0" } }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "dev": true + }, + "tsscmp": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "dev": true + }, "tweetnacl": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.1.tgz", "integrity": "sha512-kcoMoKTPYnoeS50tzoqjPY3Uv9axeuuFAZY9M/9zFnhoVvRfxz9K29IMPD7jGmt2c8SW7i3gT9WqDl2+nV7p4A==" }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dev": true, + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, "types-validate-assert": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/types-validate-assert/-/types-validate-assert-1.0.1.tgz", @@ -4312,10 +5139,10 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=" }, - "vlq": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/vlq/-/vlq-0.2.3.tgz", - "integrity": "sha512-DRibZL6DsNhIgYQ+wNdWDL2SL3bKPlVrRiBqV5yuMm++op8W4kGFtaQfCs4KEJn0wBZcHVHJ3eoywX8983k1ow==", + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", "dev": true }, "which": { @@ -4387,6 +5214,22 @@ "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", "dev": true }, + "xml2js": { + "version": "0.4.23", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", + "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "dev": true, + "requires": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + } + }, + "xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "dev": true + }, "y18n": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", @@ -4459,6 +5302,12 @@ "lodash": "^4.17.15", "yargs": "^13.3.0" } + }, + "ylru": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ylru/-/ylru-1.2.1.tgz", + "integrity": "sha512-faQrqNMzcPCHGVC2aaOINk13K+aaBDUPjGWl0teOXywElLjyVAB6Oe2jj62jHYtwsU49jXhScYbvPENK+6zAvQ==", + "dev": true } } } diff --git a/package.json b/package.json index 1c3119f..8ea492c 100644 --- a/package.json +++ b/package.json @@ -2,17 +2,25 @@ "name": "lamden-js", "version": "2.0.0", "description": "A javascript implementaion for creating wallets, submitting transactions and interacting with masternodes on the Lamden Blockchain.", - "main": "dist/lamden.js", + "main": "dist/cjs/lamden.js", + "module": "dist/esm/lamden.js", "scripts": { - "test": "npm run build && mocha", + "test": "npm run build && mocha --recursive --timeout 30000", "tests": "npm run test", - "test-network": "npm run build && mocha test/network-test.js", - "test-masternode-api": "npm run build && mocha test/masternode_api-test.js", + "test-network": "npm run build && mocha test/network-test.js --timeout 10000", + "test-masternode-api": "npm run build && mocha test/masternode_api-test.js --timeout 10000", "test-transaction-builder": "npm run build && mocha test/transactionBuilder-test.js --timeout 10000", "test-transaction-batcher": "npm run build && mocha test/transactionBatcher-test.js --timeout 60000", "test-wallet": "npm run build && mocha test/wallet-test.js", "test-encoder": "npm run build && mocha test/encoder-test.js", "test-keystore": "npm run build && mocha test/keystore-test.js", + "browsers:test-network": "npm run build && mocha test/browsers/network-test.js --timeout 10000", + "browsers:test-masternode-api": "npm run build && mocha test/browsers/masternode_api-test.js --timeout 10000", + "browsers:test-transaction-builder": "npm run build && mocha test/browsers/transactionBuilder-test.js --timeout 10000", + "browsers:test-transaction-batcher": "npm run build && mocha test/browsers/transactionBatcher-test.js --timeout 10000", + "browsers:test-wallet": "npm run build && mocha test/browsers/wallet-test.js --timeout 10000", + "browsers:test-encoder": "npm run build && mocha test/browsers/encoder-test.js --timeout 10000", + "browsers:test-keystore": "npm run build && mocha test/browsers/keystore-test.js --timeout 10000", "build": "rollup --config", "doc": "doxdox 'src/js/keystore.js' --layout markdown --output docs/keystore.md" }, @@ -44,14 +52,18 @@ }, "devDependencies": { "@babel/core": "^7.8.4", + "@rollup/plugin-alias": "^3.1.8", + "@rollup/plugin-commonjs": "^21.0.1", + "@rollup/plugin-node-resolve": "^13.0.6", + "buffer": "^6.0.3", "dotenv": "^8.2.0", "expect.js": "^0.3.1", + "koa": "^2.13.4", + "koa-static": "^5.0.0", "mocha": "^7.2.0", - "rollup": "^1.31.1", - "rollup-plugin-babel": "^4.3.3", - "rollup-plugin-commonjs": "^10.1.0", - "rollup-plugin-node-builtins": "^2.0.0", - "rollup-plugin-node-globals": "^1.4.0", - "rollup-plugin-node-resolve": "^5.2.0" + "rollup": "^2.60.0", + "rollup-plugin-polyfill-node": "^0.7.0", + "rollup-plugin-terser": "^7.0.2", + "selenium-webdriver": "^3.6.0" } } diff --git a/rollup.config.js b/rollup.config.js index a2853a8..1795b82 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -1,18 +1,35 @@ -import resolve from 'rollup-plugin-node-resolve'; -import builtins from 'rollup-plugin-node-builtins'; -import commonjs from 'rollup-plugin-commonjs'; -import globals from 'rollup-plugin-node-globals'; +import nodePolyfills from "rollup-plugin-polyfill-node"; +import commonjs from "@rollup/plugin-commonjs"; +import alias from "@rollup/plugin-alias"; +import { nodeResolve as resolve } from "@rollup/plugin-node-resolve"; +import { terser } from "rollup-plugin-terser"; -module.exports = { - input: 'src/index.js', +export default [ + { + input: "src/index.js", output: { - file: 'dist/lamden.js', - format: 'cjs' + file: "dist/esm/lamden.js", + format: "esm", }, + plugins: [ - resolve({preferBuiltins: true}), - commonjs(), - globals(), - builtins() - ] -}; \ No newline at end of file + alias({ + entries: [{ find: "bip39", replacement: "../bip39.browser" }], + }), + resolve({ browser: true, preferBuiltins: false }), + commonjs(), + nodePolyfills(), + terser(), + ], + }, + { + input: "src/index.js", + output: { + file: "dist/cjs/lamden.js", + format: "cjs", + exports: "default", + }, + plugins: [resolve({ preferBuiltins: true }), commonjs()], + external: ["tweetnacl", "bip39", "ed25519-hd-key"], + }, +]; diff --git a/src/bip39.browser.js b/src/bip39.browser.js new file mode 100644 index 0000000..8c3e545 --- /dev/null +++ b/src/bip39.browser.js @@ -0,0 +1,16654 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bip39 = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],2:[function(require,module,exports){ + +},{}],3:[function(require,module,exports){ +(function (Buffer){(function (){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this)}).call(this,require("buffer").Buffer) +},{"base64-js":1,"buffer":3,"ieee754":5}],4:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + +},{}],5:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],6:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + +},{}],7:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],8:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],9:[function(require,module,exports){ +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ +/* 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) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// 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) +} + +},{"buffer":3}],10:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/lib/_stream_readable.js'); +Stream.Writable = require('readable-stream/lib/_stream_writable.js'); +Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); +Stream.Transform = require('readable-stream/lib/_stream_transform.js'); +Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); +Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') +Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":4,"inherits":6,"readable-stream/lib/_stream_duplex.js":12,"readable-stream/lib/_stream_passthrough.js":13,"readable-stream/lib/_stream_readable.js":14,"readable-stream/lib/_stream_transform.js":15,"readable-stream/lib/_stream_writable.js":16,"readable-stream/lib/internal/streams/end-of-stream.js":20,"readable-stream/lib/internal/streams/pipeline.js":22}],11:[function(require,module,exports){ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; + +},{}],12:[function(require,module,exports){ +(function (process){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. +'use strict'; +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + + for (var key in obj) { + keys.push(key); + } + + return keys; +}; +/**/ + + +module.exports = Duplex; + +var Readable = require('./_stream_readable'); + +var Writable = require('./_stream_writable'); + +require('inherits')(Duplex, Readable); + +{ + // 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); + this.allowHalfOpen = true; + + 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() { + 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 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. + + process.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + // 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 set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); +}).call(this)}).call(this,require('_process')) +},{"./_stream_readable":14,"./_stream_writable":16,"_process":8,"inherits":6}],13:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_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); +}; +},{"./_stream_transform":15,"inherits":6}],14:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +'use strict'; + +module.exports = Readable; +/**/ + +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; +/**/ + +var EE = require('events').EventEmitter; + +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ + + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + + +var debugUtil = require('util'); + +var debug; + +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + + +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; +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. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any + // 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 (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +function ReadableState(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. + + 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" + + 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 + // array.shift() + + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + + this.sync = true; // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + + this.needReadable = false; + 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; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s + + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled + + this.readingMore = false; + this.decoder = null; + this.encoding = null; + + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); // 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', { + // 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 set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; + +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; // Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. + + +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; // Unshift should *always* be something directly out of read() + + +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; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + + if (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) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, 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); + } 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 ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + + return er; +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; // backwards compatibility. + + +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + 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 > 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 + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + + return n; +} // This function is designed to be inlinable, so please take care when making +// changes to the function body. + + +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } // If we're asking for more than the current hwm, then raise the hwm. + + + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; // Don't have enough + + if (!state.ended) { + state.needReadable = true; + return 0; + } + + return state.length; +} // you can override either this method, or the async _read(n) below. + + +Readable.prototype.read = function (n) { + debug('read', 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.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. + + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + // if we need a readable event, then we need to do some reading. + + + var doRead = state.needReadable; + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some + + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + + + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; // if the length is currently zero, then we *need* a readable event. + + if (state.length === 0) state.needReadable = true; // call internal read method + + this._read(state.highWaterMark); + + state.sync = false; // If _read pushed data synchronously, then `reading` will be false, + // 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 = 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. + if (!state.ended) state.needReadable = true; // 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(); + + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + + state.ended = true; + + 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 +// another read() call => stack overflow. This way, it might trigger +// 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; + process.nextTick(emitReadable_, stream); + } +} + +function emitReadable_(stream) { + 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); +} // at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. + + +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + // 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; + } + + state.readingMore = false; +} // abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. + + +Readable.prototype._read = function (n) { + 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; + break; + + case 1: + state.pipes = [state.pipes, dest]; + break; + + default: + state.pipes.push(dest); + break; + } + + 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) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + + + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + + function cleanup() { + debug('cleanup'); // cleanup event handlers once the pipe is broken + + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + 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 + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + 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. + // => Check whether `dest` is still a piping destination. + 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++; + } + + src.pause(); + } + } // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + + + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } // Make sure our error handler is attached before userland ones. + + + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. + + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + + dest.once('close', onclose); + + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } // tell the dest that it's being piped to + + + dest.emit('pipe', src); // start the flow if it hasn't been started already. + + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; // if we're not piping anywhere, then do nothing. + + if (state.pipesCount === 0) return this; // just one destination. most common case. + + 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. + + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } // slow case. multiple pipe destinations. + + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + 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; + } // 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; +}; // set up data events if they are asked for +// 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') { + // 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') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + 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); +} // pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. + + +Readable.prototype.resume = function () { + var state = this._readableState; + + if (!state.flowing) { + debug('resume'); // 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; + process.nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + debug('resume', state.reading); + + if (!state.reading) { + stream.read(0); + } + + state.resumeScheduled = false; + 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 (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) { + ; + } +} // wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// 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; + stream.pause(); + } + }); // proxy all the other methods. + // important when wrapping filters and duplexes. + + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } // proxy certain important events. + + + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } // when we try to consume some more bytes, simply unpause the + // underlying stream. + + + this._read = function (n) { + debug('wrapped _read', n); + + if (paused) { + paused = false; + 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() { + 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. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. + +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.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + + if (!state.endEmitted) { + state.ended = true; + 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; + } + + return -1; +} +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../errors":11,"./_stream_duplex":12,"./internal/streams/async_iterator":17,"./internal/streams/buffer_list":18,"./internal/streams/destroy":19,"./internal/streams/from":21,"./internal/streams/state":23,"./internal/streams/stream":24,"_process":8,"buffer":3,"events":4,"inherits":6,"string_decoder/":25,"util":2}],15:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. +'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'); + +require('inherits')(Transform, Duplex); + +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + + 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` + 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, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; // start out asking for a readable event once data is transformed. + + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things + // 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' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; // This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// 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) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; // Doesn't matter what the args are here. +// _transform does all the work. +// 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.transforming) { + ts.transforming = true; + + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + 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 ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} +},{"../errors":11,"./_stream_duplex":12,"inherits":6}],16:[function(require,module,exports){ +(function (process,global){(function (){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. +'use strict'; + +module.exports = Writable; +/* */ + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} // It seems a linked list but it is not +// 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 () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ + + +var Duplex; +/**/ + +Writable.WritableState = WritableState; +/**/ + +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ + +var Stream = require('./internal/streams/stream'); +/**/ + + +var Buffer = require('buffer').Buffer; + +var OurUint8Array = global.Uint8Array || function () {}; + +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} + +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +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_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, 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, + // 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() + + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called + + this.finalCalled = false; // drain event flag. + + this.needDrain = false; // at the start of calling end() + + this.ending = false; // when end() has been called, and returned + + this.ended = false; // when 'finish' is emitted + + this.finished = false; // has it been destroyed + + this.destroyed = false; // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + + this.length = 0; // a flag to see when we're in the middle of a write. + + this.writing = false; // when true all writes will be buffered until .uncork() call + + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + + this.sync = true; // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) + + this.onwrite = function (er) { + onwrite(stream, er); + }; // the callback that the user supplies to write(chunk,encoding,cb) + + + this.writecb = null; // the amount that is being written when _write is called. + + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + + this.prefinished = false; // 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; // allocate the first CorkedRequest, there is always + // 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 = []; + + while (current) { + out.push(current); + current = current.next; + } + + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); // Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. + + +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 value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + // 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. + // 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 () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; + +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb + + 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 er; + + if (chunk === null) { + 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) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + + 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.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 () { + 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 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() { + return this._writableState.highWaterMark; + } +}); // if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. + +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + + 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 = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + + state.bufferedRequestCount += 1; + } 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 (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 + process.nextTick(cb, er); // this can emit finish, and it will always happen + // after error + + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + 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) || stream.destroyed; + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + 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--; + cb(); + finishMaybe(stream, state); +} // Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. + + +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} // if there's something in the buffer waiting, then process it + + +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) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + 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 + // as the hot path ends with doWrite + + state.pendingcb++; + state.lastBufferedRequest = null; + + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + 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--; // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + 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; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks + + if (state.corked) { + state.corked = 1; + this.uncork(); + } // 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; +} + +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + + if (err) { + errorOrDestroy(stream, err); + } + + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} + +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + + if (need) { + prefinish(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) 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; + + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } // reuse the free corkReq. + + + state.corkedRequestsFree.next = corkReq; +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + // 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 set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } // backward compatibility, the user is explicitly + // managing destroyed + + + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; + +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../errors":11,"./_stream_duplex":12,"./internal/streams/destroy":19,"./internal/streams/state":23,"./internal/streams/stream":24,"_process":8,"buffer":3,"inherits":6,"util-deprecate":26}],17:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; + +var _Object$setPrototypeO; + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +var finished = require('./end-of-stream'); + +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); + +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} + +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + + if (resolve !== null) { + var data = iter[kStream].read(); // we defer if data is null + // we can be expecting either 'end' or + // 'error' + + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} + +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} + +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} + +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + + next: function next() { + var _this = this; + + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + + if (error !== null) { + return Promise.reject(error); + } + + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + + + var lastPromise = this[kLastPromise]; + var promise; + + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + + promise = new Promise(this[kHandlePromise]); + } + + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); + +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise + // returned by next() and store the error + + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + + iterator[kError] = err; + return; + } + + var resolve = iterator[kLastResolve]; + + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; + +module.exports = createReadableStreamAsyncIterator; +}).call(this)}).call(this,require('_process')) +},{"./end-of-stream":20,"_process":8}],18:[function(require,module,exports){ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var _require = require('buffer'), + Buffer = _require.Buffer; + +var _require2 = require('util'), + inspect = _require2.inspect; + +var custom = inspect && inspect.custom || 'inspect'; + +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} + +module.exports = +/*#__PURE__*/ +function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + _createClass(BufferList, [{ + key: "push", + value: 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; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: 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; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: 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; + } + }, { + key: "concat", + value: 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; + } // Consumes a specified amount of bytes or characters from the buffered data. + + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } // Consumes a specified amount of characters from the buffered data. + + }, { + key: "_getString", + value: function _getString(n) { + var p = this.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) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Consumes a specified amount of bytes from the buffered data. + + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.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) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + + break; + } + + ++c; + } + + this.length -= c; + return ret; + } // Make sure the linked list only shows the minimal necessary information. + + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread({}, options, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + + return BufferList; +}(); +},{"buffer":3,"util":2}],19:[function(require,module,exports){ +(function (process){(function (){ +'use strict'; // 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) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + + return this; + } // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + + if (this._readableState) { + this._readableState.destroyed = true; + } // if this is a duplex stream mark the writable part as destroyed as well + + + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + 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; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + 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, + errorOrDestroy: errorOrDestroy +}; +}).call(this)}).call(this,require('_process')) +},{"_process":8}],20:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + callback.apply(this, args); + }; +} + +function noop() {} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + + var writableEnded = stream._writableState && stream._writableState.finished; + + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + + var readableEnded = stream._readableState && stream._readableState.endEmitted; + + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + + var onerror = function onerror(err) { + callback.call(stream, err); + }; + + var onclose = function onclose() { + var err; + + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} + +module.exports = eos; +},{"../../../errors":11}],21:[function(require,module,exports){ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; + +},{}],22:[function(require,module,exports){ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). +'use strict'; + +var eos; + +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} + +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; + +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} + +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} + +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; // request.destroy just do .end - .abort is what we want + + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} + +function call(fn) { + fn(); +} + +function pipe(from, to) { + return from.pipe(to); +} + +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} + +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} + +module.exports = pipeline; +},{"../../../errors":11,"./end-of-stream":20}],23:[function(require,module,exports){ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; + +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} + +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + + return Math.floor(hwm); + } // Default value + + + return state.objectMode ? 16 : 16 * 1024; +} + +module.exports = { + getHighWaterMark: getHighWaterMark +}; +},{"../../../errors":11}],24:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":4}],25:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":9}],26:[function(require,module,exports){ +(function (global){(function (){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],27:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer +var Transform = require('stream').Transform +var StringDecoder = require('string_decoder').StringDecoder +var inherits = require('inherits') + +function CipherBase (hashMode) { + Transform.call(this) + this.hashMode = typeof hashMode === 'string' + if (this.hashMode) { + this[hashMode] = this._finalOrDigest + } else { + this.final = this._finalOrDigest + } + if (this._final) { + this.__final = this._final + this._final = null + } + this._decoder = null + this._encoding = null +} +inherits(CipherBase, Transform) + +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) + } + + var outData = this._update(data) + if (this.hashMode) return this + + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } + + return outData +} + +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} + +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} + +CipherBase.prototype.setAAD = function () { + throw new Error('trying to set aad in unsupported state') +} + +CipherBase.prototype._transform = function (data, _, next) { + var err + try { + if (this.hashMode) { + this._update(data) + } else { + this.push(this._update(data)) + } + } catch (e) { + err = e + } finally { + next(err) + } +} +CipherBase.prototype._flush = function (done) { + var err + try { + this.push(this.__final()) + } catch (e) { + err = e + } + + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} + +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } + + if (this._encoding !== enc) throw new Error('can\'t switch encodings') + + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } + + return out +} + +module.exports = CipherBase + +},{"inherits":31,"safe-buffer":40,"stream":10,"string_decoder":25}],28:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var MD5 = require('md5.js') +var RIPEMD160 = require('ripemd160') +var sha = require('sha.js') +var Base = require('cipher-base') + +function Hash (hash) { + Base.call(this, 'digest') + + this._hash = hash +} + +inherits(Hash, Base) + +Hash.prototype._update = function (data) { + this._hash.update(data) +} + +Hash.prototype._final = function () { + return this._hash.digest() +} + +module.exports = function createHash (alg) { + alg = alg.toLowerCase() + if (alg === 'md5') return new MD5() + if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() + + return new Hash(sha(alg)) +} + +},{"cipher-base":27,"inherits":31,"md5.js":32,"ripemd160":39,"sha.js":42}],29:[function(require,module,exports){ +var MD5 = require('md5.js') + +module.exports = function (buffer) { + return new MD5().update(buffer).digest() +} + +},{"md5.js":32}],30:[function(require,module,exports){ +'use strict' +var Buffer = require('safe-buffer').Buffer +var Transform = require('stream').Transform +var inherits = require('inherits') + +function throwIfNotStringOrBuffer (val, prefix) { + if (!Buffer.isBuffer(val) && typeof val !== 'string') { + throw new TypeError(prefix + ' must be a string or a buffer') + } +} + +function HashBase (blockSize) { + Transform.call(this) + + this._block = Buffer.allocUnsafe(blockSize) + this._blockSize = blockSize + this._blockOffset = 0 + this._length = [0, 0, 0, 0] + + this._finalized = false +} + +inherits(HashBase, Transform) + +HashBase.prototype._transform = function (chunk, encoding, callback) { + var error = null + try { + this.update(chunk, encoding) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype._flush = function (callback) { + var error = null + try { + this.push(this.digest()) + } catch (err) { + error = err + } + + callback(error) +} + +HashBase.prototype.update = function (data, encoding) { + throwIfNotStringOrBuffer(data, 'Data') + if (this._finalized) throw new Error('Digest already called') + if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) + + // consume data + var block = this._block + var offset = 0 + while (this._blockOffset + data.length - offset >= this._blockSize) { + for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] + this._update() + this._blockOffset = 0 + } + while (offset < data.length) block[this._blockOffset++] = data[offset++] + + // update length + for (var j = 0, carry = data.length * 8; carry > 0; ++j) { + this._length[j] += carry + carry = (this._length[j] / 0x0100000000) | 0 + if (carry > 0) this._length[j] -= 0x0100000000 * carry + } + + return this +} + +HashBase.prototype._update = function () { + throw new Error('_update is not implemented') +} + +HashBase.prototype.digest = function (encoding) { + if (this._finalized) throw new Error('Digest already called') + this._finalized = true + + var digest = this._digest() + if (encoding !== undefined) digest = digest.toString(encoding) + + // reset state + this._block.fill(0) + this._blockOffset = 0 + for (var i = 0; i < 4; ++i) this._length[i] = 0 + + return digest +} + +HashBase.prototype._digest = function () { + throw new Error('_digest is not implemented') +} + +module.exports = HashBase + +},{"inherits":31,"safe-buffer":40,"stream":10}],31:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],32:[function(require,module,exports){ +'use strict' +var inherits = require('inherits') +var HashBase = require('hash-base') +var Buffer = require('safe-buffer').Buffer + +var ARRAY16 = new Array(16) + +function MD5 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 +} + +inherits(MD5, HashBase) + +MD5.prototype._update = function () { + var M = ARRAY16 + for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) + + var a = this._a + var b = this._b + var c = this._c + var d = this._d + + a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) + d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) + c = fnF(c, d, a, b, M[2], 0x242070db, 17) + b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) + a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) + d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) + c = fnF(c, d, a, b, M[6], 0xa8304613, 17) + b = fnF(b, c, d, a, M[7], 0xfd469501, 22) + a = fnF(a, b, c, d, M[8], 0x698098d8, 7) + d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) + c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) + b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) + a = fnF(a, b, c, d, M[12], 0x6b901122, 7) + d = fnF(d, a, b, c, M[13], 0xfd987193, 12) + c = fnF(c, d, a, b, M[14], 0xa679438e, 17) + b = fnF(b, c, d, a, M[15], 0x49b40821, 22) + + a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) + d = fnG(d, a, b, c, M[6], 0xc040b340, 9) + c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) + b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) + a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) + d = fnG(d, a, b, c, M[10], 0x02441453, 9) + c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) + b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) + a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) + d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) + c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) + b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) + a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) + d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) + c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) + b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) + + a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) + d = fnH(d, a, b, c, M[8], 0x8771f681, 11) + c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) + b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) + a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) + d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) + c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) + b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) + a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) + d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) + c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) + b = fnH(b, c, d, a, M[6], 0x04881d05, 23) + a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) + d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) + c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) + b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) + + a = fnI(a, b, c, d, M[0], 0xf4292244, 6) + d = fnI(d, a, b, c, M[7], 0x432aff97, 10) + c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) + b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) + a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) + d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) + c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) + b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) + a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) + d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) + c = fnI(c, d, a, b, M[6], 0xa3014314, 15) + b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) + a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) + d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) + c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) + b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) + + this._a = (this._a + a) | 0 + this._b = (this._b + b) | 0 + this._c = (this._c + c) | 0 + this._d = (this._d + d) | 0 +} + +MD5.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.allocUnsafe(16) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fnF (a, b, c, d, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 +} + +function fnG (a, b, c, d, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 +} + +function fnH (a, b, c, d, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 +} + +function fnI (a, b, c, d, m, k, s) { + return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 +} + +module.exports = MD5 + +},{"hash-base":30,"inherits":31,"safe-buffer":40}],33:[function(require,module,exports){ +exports.pbkdf2 = require('./lib/async') +exports.pbkdf2Sync = require('./lib/sync') + +},{"./lib/async":34,"./lib/sync":37}],34:[function(require,module,exports){ +(function (process,global){(function (){ +var checkParameters = require('./precondition') +var defaultEncoding = require('./default-encoding') +var sync = require('./sync') +var Buffer = require('safe-buffer').Buffer + +var ZERO_BUF +var subtle = global.crypto && global.crypto.subtle +var toBrowser = { + 'sha': 'SHA-1', + 'sha-1': 'SHA-1', + 'sha1': 'SHA-1', + 'sha256': 'SHA-256', + 'sha-256': 'SHA-256', + 'sha384': 'SHA-384', + 'sha-384': 'SHA-384', + 'sha-512': 'SHA-512', + 'sha512': 'SHA-512' +} +var checks = [] +function checkNative (algo) { + if (global.process && !global.process.browser) { + return Promise.resolve(false) + } + if (!subtle || !subtle.importKey || !subtle.deriveBits) { + return Promise.resolve(false) + } + if (checks[algo] !== undefined) { + return checks[algo] + } + ZERO_BUF = ZERO_BUF || Buffer.alloc(8) + var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) + .then(function () { + return true + }).catch(function () { + return false + }) + checks[algo] = prom + return prom +} + +function browserPbkdf2 (password, salt, iterations, length, algo) { + return subtle.importKey( + 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] + ).then(function (key) { + return subtle.deriveBits({ + name: 'PBKDF2', + salt: salt, + iterations: iterations, + hash: { + name: algo + } + }, key, length << 3) + }).then(function (res) { + return Buffer.from(res) + }) +} + +function resolvePromise (promise, callback) { + promise.then(function (out) { + process.nextTick(function () { + callback(null, out) + }) + }, function (e) { + process.nextTick(function () { + callback(e) + }) + }) +} +module.exports = function (password, salt, iterations, keylen, digest, callback) { + if (typeof digest === 'function') { + callback = digest + digest = undefined + } + + digest = digest || 'sha1' + var algo = toBrowser[digest.toLowerCase()] + + if (!algo || typeof global.Promise !== 'function') { + return process.nextTick(function () { + var out + try { + out = sync(password, salt, iterations, keylen, digest) + } catch (e) { + return callback(e) + } + callback(null, out) + }) + } + + checkParameters(password, salt, iterations, keylen) + if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') + if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) + + resolvePromise(checkNative(algo).then(function (resp) { + if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo) + + return sync(password, salt, iterations, keylen, digest) + }), callback) +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./default-encoding":35,"./precondition":36,"./sync":37,"_process":8,"safe-buffer":40}],35:[function(require,module,exports){ +(function (process){(function (){ +var defaultEncoding +/* istanbul ignore next */ +if (process.browser) { + defaultEncoding = 'utf-8' +} else { + var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) + + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' +} +module.exports = defaultEncoding + +}).call(this)}).call(this,require('_process')) +},{"_process":8}],36:[function(require,module,exports){ +(function (Buffer){(function (){ +var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs + +function checkBuffer (buf, name) { + if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) { + throw new TypeError(name + ' must be a buffer or string') + } +} + +module.exports = function (password, salt, iterations, keylen) { + checkBuffer(password, 'Password') + checkBuffer(salt, 'Salt') + + if (typeof iterations !== 'number') { + throw new TypeError('Iterations not a number') + } + + if (iterations < 0) { + throw new TypeError('Bad iterations') + } + + if (typeof keylen !== 'number') { + throw new TypeError('Key length not a number') + } + + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ + throw new TypeError('Bad key length') + } +} + +}).call(this)}).call(this,{"isBuffer":require("../../../../../../AppData/Roaming/npm/node_modules/browserify/node_modules/is-buffer/index.js")}) +},{"../../../../../../AppData/Roaming/npm/node_modules/browserify/node_modules/is-buffer/index.js":7}],37:[function(require,module,exports){ +var md5 = require('create-hash/md5') +var RIPEMD160 = require('ripemd160') +var sha = require('sha.js') + +var checkParameters = require('./precondition') +var defaultEncoding = require('./default-encoding') +var Buffer = require('safe-buffer').Buffer +var ZEROS = Buffer.alloc(128) +var sizes = { + md5: 16, + sha1: 20, + sha224: 28, + sha256: 32, + sha384: 48, + sha512: 64, + rmd160: 20, + ripemd160: 20 +} + +function Hmac (alg, key, saltLen) { + var hash = getDigest(alg) + var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 + + if (key.length > blocksize) { + key = hash(key) + } else if (key.length < blocksize) { + key = Buffer.concat([key, ZEROS], blocksize) + } + + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) + var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) + for (var i = 0; i < blocksize; i++) { + ipad[i] = key[i] ^ 0x36 + opad[i] = key[i] ^ 0x5C + } + + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) + ipad.copy(ipad1, 0, 0, blocksize) + this.ipad1 = ipad1 + this.ipad2 = ipad + this.opad = opad + this.alg = alg + this.blocksize = blocksize + this.hash = hash + this.size = sizes[alg] +} + +Hmac.prototype.run = function (data, ipad) { + data.copy(ipad, this.blocksize) + var h = this.hash(ipad) + h.copy(this.opad, this.blocksize) + return this.hash(this.opad) +} + +function getDigest (alg) { + function shaFunc (data) { + return sha(alg).update(data).digest() + } + function rmd160Func (data) { + return new RIPEMD160().update(data).digest() + } + + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func + if (alg === 'md5') return md5 + return shaFunc +} + +function pbkdf2 (password, salt, iterations, keylen, digest) { + checkParameters(password, salt, iterations, keylen) + + if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) + if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) + + digest = digest || 'sha1' + + var hmac = new Hmac(digest, password, salt.length) + + var DK = Buffer.allocUnsafe(keylen) + var block1 = Buffer.allocUnsafe(salt.length + 4) + salt.copy(block1, 0, 0, salt.length) + + var destPos = 0 + var hLen = sizes[digest] + var l = Math.ceil(keylen / hLen) + + for (var i = 1; i <= l; i++) { + block1.writeUInt32BE(i, salt.length) + + var T = hmac.run(block1, hmac.ipad1) + var U = T + + for (var j = 1; j < iterations; j++) { + U = hmac.run(U, hmac.ipad2) + for (var k = 0; k < hLen; k++) T[k] ^= U[k] + } + + T.copy(DK, destPos) + destPos += hLen + } + + return DK +} + +module.exports = pbkdf2 + +},{"./default-encoding":35,"./precondition":36,"create-hash/md5":29,"ripemd160":39,"safe-buffer":40,"sha.js":42}],38:[function(require,module,exports){ +(function (process,global){(function (){ +'use strict' + +// limit of Crypto.getRandomValues() +// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues +var MAX_BYTES = 65536 + +// Node supports requesting up to this number of bytes +// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 +var MAX_UINT32 = 4294967295 + +function oldBrowser () { + throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') +} + +var Buffer = require('safe-buffer').Buffer +var crypto = global.crypto || global.msCrypto + +if (crypto && crypto.getRandomValues) { + module.exports = randomBytes +} else { + module.exports = oldBrowser +} + +function randomBytes (size, cb) { + // phantomjs needs to throw + if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') + + var bytes = Buffer.allocUnsafe(size) + + if (size > 0) { // getRandomValues fails on IE if size == 0 + if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues + // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues + for (var generated = 0; generated < size; generated += MAX_BYTES) { + // buffer.slice automatically checks if the end is past the end of + // the buffer so we don't have to here + crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) + } + } else { + crypto.getRandomValues(bytes) + } + } + + if (typeof cb === 'function') { + return process.nextTick(function () { + cb(null, bytes) + }) + } + + return bytes +} + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":8,"safe-buffer":40}],39:[function(require,module,exports){ +'use strict' +var Buffer = require('buffer').Buffer +var inherits = require('inherits') +var HashBase = require('hash-base') + +var ARRAY16 = new Array(16) + +var zl = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 +] + +var zr = [ + 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 +] + +var sl = [ + 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 +] + +var sr = [ + 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 +] + +var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] +var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] + +function RIPEMD160 () { + HashBase.call(this, 64) + + // state + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 +} + +inherits(RIPEMD160, HashBase) + +RIPEMD160.prototype._update = function () { + var words = ARRAY16 + for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) + + var al = this._a | 0 + var bl = this._b | 0 + var cl = this._c | 0 + var dl = this._d | 0 + var el = this._e | 0 + + var ar = this._a | 0 + var br = this._b | 0 + var cr = this._c | 0 + var dr = this._d | 0 + var er = this._e | 0 + + // computation + for (var i = 0; i < 80; i += 1) { + var tl + var tr + if (i < 16) { + tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) + tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) + } else if (i < 32) { + tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) + tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) + } else if (i < 48) { + tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) + tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) + } else if (i < 64) { + tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) + tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) + } else { // if (i<80) { + tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) + tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) + } + + al = el + el = dl + dl = rotl(cl, 10) + cl = bl + bl = tl + + ar = er + er = dr + dr = rotl(cr, 10) + cr = br + br = tr + } + + // update state + var t = (this._b + cl + dr) | 0 + this._b = (this._c + dl + er) | 0 + this._c = (this._d + el + ar) | 0 + this._d = (this._e + al + br) | 0 + this._e = (this._a + bl + cr) | 0 + this._a = t +} + +RIPEMD160.prototype._digest = function () { + // create padding and handle blocks + this._block[this._blockOffset++] = 0x80 + if (this._blockOffset > 56) { + this._block.fill(0, this._blockOffset, 64) + this._update() + this._blockOffset = 0 + } + + this._block.fill(0, this._blockOffset, 56) + this._block.writeUInt32LE(this._length[0], 56) + this._block.writeUInt32LE(this._length[1], 60) + this._update() + + // produce result + var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) + buffer.writeInt32LE(this._a, 0) + buffer.writeInt32LE(this._b, 4) + buffer.writeInt32LE(this._c, 8) + buffer.writeInt32LE(this._d, 12) + buffer.writeInt32LE(this._e, 16) + return buffer +} + +function rotl (x, n) { + return (x << n) | (x >>> (32 - n)) +} + +function fn1 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn2 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 +} + +function fn3 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 +} + +function fn4 (a, b, c, d, e, m, k, s) { + return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 +} + +function fn5 (a, b, c, d, e, m, k, s) { + return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 +} + +module.exports = RIPEMD160 + +},{"buffer":3,"hash-base":30,"inherits":31}],40:[function(require,module,exports){ +/* 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) +} + +},{"buffer":3}],41:[function(require,module,exports){ +var Buffer = require('safe-buffer').Buffer + +// prototype class for hash functions +function Hash (blockSize, finalSize) { + this._block = Buffer.alloc(blockSize) + this._finalSize = finalSize + this._blockSize = blockSize + this._len = 0 +} + +Hash.prototype.update = function (data, enc) { + if (typeof data === 'string') { + enc = enc || 'utf8' + data = Buffer.from(data, enc) + } + + var block = this._block + var blockSize = this._blockSize + var length = data.length + var accum = this._len + + for (var offset = 0; offset < length;) { + var assigned = accum % blockSize + var remainder = Math.min(length - offset, blockSize - assigned) + + for (var i = 0; i < remainder; i++) { + block[assigned + i] = data[offset + i] + } + + accum += remainder + offset += remainder + + if ((accum % blockSize) === 0) { + this._update(block) + } + } + + this._len += length + return this +} + +Hash.prototype.digest = function (enc) { + var rem = this._len % this._blockSize + + this._block[rem] = 0x80 + + // zero (rem + 1) trailing bits, where (rem + 1) is the smallest + // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize + this._block.fill(0, rem + 1) + + if (rem >= this._finalSize) { + this._update(this._block) + this._block.fill(0) + } + + var bits = this._len * 8 + + // uint32 + if (bits <= 0xffffffff) { + this._block.writeUInt32BE(bits, this._blockSize - 4) + + // uint64 + } else { + var lowBits = (bits & 0xffffffff) >>> 0 + var highBits = (bits - lowBits) / 0x100000000 + + this._block.writeUInt32BE(highBits, this._blockSize - 8) + this._block.writeUInt32BE(lowBits, this._blockSize - 4) + } + + this._update(this._block) + var hash = this._hash() + + return enc ? hash.toString(enc) : hash +} + +Hash.prototype._update = function () { + throw new Error('_update must be implemented by subclass') +} + +module.exports = Hash + +},{"safe-buffer":40}],42:[function(require,module,exports){ +var exports = module.exports = function SHA (algorithm) { + algorithm = algorithm.toLowerCase() + + var Algorithm = exports[algorithm] + if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') + + return new Algorithm() +} + +exports.sha = require('./sha') +exports.sha1 = require('./sha1') +exports.sha224 = require('./sha224') +exports.sha256 = require('./sha256') +exports.sha384 = require('./sha384') +exports.sha512 = require('./sha512') + +},{"./sha":43,"./sha1":44,"./sha224":45,"./sha256":46,"./sha384":47,"./sha512":48}],43:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined + * in FIPS PUB 180-1 + * This source code is derived from sha1.js of the same repository. + * The difference between SHA-0 and SHA-1 is just a bitwise rotate left + * operation was added. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha, Hash) + +Sha.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha + +},{"./hash":41,"inherits":31,"safe-buffer":40}],44:[function(require,module,exports){ +/* + * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined + * in FIPS PUB 180-1 + * Version 2.1a Copyright Paul Johnston 2000 - 2002. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for details. + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 +] + +var W = new Array(80) + +function Sha1 () { + this.init() + this._w = W + + Hash.call(this, 64, 56) +} + +inherits(Sha1, Hash) + +Sha1.prototype.init = function () { + this._a = 0x67452301 + this._b = 0xefcdab89 + this._c = 0x98badcfe + this._d = 0x10325476 + this._e = 0xc3d2e1f0 + + return this +} + +function rotl1 (num) { + return (num << 1) | (num >>> 31) +} + +function rotl5 (num) { + return (num << 5) | (num >>> 27) +} + +function rotl30 (num) { + return (num << 30) | (num >>> 2) +} + +function ft (s, b, c, d) { + if (s === 0) return (b & c) | ((~b) & d) + if (s === 2) return (b & c) | (b & d) | (c & d) + return b ^ c ^ d +} + +Sha1.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) + + for (var j = 0; j < 80; ++j) { + var s = ~~(j / 20) + var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 + + e = d + d = c + c = rotl30(b) + b = a + a = t + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 +} + +Sha1.prototype._hash = function () { + var H = Buffer.allocUnsafe(20) + + H.writeInt32BE(this._a | 0, 0) + H.writeInt32BE(this._b | 0, 4) + H.writeInt32BE(this._c | 0, 8) + H.writeInt32BE(this._d | 0, 12) + H.writeInt32BE(this._e | 0, 16) + + return H +} + +module.exports = Sha1 + +},{"./hash":41,"inherits":31,"safe-buffer":40}],45:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Sha256 = require('./sha256') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(64) + +function Sha224 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha224, Sha256) + +Sha224.prototype.init = function () { + this._a = 0xc1059ed8 + this._b = 0x367cd507 + this._c = 0x3070dd17 + this._d = 0xf70e5939 + this._e = 0xffc00b31 + this._f = 0x68581511 + this._g = 0x64f98fa7 + this._h = 0xbefa4fa4 + + return this +} + +Sha224.prototype._hash = function () { + var H = Buffer.allocUnsafe(28) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + + return H +} + +module.exports = Sha224 + +},{"./hash":41,"./sha256":46,"inherits":31,"safe-buffer":40}],46:[function(require,module,exports){ +/** + * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined + * in FIPS 180-2 + * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * + */ + +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 +] + +var W = new Array(64) + +function Sha256 () { + this.init() + + this._w = W // new Array(64) + + Hash.call(this, 64, 56) +} + +inherits(Sha256, Hash) + +Sha256.prototype.init = function () { + this._a = 0x6a09e667 + this._b = 0xbb67ae85 + this._c = 0x3c6ef372 + this._d = 0xa54ff53a + this._e = 0x510e527f + this._f = 0x9b05688c + this._g = 0x1f83d9ab + this._h = 0x5be0cd19 + + return this +} + +function ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x) { + return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) +} + +function sigma1 (x) { + return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) +} + +function gamma0 (x) { + return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) +} + +function gamma1 (x) { + return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) +} + +Sha256.prototype._update = function (M) { + var W = this._w + + var a = this._a | 0 + var b = this._b | 0 + var c = this._c | 0 + var d = this._d | 0 + var e = this._e | 0 + var f = this._f | 0 + var g = this._g | 0 + var h = this._h | 0 + + for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) + for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 + + for (var j = 0; j < 64; ++j) { + var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 + var T2 = (sigma0(a) + maj(a, b, c)) | 0 + + h = g + g = f + f = e + e = (d + T1) | 0 + d = c + c = b + b = a + a = (T1 + T2) | 0 + } + + this._a = (a + this._a) | 0 + this._b = (b + this._b) | 0 + this._c = (c + this._c) | 0 + this._d = (d + this._d) | 0 + this._e = (e + this._e) | 0 + this._f = (f + this._f) | 0 + this._g = (g + this._g) | 0 + this._h = (h + this._h) | 0 +} + +Sha256.prototype._hash = function () { + var H = Buffer.allocUnsafe(32) + + H.writeInt32BE(this._a, 0) + H.writeInt32BE(this._b, 4) + H.writeInt32BE(this._c, 8) + H.writeInt32BE(this._d, 12) + H.writeInt32BE(this._e, 16) + H.writeInt32BE(this._f, 20) + H.writeInt32BE(this._g, 24) + H.writeInt32BE(this._h, 28) + + return H +} + +module.exports = Sha256 + +},{"./hash":41,"inherits":31,"safe-buffer":40}],47:[function(require,module,exports){ +var inherits = require('inherits') +var SHA512 = require('./sha512') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var W = new Array(160) + +function Sha384 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha384, SHA512) + +Sha384.prototype.init = function () { + this._ah = 0xcbbb9d5d + this._bh = 0x629a292a + this._ch = 0x9159015a + this._dh = 0x152fecd8 + this._eh = 0x67332667 + this._fh = 0x8eb44a87 + this._gh = 0xdb0c2e0d + this._hh = 0x47b5481d + + this._al = 0xc1059ed8 + this._bl = 0x367cd507 + this._cl = 0x3070dd17 + this._dl = 0xf70e5939 + this._el = 0xffc00b31 + this._fl = 0x68581511 + this._gl = 0x64f98fa7 + this._hl = 0xbefa4fa4 + + return this +} + +Sha384.prototype._hash = function () { + var H = Buffer.allocUnsafe(48) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + + return H +} + +module.exports = Sha384 + +},{"./hash":41,"./sha512":48,"inherits":31,"safe-buffer":40}],48:[function(require,module,exports){ +var inherits = require('inherits') +var Hash = require('./hash') +var Buffer = require('safe-buffer').Buffer + +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +] + +var W = new Array(160) + +function Sha512 () { + this.init() + this._w = W + + Hash.call(this, 128, 112) +} + +inherits(Sha512, Hash) + +Sha512.prototype.init = function () { + this._ah = 0x6a09e667 + this._bh = 0xbb67ae85 + this._ch = 0x3c6ef372 + this._dh = 0xa54ff53a + this._eh = 0x510e527f + this._fh = 0x9b05688c + this._gh = 0x1f83d9ab + this._hh = 0x5be0cd19 + + this._al = 0xf3bcc908 + this._bl = 0x84caa73b + this._cl = 0xfe94f82b + this._dl = 0x5f1d36f1 + this._el = 0xade682d1 + this._fl = 0x2b3e6c1f + this._gl = 0xfb41bd6b + this._hl = 0x137e2179 + + return this +} + +function Ch (x, y, z) { + return z ^ (x & (y ^ z)) +} + +function maj (x, y, z) { + return (x & y) | (z & (x | y)) +} + +function sigma0 (x, xl) { + return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) +} + +function sigma1 (x, xl) { + return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) +} + +function Gamma0 (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) +} + +function Gamma0l (x, xl) { + return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) +} + +function Gamma1 (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) +} + +function Gamma1l (x, xl) { + return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) +} + +function getCarry (a, b) { + return (a >>> 0) < (b >>> 0) ? 1 : 0 +} + +Sha512.prototype._update = function (M) { + var W = this._w + + var ah = this._ah | 0 + var bh = this._bh | 0 + var ch = this._ch | 0 + var dh = this._dh | 0 + var eh = this._eh | 0 + var fh = this._fh | 0 + var gh = this._gh | 0 + var hh = this._hh | 0 + + var al = this._al | 0 + var bl = this._bl | 0 + var cl = this._cl | 0 + var dl = this._dl | 0 + var el = this._el | 0 + var fl = this._fl | 0 + var gl = this._gl | 0 + var hl = this._hl | 0 + + for (var i = 0; i < 32; i += 2) { + W[i] = M.readInt32BE(i * 4) + W[i + 1] = M.readInt32BE(i * 4 + 4) + } + for (; i < 160; i += 2) { + var xh = W[i - 15 * 2] + var xl = W[i - 15 * 2 + 1] + var gamma0 = Gamma0(xh, xl) + var gamma0l = Gamma0l(xl, xh) + + xh = W[i - 2 * 2] + xl = W[i - 2 * 2 + 1] + var gamma1 = Gamma1(xh, xl) + var gamma1l = Gamma1l(xl, xh) + + // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] + var Wi7h = W[i - 7 * 2] + var Wi7l = W[i - 7 * 2 + 1] + + var Wi16h = W[i - 16 * 2] + var Wi16l = W[i - 16 * 2 + 1] + + var Wil = (gamma0l + Wi7l) | 0 + var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 + Wil = (Wil + gamma1l) | 0 + Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 + Wil = (Wil + Wi16l) | 0 + Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 + + W[i] = Wih + W[i + 1] = Wil + } + + for (var j = 0; j < 160; j += 2) { + Wih = W[j] + Wil = W[j + 1] + + var majh = maj(ah, bh, ch) + var majl = maj(al, bl, cl) + + var sigma0h = sigma0(ah, al) + var sigma0l = sigma0(al, ah) + var sigma1h = sigma1(eh, el) + var sigma1l = sigma1(el, eh) + + // t1 = h + sigma1 + ch + K[j] + W[j] + var Kih = K[j] + var Kil = K[j + 1] + + var chh = Ch(eh, fh, gh) + var chl = Ch(el, fl, gl) + + var t1l = (hl + sigma1l) | 0 + var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 + t1l = (t1l + chl) | 0 + t1h = (t1h + chh + getCarry(t1l, chl)) | 0 + t1l = (t1l + Kil) | 0 + t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 + t1l = (t1l + Wil) | 0 + t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 + + // t2 = sigma0 + maj + var t2l = (sigma0l + majl) | 0 + var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + el = (dl + t1l) | 0 + eh = (dh + t1h + getCarry(el, dl)) | 0 + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + al = (t1l + t2l) | 0 + ah = (t1h + t2h + getCarry(al, t1l)) | 0 + } + + this._al = (this._al + al) | 0 + this._bl = (this._bl + bl) | 0 + this._cl = (this._cl + cl) | 0 + this._dl = (this._dl + dl) | 0 + this._el = (this._el + el) | 0 + this._fl = (this._fl + fl) | 0 + this._gl = (this._gl + gl) | 0 + this._hl = (this._hl + hl) | 0 + + this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 + this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 + this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 + this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 + this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 + this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 + this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 + this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 +} + +Sha512.prototype._hash = function () { + var H = Buffer.allocUnsafe(64) + + function writeInt64BE (h, l, offset) { + H.writeInt32BE(h, offset) + H.writeInt32BE(l, offset + 4) + } + + writeInt64BE(this._ah, this._al, 0) + writeInt64BE(this._bh, this._bl, 8) + writeInt64BE(this._ch, this._cl, 16) + writeInt64BE(this._dh, this._dl, 24) + writeInt64BE(this._eh, this._el, 32) + writeInt64BE(this._fh, this._fl, 40) + writeInt64BE(this._gh, this._gl, 48) + writeInt64BE(this._hh, this._hl, 56) + + return H +} + +module.exports = Sha512 + +},{"./hash":41,"inherits":31,"safe-buffer":40}],49:[function(require,module,exports){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// browserify by default only pulls in files that are hard coded in requires +// In order of last to first in this file, the default wordlist will be chosen +// based on what is present. (Bundles may remove wordlists they don't need) +const wordlists = {}; +exports.wordlists = wordlists; +let _default; +exports._default = _default; +try { + exports._default = _default = require('./wordlists/czech.json'); + wordlists.czech = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/chinese_simplified.json'); + wordlists.chinese_simplified = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/chinese_traditional.json'); + wordlists.chinese_traditional = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/korean.json'); + wordlists.korean = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/french.json'); + wordlists.french = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/italian.json'); + wordlists.italian = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/spanish.json'); + wordlists.spanish = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/japanese.json'); + wordlists.japanese = _default; + wordlists.JA = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/portuguese.json'); + wordlists.portuguese = _default; +} +catch (err) { } +try { + exports._default = _default = require('./wordlists/english.json'); + wordlists.english = _default; + wordlists.EN = _default; +} +catch (err) { } + +},{"./wordlists/chinese_simplified.json":51,"./wordlists/chinese_traditional.json":undefined,"./wordlists/czech.json":undefined,"./wordlists/english.json":52,"./wordlists/french.json":undefined,"./wordlists/italian.json":undefined,"./wordlists/japanese.json":53,"./wordlists/korean.json":undefined,"./wordlists/portuguese.json":54,"./wordlists/spanish.json":undefined}],50:[function(require,module,exports){ +(function (Buffer){(function (){ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const createHash = require("create-hash"); +const pbkdf2_1 = require("pbkdf2"); +const randomBytes = require("randombytes"); +const _wordlists_1 = require("./_wordlists"); +let DEFAULT_WORDLIST = _wordlists_1._default; +const INVALID_MNEMONIC = 'Invalid mnemonic'; +const INVALID_ENTROPY = 'Invalid entropy'; +const INVALID_CHECKSUM = 'Invalid mnemonic checksum'; +const WORDLIST_REQUIRED = 'A wordlist is required but a default could not be found.\n' + + 'Please pass a 2048 word array explicitly.'; +function pbkdf2Promise(password, saltMixin, iterations, keylen, digest) { + return Promise.resolve().then(() => new Promise((resolve, reject) => { + const callback = (err, derivedKey) => { + if (err) { + return reject(err); + } + else { + return resolve(derivedKey); + } + }; + pbkdf2_1.pbkdf2(password, saltMixin, iterations, keylen, digest, callback); + })); +} +function normalize(str) { + return (str || '').normalize('NFKD'); +} +function lpad(str, padString, length) { + while (str.length < length) { + str = padString + str; + } + return str; +} +function binaryToByte(bin) { + return parseInt(bin, 2); +} +function bytesToBinary(bytes) { + return bytes.map((x) => lpad(x.toString(2), '0', 8)).join(''); +} +function deriveChecksumBits(entropyBuffer) { + const ENT = entropyBuffer.length * 8; + const CS = ENT / 32; + const hash = createHash('sha256') + .update(entropyBuffer) + .digest(); + return bytesToBinary(Array.from(hash)).slice(0, CS); +} +function salt(password) { + return 'mnemonic' + (password || ''); +} +function mnemonicToSeedSync(mnemonic, password) { + const mnemonicBuffer = Buffer.from(normalize(mnemonic), 'utf8'); + const saltBuffer = Buffer.from(salt(normalize(password)), 'utf8'); + return pbkdf2_1.pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512'); +} +exports.mnemonicToSeedSync = mnemonicToSeedSync; +function mnemonicToSeed(mnemonic, password) { + return Promise.resolve().then(() => { + const mnemonicBuffer = Buffer.from(normalize(mnemonic), 'utf8'); + const saltBuffer = Buffer.from(salt(normalize(password)), 'utf8'); + return pbkdf2Promise(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512'); + }); +} +exports.mnemonicToSeed = mnemonicToSeed; +function mnemonicToEntropy(mnemonic, wordlist) { + wordlist = wordlist || DEFAULT_WORDLIST; + if (!wordlist) { + throw new Error(WORDLIST_REQUIRED); + } + const words = normalize(mnemonic).split(' '); + if (words.length % 3 !== 0) { + throw new Error(INVALID_MNEMONIC); + } + // convert word indices to 11 bit binary strings + const bits = words + .map((word) => { + const index = wordlist.indexOf(word); + if (index === -1) { + throw new Error(INVALID_MNEMONIC); + } + return lpad(index.toString(2), '0', 11); + }) + .join(''); + // split the binary string into ENT/CS + const dividerIndex = Math.floor(bits.length / 33) * 32; + const entropyBits = bits.slice(0, dividerIndex); + const checksumBits = bits.slice(dividerIndex); + // calculate the checksum and compare + const entropyBytes = entropyBits.match(/(.{1,8})/g).map(binaryToByte); + if (entropyBytes.length < 16) { + throw new Error(INVALID_ENTROPY); + } + if (entropyBytes.length > 32) { + throw new Error(INVALID_ENTROPY); + } + if (entropyBytes.length % 4 !== 0) { + throw new Error(INVALID_ENTROPY); + } + const entropy = Buffer.from(entropyBytes); + const newChecksum = deriveChecksumBits(entropy); + if (newChecksum !== checksumBits) { + throw new Error(INVALID_CHECKSUM); + } + return entropy.toString('hex'); +} +exports.mnemonicToEntropy = mnemonicToEntropy; +function entropyToMnemonic(entropy, wordlist) { + if (!Buffer.isBuffer(entropy)) { + entropy = Buffer.from(entropy, 'hex'); + } + wordlist = wordlist || DEFAULT_WORDLIST; + if (!wordlist) { + throw new Error(WORDLIST_REQUIRED); + } + // 128 <= ENT <= 256 + if (entropy.length < 16) { + throw new TypeError(INVALID_ENTROPY); + } + if (entropy.length > 32) { + throw new TypeError(INVALID_ENTROPY); + } + if (entropy.length % 4 !== 0) { + throw new TypeError(INVALID_ENTROPY); + } + const entropyBits = bytesToBinary(Array.from(entropy)); + const checksumBits = deriveChecksumBits(entropy); + const bits = entropyBits + checksumBits; + const chunks = bits.match(/(.{1,11})/g); + const words = chunks.map((binary) => { + const index = binaryToByte(binary); + return wordlist[index]; + }); + return wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093' // Japanese wordlist + ? words.join('\u3000') + : words.join(' '); +} +exports.entropyToMnemonic = entropyToMnemonic; +function generateMnemonic(strength, rng, wordlist) { + strength = strength || 128; + if (strength % 32 !== 0) { + throw new TypeError(INVALID_ENTROPY); + } + rng = rng || randomBytes; + return entropyToMnemonic(rng(strength / 8), wordlist); +} +exports.generateMnemonic = generateMnemonic; +function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +exports.validateMnemonic = validateMnemonic; +function setDefaultWordlist(language) { + const result = _wordlists_1.wordlists[language]; + if (result) { + DEFAULT_WORDLIST = result; + } + else { + throw new Error('Could not find wordlist for language "' + language + '"'); + } +} +exports.setDefaultWordlist = setDefaultWordlist; +function getDefaultWordlist() { + if (!DEFAULT_WORDLIST) { + throw new Error('No Default Wordlist set'); + } + return Object.keys(_wordlists_1.wordlists).filter((lang) => { + if (lang === 'JA' || lang === 'EN') { + return false; + } + return _wordlists_1.wordlists[lang].every((word, index) => word === DEFAULT_WORDLIST[index]); + })[0]; +} +exports.getDefaultWordlist = getDefaultWordlist; +var _wordlists_2 = require("./_wordlists"); +exports.wordlists = _wordlists_2.wordlists; + +}).call(this)}).call(this,require("buffer").Buffer) +},{"./_wordlists":49,"buffer":3,"create-hash":28,"pbkdf2":33,"randombytes":38}],51:[function(require,module,exports){ +module.exports=[ + "的", + "一", + "是", + "在", + "不", + "了", + "有", + "和", + "人", + "这", + "中", + "大", + "为", + "上", + "个", + "国", + "我", + "以", + "要", + "他", + "时", + "来", + "用", + "们", + "生", + "到", + "作", + "地", + "于", + "出", + "就", + "分", + "对", + "成", + "会", + "可", + "主", + "发", + "年", + "动", + "同", + "工", + "也", + "能", + "下", + "过", + "子", + "说", + "产", + "种", + "面", + "而", + "方", + "后", + "多", + "定", + "行", + "学", + "法", + "所", + "民", + "得", + "经", + "十", + "三", + "之", + "进", + "着", + "等", + "部", + "度", + "家", + "电", + "力", + "里", + "如", + "水", + "化", + "高", + "自", + "二", + "理", + "起", + "小", + "物", + "现", + "实", + "加", + "量", + "都", + "两", + "体", + "制", + "机", + "当", + "使", + "点", + "从", + "业", + "本", + "去", + "把", + "性", + "好", + "应", + "开", + "它", + "合", + "还", + "因", + "由", + "其", + "些", + "然", + "前", + "外", + "天", + "政", + "四", + "日", + "那", + "社", + "义", + "事", + "平", + "形", + "相", + "全", + "表", + "间", + "样", + "与", + "关", + "各", + "重", + "新", + "线", + "内", + "数", + "正", + "心", + "反", + "你", + "明", + "看", + "原", + "又", + "么", + "利", + "比", + "或", + "但", + "质", + "气", + "第", + "向", + "道", + "命", + "此", + "变", + "条", + "只", + "没", + "结", + "解", + "问", + "意", + "建", + "月", + "公", + "无", + "系", + "军", + "很", + "情", + "者", + "最", + "立", + "代", + "想", + "已", + "通", + "并", + "提", + "直", + "题", + "党", + "程", + "展", + "五", + "果", + "料", + "象", + "员", + "革", + "位", + "入", + "常", + "文", + "总", + "次", + "品", + "式", + "活", + "设", + "及", + "管", + "特", + "件", + "长", + "求", + "老", + "头", + "基", + "资", + "边", + "流", + "路", + "级", + "少", + "图", + "山", + "统", + "接", + "知", + "较", + "将", + "组", + "见", + "计", + "别", + "她", + "手", + "角", + "期", + "根", + "论", + "运", + "农", + "指", + "几", + "九", + "区", + "强", + "放", + "决", + "西", + "被", + "干", + "做", + "必", + "战", + "先", + "回", + "则", + "任", + "取", + "据", + "处", + "队", + "南", + "给", + "色", + "光", + "门", + "即", + "保", + "治", + "北", + "造", + "百", + "规", + "热", + "领", + "七", + "海", + "口", + "东", + "导", + "器", + "压", + "志", + "世", + "金", + "增", + "争", + "济", + "阶", + "油", + "思", + "术", + "极", + "交", + "受", + "联", + "什", + "认", + "六", + "共", + "权", + "收", + "证", + "改", + "清", + "美", + "再", + "采", + "转", + "更", + "单", + "风", + "切", + "打", + "白", + "教", + "速", + "花", + "带", + "安", + "场", + "身", + "车", + "例", + "真", + "务", + "具", + "万", + "每", + "目", + "至", + "达", + "走", + "积", + "示", + "议", + "声", + "报", + "斗", + "完", + "类", + "八", + "离", + "华", + "名", + "确", + "才", + "科", + "张", + "信", + "马", + "节", + "话", + "米", + "整", + "空", + "元", + "况", + "今", + "集", + "温", + "传", + "土", + "许", + "步", + "群", + "广", + "石", + "记", + "需", + "段", + "研", + "界", + "拉", + "林", + "律", + "叫", + "且", + "究", + "观", + "越", + "织", + "装", + "影", + "算", + "低", + "持", + "音", + "众", + "书", + "布", + "复", + "容", + "儿", + "须", + "际", + "商", + "非", + "验", + "连", + "断", + "深", + "难", + "近", + "矿", + "千", + "周", + "委", + "素", + "技", + "备", + "半", + "办", + "青", + "省", + "列", + "习", + "响", + "约", + "支", + "般", + "史", + "感", + "劳", + "便", + "团", + "往", + "酸", + "历", + "市", + "克", + "何", + "除", + "消", + "构", + "府", + "称", + "太", + "准", + "精", + "值", + "号", + "率", + "族", + "维", + "划", + "选", + "标", + "写", + "存", + "候", + "毛", + "亲", + "快", + "效", + "斯", + "院", + "查", + "江", + "型", + "眼", + "王", + "按", + "格", + "养", + "易", + "置", + "派", + "层", + "片", + "始", + "却", + "专", + "状", + "育", + "厂", + "京", + "识", + "适", + "属", + "圆", + "包", + "火", + "住", + "调", + "满", + "县", + "局", + "照", + "参", + "红", + "细", + "引", + "听", + "该", + "铁", + "价", + "严", + "首", + "底", + "液", + "官", + "德", + "随", + "病", + "苏", + "失", + "尔", + "死", + "讲", + "配", + "女", + "黄", + "推", + "显", + "谈", + "罪", + "神", + "艺", + "呢", + "席", + "含", + "企", + "望", + "密", + "批", + "营", + "项", + "防", + "举", + "球", + "英", + "氧", + "势", + "告", + "李", + "台", + "落", + "木", + "帮", + "轮", + "破", + "亚", + "师", + "围", + "注", + "远", + "字", + "材", + "排", + "供", + "河", + "态", + "封", + "另", + "施", + "减", + "树", + "溶", + "怎", + "止", + "案", + "言", + "士", + "均", + "武", + "固", + "叶", + "鱼", + "波", + "视", + "仅", + "费", + "紧", + "爱", + "左", + "章", + "早", + "朝", + "害", + "续", + "轻", + "服", + "试", + "食", + "充", + "兵", + "源", + "判", + "护", + "司", + "足", + "某", + "练", + "差", + "致", + "板", + "田", + "降", + "黑", + "犯", + "负", + "击", + "范", + "继", + "兴", + "似", + "余", + "坚", + "曲", + "输", + "修", + "故", + "城", + "夫", + "够", + "送", + "笔", + "船", + "占", + "右", + "财", + "吃", + "富", + "春", + "职", + "觉", + "汉", + "画", + "功", + "巴", + "跟", + "虽", + "杂", + "飞", + "检", + "吸", + "助", + "升", + "阳", + "互", + "初", + "创", + "抗", + "考", + "投", + "坏", + "策", + "古", + "径", + "换", + "未", + "跑", + "留", + "钢", + "曾", + "端", + "责", + "站", + "简", + "述", + "钱", + "副", + "尽", + "帝", + "射", + "草", + "冲", + "承", + "独", + "令", + "限", + "阿", + "宣", + "环", + "双", + "请", + "超", + "微", + "让", + "控", + "州", + "良", + "轴", + "找", + "否", + "纪", + "益", + "依", + "优", + "顶", + "础", + "载", + "倒", + "房", + "突", + "坐", + "粉", + "敌", + "略", + "客", + "袁", + "冷", + "胜", + "绝", + "析", + "块", + "剂", + "测", + "丝", + "协", + "诉", + "念", + "陈", + "仍", + "罗", + "盐", + "友", + "洋", + "错", + "苦", + "夜", + "刑", + "移", + "频", + "逐", + "靠", + "混", + "母", + "短", + "皮", + "终", + "聚", + "汽", + "村", + "云", + "哪", + "既", + "距", + "卫", + "停", + "烈", + "央", + "察", + "烧", + "迅", + "境", + "若", + "印", + "洲", + "刻", + "括", + "激", + "孔", + "搞", + "甚", + "室", + "待", + "核", + "校", + "散", + "侵", + "吧", + "甲", + "游", + "久", + "菜", + "味", + "旧", + "模", + "湖", + "货", + "损", + "预", + "阻", + "毫", + "普", + "稳", + "乙", + "妈", + "植", + "息", + "扩", + "银", + "语", + "挥", + "酒", + "守", + "拿", + "序", + "纸", + "医", + "缺", + "雨", + "吗", + "针", + "刘", + "啊", + "急", + "唱", + "误", + "训", + "愿", + "审", + "附", + "获", + "茶", + "鲜", + "粮", + "斤", + "孩", + "脱", + "硫", + "肥", + "善", + "龙", + "演", + "父", + "渐", + "血", + "欢", + "械", + "掌", + "歌", + "沙", + "刚", + "攻", + "谓", + "盾", + "讨", + "晚", + "粒", + "乱", + "燃", + "矛", + "乎", + "杀", + "药", + "宁", + "鲁", + "贵", + "钟", + "煤", + "读", + "班", + "伯", + "香", + "介", + "迫", + "句", + "丰", + "培", + "握", + "兰", + "担", + "弦", + "蛋", + "沉", + "假", + "穿", + "执", + "答", + "乐", + "谁", + "顺", + "烟", + "缩", + "征", + "脸", + "喜", + "松", + "脚", + "困", + "异", + "免", + "背", + "星", + "福", + "买", + "染", + "井", + "概", + "慢", + "怕", + "磁", + "倍", + "祖", + "皇", + "促", + "静", + "补", + "评", + "翻", + "肉", + "践", + "尼", + "衣", + "宽", + "扬", + "棉", + "希", + "伤", + "操", + "垂", + "秋", + "宜", + "氢", + "套", + "督", + "振", + "架", + "亮", + "末", + "宪", + "庆", + "编", + "牛", + "触", + "映", + "雷", + "销", + "诗", + "座", + "居", + "抓", + "裂", + "胞", + "呼", + "娘", + "景", + "威", + "绿", + "晶", + "厚", + "盟", + "衡", + "鸡", + "孙", + "延", + "危", + "胶", + "屋", + "乡", + "临", + "陆", + "顾", + "掉", + "呀", + "灯", + "岁", + "措", + "束", + "耐", + "剧", + "玉", + "赵", + "跳", + "哥", + "季", + "课", + "凯", + "胡", + "额", + "款", + "绍", + "卷", + "齐", + "伟", + "蒸", + "殖", + "永", + "宗", + "苗", + "川", + "炉", + "岩", + "弱", + "零", + "杨", + "奏", + "沿", + "露", + "杆", + "探", + "滑", + "镇", + "饭", + "浓", + "航", + "怀", + "赶", + "库", + "夺", + "伊", + "灵", + "税", + "途", + "灭", + "赛", + "归", + "召", + "鼓", + "播", + "盘", + "裁", + "险", + "康", + "唯", + "录", + "菌", + "纯", + "借", + "糖", + "盖", + "横", + "符", + "私", + "努", + "堂", + "域", + "枪", + "润", + "幅", + "哈", + "竟", + "熟", + "虫", + "泽", + "脑", + "壤", + "碳", + "欧", + "遍", + "侧", + "寨", + "敢", + "彻", + "虑", + "斜", + "薄", + "庭", + "纳", + "弹", + "饲", + "伸", + "折", + "麦", + "湿", + "暗", + "荷", + "瓦", + "塞", + "床", + "筑", + "恶", + "户", + "访", + "塔", + "奇", + "透", + "梁", + "刀", + "旋", + "迹", + "卡", + "氯", + "遇", + "份", + "毒", + "泥", + "退", + "洗", + "摆", + "灰", + "彩", + "卖", + "耗", + "夏", + "择", + "忙", + "铜", + "献", + "硬", + "予", + "繁", + "圈", + "雪", + "函", + "亦", + "抽", + "篇", + "阵", + "阴", + "丁", + "尺", + "追", + "堆", + "雄", + "迎", + "泛", + "爸", + "楼", + "避", + "谋", + "吨", + "野", + "猪", + "旗", + "累", + "偏", + "典", + "馆", + "索", + "秦", + "脂", + "潮", + "爷", + "豆", + "忽", + "托", + "惊", + "塑", + "遗", + "愈", + "朱", + "替", + "纤", + "粗", + "倾", + "尚", + "痛", + "楚", + "谢", + "奋", + "购", + "磨", + "君", + "池", + "旁", + "碎", + "骨", + "监", + "捕", + "弟", + "暴", + "割", + "贯", + "殊", + "释", + "词", + "亡", + "壁", + "顿", + "宝", + "午", + "尘", + "闻", + "揭", + "炮", + "残", + "冬", + "桥", + "妇", + "警", + "综", + "招", + "吴", + "付", + "浮", + "遭", + "徐", + "您", + "摇", + "谷", + "赞", + "箱", + "隔", + "订", + "男", + "吹", + "园", + "纷", + "唐", + "败", + "宋", + "玻", + "巨", + "耕", + "坦", + "荣", + "闭", + "湾", + "键", + "凡", + "驻", + "锅", + "救", + "恩", + "剥", + "凝", + "碱", + "齿", + "截", + "炼", + "麻", + "纺", + "禁", + "废", + "盛", + "版", + "缓", + "净", + "睛", + "昌", + "婚", + "涉", + "筒", + "嘴", + "插", + "岸", + "朗", + "庄", + "街", + "藏", + "姑", + "贸", + "腐", + "奴", + "啦", + "惯", + "乘", + "伙", + "恢", + "匀", + "纱", + "扎", + "辩", + "耳", + "彪", + "臣", + "亿", + "璃", + "抵", + "脉", + "秀", + "萨", + "俄", + "网", + "舞", + "店", + "喷", + "纵", + "寸", + "汗", + "挂", + "洪", + "贺", + "闪", + "柬", + "爆", + "烯", + "津", + "稻", + "墙", + "软", + "勇", + "像", + "滚", + "厘", + "蒙", + "芳", + "肯", + "坡", + "柱", + "荡", + "腿", + "仪", + "旅", + "尾", + "轧", + "冰", + "贡", + "登", + "黎", + "削", + "钻", + "勒", + "逃", + "障", + "氨", + "郭", + "峰", + "币", + "港", + "伏", + "轨", + "亩", + "毕", + "擦", + "莫", + "刺", + "浪", + "秘", + "援", + "株", + "健", + "售", + "股", + "岛", + "甘", + "泡", + "睡", + "童", + "铸", + "汤", + "阀", + "休", + "汇", + "舍", + "牧", + "绕", + "炸", + "哲", + "磷", + "绩", + "朋", + "淡", + "尖", + "启", + "陷", + "柴", + "呈", + "徒", + "颜", + "泪", + "稍", + "忘", + "泵", + "蓝", + "拖", + "洞", + "授", + "镜", + "辛", + "壮", + "锋", + "贫", + "虚", + "弯", + "摩", + "泰", + "幼", + "廷", + "尊", + "窗", + "纲", + "弄", + "隶", + "疑", + "氏", + "宫", + "姐", + "震", + "瑞", + "怪", + "尤", + "琴", + "循", + "描", + "膜", + "违", + "夹", + "腰", + "缘", + "珠", + "穷", + "森", + "枝", + "竹", + "沟", + "催", + "绳", + "忆", + "邦", + "剩", + "幸", + "浆", + "栏", + "拥", + "牙", + "贮", + "礼", + "滤", + "钠", + "纹", + "罢", + "拍", + "咱", + "喊", + "袖", + "埃", + "勤", + "罚", + "焦", + "潜", + "伍", + "墨", + "欲", + "缝", + "姓", + "刊", + "饱", + "仿", + "奖", + "铝", + "鬼", + "丽", + "跨", + "默", + "挖", + "链", + "扫", + "喝", + "袋", + "炭", + "污", + "幕", + "诸", + "弧", + "励", + "梅", + "奶", + "洁", + "灾", + "舟", + "鉴", + "苯", + "讼", + "抱", + "毁", + "懂", + "寒", + "智", + "埔", + "寄", + "届", + "跃", + "渡", + "挑", + "丹", + "艰", + "贝", + "碰", + "拔", + "爹", + "戴", + "码", + "梦", + "芽", + "熔", + "赤", + "渔", + "哭", + "敬", + "颗", + "奔", + "铅", + "仲", + "虎", + "稀", + "妹", + "乏", + "珍", + "申", + "桌", + "遵", + "允", + "隆", + "螺", + "仓", + "魏", + "锐", + "晓", + "氮", + "兼", + "隐", + "碍", + "赫", + "拨", + "忠", + "肃", + "缸", + "牵", + "抢", + "博", + "巧", + "壳", + "兄", + "杜", + "讯", + "诚", + "碧", + "祥", + "柯", + "页", + "巡", + "矩", + "悲", + "灌", + "龄", + "伦", + "票", + "寻", + "桂", + "铺", + "圣", + "恐", + "恰", + "郑", + "趣", + "抬", + "荒", + "腾", + "贴", + "柔", + "滴", + "猛", + "阔", + "辆", + "妻", + "填", + "撤", + "储", + "签", + "闹", + "扰", + "紫", + "砂", + "递", + "戏", + "吊", + "陶", + "伐", + "喂", + "疗", + "瓶", + "婆", + "抚", + "臂", + "摸", + "忍", + "虾", + "蜡", + "邻", + "胸", + "巩", + "挤", + "偶", + "弃", + "槽", + "劲", + "乳", + "邓", + "吉", + "仁", + "烂", + "砖", + "租", + "乌", + "舰", + "伴", + "瓜", + "浅", + "丙", + "暂", + "燥", + "橡", + "柳", + "迷", + "暖", + "牌", + "秧", + "胆", + "详", + "簧", + "踏", + "瓷", + "谱", + "呆", + "宾", + "糊", + "洛", + "辉", + "愤", + "竞", + "隙", + "怒", + "粘", + "乃", + "绪", + "肩", + "籍", + "敏", + "涂", + "熙", + "皆", + "侦", + "悬", + "掘", + "享", + "纠", + "醒", + "狂", + "锁", + "淀", + "恨", + "牲", + "霸", + "爬", + "赏", + "逆", + "玩", + "陵", + "祝", + "秒", + "浙", + "貌", + "役", + "彼", + "悉", + "鸭", + "趋", + "凤", + "晨", + "畜", + "辈", + "秩", + "卵", + "署", + "梯", + "炎", + "滩", + "棋", + "驱", + "筛", + "峡", + "冒", + "啥", + "寿", + "译", + "浸", + "泉", + "帽", + "迟", + "硅", + "疆", + "贷", + "漏", + "稿", + "冠", + "嫩", + "胁", + "芯", + "牢", + "叛", + "蚀", + "奥", + "鸣", + "岭", + "羊", + "凭", + "串", + "塘", + "绘", + "酵", + "融", + "盆", + "锡", + "庙", + "筹", + "冻", + "辅", + "摄", + "袭", + "筋", + "拒", + "僚", + "旱", + "钾", + "鸟", + "漆", + "沈", + "眉", + "疏", + "添", + "棒", + "穗", + "硝", + "韩", + "逼", + "扭", + "侨", + "凉", + "挺", + "碗", + "栽", + "炒", + "杯", + "患", + "馏", + "劝", + "豪", + "辽", + "勃", + "鸿", + "旦", + "吏", + "拜", + "狗", + "埋", + "辊", + "掩", + "饮", + "搬", + "骂", + "辞", + "勾", + "扣", + "估", + "蒋", + "绒", + "雾", + "丈", + "朵", + "姆", + "拟", + "宇", + "辑", + "陕", + "雕", + "偿", + "蓄", + "崇", + "剪", + "倡", + "厅", + "咬", + "驶", + "薯", + "刷", + "斥", + "番", + "赋", + "奉", + "佛", + "浇", + "漫", + "曼", + "扇", + "钙", + "桃", + "扶", + "仔", + "返", + "俗", + "亏", + "腔", + "鞋", + "棱", + "覆", + "框", + "悄", + "叔", + "撞", + "骗", + "勘", + "旺", + "沸", + "孤", + "吐", + "孟", + "渠", + "屈", + "疾", + "妙", + "惜", + "仰", + "狠", + "胀", + "谐", + "抛", + "霉", + "桑", + "岗", + "嘛", + "衰", + "盗", + "渗", + "脏", + "赖", + "涌", + "甜", + "曹", + "阅", + "肌", + "哩", + "厉", + "烃", + "纬", + "毅", + "昨", + "伪", + "症", + "煮", + "叹", + "钉", + "搭", + "茎", + "笼", + "酷", + "偷", + "弓", + "锥", + "恒", + "杰", + "坑", + "鼻", + "翼", + "纶", + "叙", + "狱", + "逮", + "罐", + "络", + "棚", + "抑", + "膨", + "蔬", + "寺", + "骤", + "穆", + "冶", + "枯", + "册", + "尸", + "凸", + "绅", + "坯", + "牺", + "焰", + "轰", + "欣", + "晋", + "瘦", + "御", + "锭", + "锦", + "丧", + "旬", + "锻", + "垄", + "搜", + "扑", + "邀", + "亭", + "酯", + "迈", + "舒", + "脆", + "酶", + "闲", + "忧", + "酚", + "顽", + "羽", + "涨", + "卸", + "仗", + "陪", + "辟", + "惩", + "杭", + "姚", + "肚", + "捉", + "飘", + "漂", + "昆", + "欺", + "吾", + "郎", + "烷", + "汁", + "呵", + "饰", + "萧", + "雅", + "邮", + "迁", + "燕", + "撒", + "姻", + "赴", + "宴", + "烦", + "债", + "帐", + "斑", + "铃", + "旨", + "醇", + "董", + "饼", + "雏", + "姿", + "拌", + "傅", + "腹", + "妥", + "揉", + "贤", + "拆", + "歪", + "葡", + "胺", + "丢", + "浩", + "徽", + "昂", + "垫", + "挡", + "览", + "贪", + "慰", + "缴", + "汪", + "慌", + "冯", + "诺", + "姜", + "谊", + "凶", + "劣", + "诬", + "耀", + "昏", + "躺", + "盈", + "骑", + "乔", + "溪", + "丛", + "卢", + "抹", + "闷", + "咨", + "刮", + "驾", + "缆", + "悟", + "摘", + "铒", + "掷", + "颇", + "幻", + "柄", + "惠", + "惨", + "佳", + "仇", + "腊", + "窝", + "涤", + "剑", + "瞧", + "堡", + "泼", + "葱", + "罩", + "霍", + "捞", + "胎", + "苍", + "滨", + "俩", + "捅", + "湘", + "砍", + "霞", + "邵", + "萄", + "疯", + "淮", + "遂", + "熊", + "粪", + "烘", + "宿", + "档", + "戈", + "驳", + "嫂", + "裕", + "徙", + "箭", + "捐", + "肠", + "撑", + "晒", + "辨", + "殿", + "莲", + "摊", + "搅", + "酱", + "屏", + "疫", + "哀", + "蔡", + "堵", + "沫", + "皱", + "畅", + "叠", + "阁", + "莱", + "敲", + "辖", + "钩", + "痕", + "坝", + "巷", + "饿", + "祸", + "丘", + "玄", + "溜", + "曰", + "逻", + "彭", + "尝", + "卿", + "妨", + "艇", + "吞", + "韦", + "怨", + "矮", + "歇" +] + +},{}],52:[function(require,module,exports){ +module.exports=[ + "abandon", + "ability", + "able", + "about", + "above", + "absent", + "absorb", + "abstract", + "absurd", + "abuse", + "access", + "accident", + "account", + "accuse", + "achieve", + "acid", + "acoustic", + "acquire", + "across", + "act", + "action", + "actor", + "actress", + "actual", + "adapt", + "add", + "addict", + "address", + "adjust", + "admit", + "adult", + "advance", + "advice", + "aerobic", + "affair", + "afford", + "afraid", + "again", + "age", + "agent", + "agree", + "ahead", + "aim", + "air", + "airport", + "aisle", + "alarm", + "album", + "alcohol", + "alert", + "alien", + "all", + "alley", + "allow", + "almost", + "alone", + "alpha", + "already", + "also", + "alter", + "always", + "amateur", + "amazing", + "among", + "amount", + "amused", + "analyst", + "anchor", + "ancient", + "anger", + "angle", + "angry", + "animal", + "ankle", + "announce", + "annual", + "another", + "answer", + "antenna", + "antique", + "anxiety", + "any", + "apart", + "apology", + "appear", + "apple", + "approve", + "april", + "arch", + "arctic", + "area", + "arena", + "argue", + "arm", + "armed", + "armor", + "army", + "around", + "arrange", + "arrest", + "arrive", + "arrow", + "art", + "artefact", + "artist", + "artwork", + "ask", + "aspect", + "assault", + "asset", + "assist", + "assume", + "asthma", + "athlete", + "atom", + "attack", + "attend", + "attitude", + "attract", + "auction", + "audit", + "august", + "aunt", + "author", + "auto", + "autumn", + "average", + "avocado", + "avoid", + "awake", + "aware", + "away", + "awesome", + "awful", + "awkward", + "axis", + "baby", + "bachelor", + "bacon", + "badge", + "bag", + "balance", + "balcony", + "ball", + "bamboo", + "banana", + "banner", + "bar", + "barely", + "bargain", + "barrel", + "base", + "basic", + "basket", + "battle", + "beach", + "bean", + "beauty", + "because", + "become", + "beef", + "before", + "begin", + "behave", + "behind", + "believe", + "below", + "belt", + "bench", + "benefit", + "best", + "betray", + "better", + "between", + "beyond", + "bicycle", + "bid", + "bike", + "bind", + "biology", + "bird", + "birth", + "bitter", + "black", + "blade", + "blame", + "blanket", + "blast", + "bleak", + "bless", + "blind", + "blood", + "blossom", + "blouse", + "blue", + "blur", + "blush", + "board", + "boat", + "body", + "boil", + "bomb", + "bone", + "bonus", + "book", + "boost", + "border", + "boring", + "borrow", + "boss", + "bottom", + "bounce", + "box", + "boy", + "bracket", + "brain", + "brand", + "brass", + "brave", + "bread", + "breeze", + "brick", + "bridge", + "brief", + "bright", + "bring", + "brisk", + "broccoli", + "broken", + "bronze", + "broom", + "brother", + "brown", + "brush", + "bubble", + "buddy", + "budget", + "buffalo", + "build", + "bulb", + "bulk", + "bullet", + "bundle", + "bunker", + "burden", + "burger", + "burst", + "bus", + "business", + "busy", + "butter", + "buyer", + "buzz", + "cabbage", + "cabin", + "cable", + "cactus", + "cage", + "cake", + "call", + "calm", + "camera", + "camp", + "can", + "canal", + "cancel", + "candy", + "cannon", + "canoe", + "canvas", + "canyon", + "capable", + "capital", + "captain", + "car", + "carbon", + "card", + "cargo", + "carpet", + "carry", + "cart", + "case", + "cash", + "casino", + "castle", + "casual", + "cat", + "catalog", + "catch", + "category", + "cattle", + "caught", + "cause", + "caution", + "cave", + "ceiling", + "celery", + "cement", + "census", + "century", + "cereal", + "certain", + "chair", + "chalk", + "champion", + "change", + "chaos", + "chapter", + "charge", + "chase", + "chat", + "cheap", + "check", + "cheese", + "chef", + "cherry", + "chest", + "chicken", + "chief", + "child", + "chimney", + "choice", + "choose", + "chronic", + "chuckle", + "chunk", + "churn", + "cigar", + "cinnamon", + "circle", + "citizen", + "city", + "civil", + "claim", + "clap", + "clarify", + "claw", + "clay", + "clean", + "clerk", + "clever", + "click", + "client", + "cliff", + "climb", + "clinic", + "clip", + "clock", + "clog", + "close", + "cloth", + "cloud", + "clown", + "club", + "clump", + "cluster", + "clutch", + "coach", + "coast", + "coconut", + "code", + "coffee", + "coil", + "coin", + "collect", + "color", + "column", + "combine", + "come", + "comfort", + "comic", + "common", + "company", + "concert", + "conduct", + "confirm", + "congress", + "connect", + "consider", + "control", + "convince", + "cook", + "cool", + "copper", + "copy", + "coral", + "core", + "corn", + "correct", + "cost", + "cotton", + "couch", + "country", + "couple", + "course", + "cousin", + "cover", + "coyote", + "crack", + "cradle", + "craft", + "cram", + "crane", + "crash", + "crater", + "crawl", + "crazy", + "cream", + "credit", + "creek", + "crew", + "cricket", + "crime", + "crisp", + "critic", + "crop", + "cross", + "crouch", + "crowd", + "crucial", + "cruel", + "cruise", + "crumble", + "crunch", + "crush", + "cry", + "crystal", + "cube", + "culture", + "cup", + "cupboard", + "curious", + "current", + "curtain", + "curve", + "cushion", + "custom", + "cute", + "cycle", + "dad", + "damage", + "damp", + "dance", + "danger", + "daring", + "dash", + "daughter", + "dawn", + "day", + "deal", + "debate", + "debris", + "decade", + "december", + "decide", + "decline", + "decorate", + "decrease", + "deer", + "defense", + "define", + "defy", + "degree", + "delay", + "deliver", + "demand", + "demise", + "denial", + "dentist", + "deny", + "depart", + "depend", + "deposit", + "depth", + "deputy", + "derive", + "describe", + "desert", + "design", + "desk", + "despair", + "destroy", + "detail", + "detect", + "develop", + "device", + "devote", + "diagram", + "dial", + "diamond", + "diary", + "dice", + "diesel", + "diet", + "differ", + "digital", + "dignity", + "dilemma", + "dinner", + "dinosaur", + "direct", + "dirt", + "disagree", + "discover", + "disease", + "dish", + "dismiss", + "disorder", + "display", + "distance", + "divert", + "divide", + "divorce", + "dizzy", + "doctor", + "document", + "dog", + "doll", + "dolphin", + "domain", + "donate", + "donkey", + "donor", + "door", + "dose", + "double", + "dove", + "draft", + "dragon", + "drama", + "drastic", + "draw", + "dream", + "dress", + "drift", + "drill", + "drink", + "drip", + "drive", + "drop", + "drum", + "dry", + "duck", + "dumb", + "dune", + "during", + "dust", + "dutch", + "duty", + "dwarf", + "dynamic", + "eager", + "eagle", + "early", + "earn", + "earth", + "easily", + "east", + "easy", + "echo", + "ecology", + "economy", + "edge", + "edit", + "educate", + "effort", + "egg", + "eight", + "either", + "elbow", + "elder", + "electric", + "elegant", + "element", + "elephant", + "elevator", + "elite", + "else", + "embark", + "embody", + "embrace", + "emerge", + "emotion", + "employ", + "empower", + "empty", + "enable", + "enact", + "end", + "endless", + "endorse", + "enemy", + "energy", + "enforce", + "engage", + "engine", + "enhance", + "enjoy", + "enlist", + "enough", + "enrich", + "enroll", + "ensure", + "enter", + "entire", + "entry", + "envelope", + "episode", + "equal", + "equip", + "era", + "erase", + "erode", + "erosion", + "error", + "erupt", + "escape", + "essay", + "essence", + "estate", + "eternal", + "ethics", + "evidence", + "evil", + "evoke", + "evolve", + "exact", + "example", + "excess", + "exchange", + "excite", + "exclude", + "excuse", + "execute", + "exercise", + "exhaust", + "exhibit", + "exile", + "exist", + "exit", + "exotic", + "expand", + "expect", + "expire", + "explain", + "expose", + "express", + "extend", + "extra", + "eye", + "eyebrow", + "fabric", + "face", + "faculty", + "fade", + "faint", + "faith", + "fall", + "false", + "fame", + "family", + "famous", + "fan", + "fancy", + "fantasy", + "farm", + "fashion", + "fat", + "fatal", + "father", + "fatigue", + "fault", + "favorite", + "feature", + "february", + "federal", + "fee", + "feed", + "feel", + "female", + "fence", + "festival", + "fetch", + "fever", + "few", + "fiber", + "fiction", + "field", + "figure", + "file", + "film", + "filter", + "final", + "find", + "fine", + "finger", + "finish", + "fire", + "firm", + "first", + "fiscal", + "fish", + "fit", + "fitness", + "fix", + "flag", + "flame", + "flash", + "flat", + "flavor", + "flee", + "flight", + "flip", + "float", + "flock", + "floor", + "flower", + "fluid", + "flush", + "fly", + "foam", + "focus", + "fog", + "foil", + "fold", + "follow", + "food", + "foot", + "force", + "forest", + "forget", + "fork", + "fortune", + "forum", + "forward", + "fossil", + "foster", + "found", + "fox", + "fragile", + "frame", + "frequent", + "fresh", + "friend", + "fringe", + "frog", + "front", + "frost", + "frown", + "frozen", + "fruit", + "fuel", + "fun", + "funny", + "furnace", + "fury", + "future", + "gadget", + "gain", + "galaxy", + "gallery", + "game", + "gap", + "garage", + "garbage", + "garden", + "garlic", + "garment", + "gas", + "gasp", + "gate", + "gather", + "gauge", + "gaze", + "general", + "genius", + "genre", + "gentle", + "genuine", + "gesture", + "ghost", + "giant", + "gift", + "giggle", + "ginger", + "giraffe", + "girl", + "give", + "glad", + "glance", + "glare", + "glass", + "glide", + "glimpse", + "globe", + "gloom", + "glory", + "glove", + "glow", + "glue", + "goat", + "goddess", + "gold", + "good", + "goose", + "gorilla", + "gospel", + "gossip", + "govern", + "gown", + "grab", + "grace", + "grain", + "grant", + "grape", + "grass", + "gravity", + "great", + "green", + "grid", + "grief", + "grit", + "grocery", + "group", + "grow", + "grunt", + "guard", + "guess", + "guide", + "guilt", + "guitar", + "gun", + "gym", + "habit", + "hair", + "half", + "hammer", + "hamster", + "hand", + "happy", + "harbor", + "hard", + "harsh", + "harvest", + "hat", + "have", + "hawk", + "hazard", + "head", + "health", + "heart", + "heavy", + "hedgehog", + "height", + "hello", + "helmet", + "help", + "hen", + "hero", + "hidden", + "high", + "hill", + "hint", + "hip", + "hire", + "history", + "hobby", + "hockey", + "hold", + "hole", + "holiday", + "hollow", + "home", + "honey", + "hood", + "hope", + "horn", + "horror", + "horse", + "hospital", + "host", + "hotel", + "hour", + "hover", + "hub", + "huge", + "human", + "humble", + "humor", + "hundred", + "hungry", + "hunt", + "hurdle", + "hurry", + "hurt", + "husband", + "hybrid", + "ice", + "icon", + "idea", + "identify", + "idle", + "ignore", + "ill", + "illegal", + "illness", + "image", + "imitate", + "immense", + "immune", + "impact", + "impose", + "improve", + "impulse", + "inch", + "include", + "income", + "increase", + "index", + "indicate", + "indoor", + "industry", + "infant", + "inflict", + "inform", + "inhale", + "inherit", + "initial", + "inject", + "injury", + "inmate", + "inner", + "innocent", + "input", + "inquiry", + "insane", + "insect", + "inside", + "inspire", + "install", + "intact", + "interest", + "into", + "invest", + "invite", + "involve", + "iron", + "island", + "isolate", + "issue", + "item", + "ivory", + "jacket", + "jaguar", + "jar", + "jazz", + "jealous", + "jeans", + "jelly", + "jewel", + "job", + "join", + "joke", + "journey", + "joy", + "judge", + "juice", + "jump", + "jungle", + "junior", + "junk", + "just", + "kangaroo", + "keen", + "keep", + "ketchup", + "key", + "kick", + "kid", + "kidney", + "kind", + "kingdom", + "kiss", + "kit", + "kitchen", + "kite", + "kitten", + "kiwi", + "knee", + "knife", + "knock", + "know", + "lab", + "label", + "labor", + "ladder", + "lady", + "lake", + "lamp", + "language", + "laptop", + "large", + "later", + "latin", + "laugh", + "laundry", + "lava", + "law", + "lawn", + "lawsuit", + "layer", + "lazy", + "leader", + "leaf", + "learn", + "leave", + "lecture", + "left", + "leg", + "legal", + "legend", + "leisure", + "lemon", + "lend", + "length", + "lens", + "leopard", + "lesson", + "letter", + "level", + "liar", + "liberty", + "library", + "license", + "life", + "lift", + "light", + "like", + "limb", + "limit", + "link", + "lion", + "liquid", + "list", + "little", + "live", + "lizard", + "load", + "loan", + "lobster", + "local", + "lock", + "logic", + "lonely", + "long", + "loop", + "lottery", + "loud", + "lounge", + "love", + "loyal", + "lucky", + "luggage", + "lumber", + "lunar", + "lunch", + "luxury", + "lyrics", + "machine", + "mad", + "magic", + "magnet", + "maid", + "mail", + "main", + "major", + "make", + "mammal", + "man", + "manage", + "mandate", + "mango", + "mansion", + "manual", + "maple", + "marble", + "march", + "margin", + "marine", + "market", + "marriage", + "mask", + "mass", + "master", + "match", + "material", + "math", + "matrix", + "matter", + "maximum", + "maze", + "meadow", + "mean", + "measure", + "meat", + "mechanic", + "medal", + "media", + "melody", + "melt", + "member", + "memory", + "mention", + "menu", + "mercy", + "merge", + "merit", + "merry", + "mesh", + "message", + "metal", + "method", + "middle", + "midnight", + "milk", + "million", + "mimic", + "mind", + "minimum", + "minor", + "minute", + "miracle", + "mirror", + "misery", + "miss", + "mistake", + "mix", + "mixed", + "mixture", + "mobile", + "model", + "modify", + "mom", + "moment", + "monitor", + "monkey", + "monster", + "month", + "moon", + "moral", + "more", + "morning", + "mosquito", + "mother", + "motion", + "motor", + "mountain", + "mouse", + "move", + "movie", + "much", + "muffin", + "mule", + "multiply", + "muscle", + "museum", + "mushroom", + "music", + "must", + "mutual", + "myself", + "mystery", + "myth", + "naive", + "name", + "napkin", + "narrow", + "nasty", + "nation", + "nature", + "near", + "neck", + "need", + "negative", + "neglect", + "neither", + "nephew", + "nerve", + "nest", + "net", + "network", + "neutral", + "never", + "news", + "next", + "nice", + "night", + "noble", + "noise", + "nominee", + "noodle", + "normal", + "north", + "nose", + "notable", + "note", + "nothing", + "notice", + "novel", + "now", + "nuclear", + "number", + "nurse", + "nut", + "oak", + "obey", + "object", + "oblige", + "obscure", + "observe", + "obtain", + "obvious", + "occur", + "ocean", + "october", + "odor", + "off", + "offer", + "office", + "often", + "oil", + "okay", + "old", + "olive", + "olympic", + "omit", + "once", + "one", + "onion", + "online", + "only", + "open", + "opera", + "opinion", + "oppose", + "option", + "orange", + "orbit", + "orchard", + "order", + "ordinary", + "organ", + "orient", + "original", + "orphan", + "ostrich", + "other", + "outdoor", + "outer", + "output", + "outside", + "oval", + "oven", + "over", + "own", + "owner", + "oxygen", + "oyster", + "ozone", + "pact", + "paddle", + "page", + "pair", + "palace", + "palm", + "panda", + "panel", + "panic", + "panther", + "paper", + "parade", + "parent", + "park", + "parrot", + "party", + "pass", + "patch", + "path", + "patient", + "patrol", + "pattern", + "pause", + "pave", + "payment", + "peace", + "peanut", + "pear", + "peasant", + "pelican", + "pen", + "penalty", + "pencil", + "people", + "pepper", + "perfect", + "permit", + "person", + "pet", + "phone", + "photo", + "phrase", + "physical", + "piano", + "picnic", + "picture", + "piece", + "pig", + "pigeon", + "pill", + "pilot", + "pink", + "pioneer", + "pipe", + "pistol", + "pitch", + "pizza", + "place", + "planet", + "plastic", + "plate", + "play", + "please", + "pledge", + "pluck", + "plug", + "plunge", + "poem", + "poet", + "point", + "polar", + "pole", + "police", + "pond", + "pony", + "pool", + "popular", + "portion", + "position", + "possible", + "post", + "potato", + "pottery", + "poverty", + "powder", + "power", + "practice", + "praise", + "predict", + "prefer", + "prepare", + "present", + "pretty", + "prevent", + "price", + "pride", + "primary", + "print", + "priority", + "prison", + "private", + "prize", + "problem", + "process", + "produce", + "profit", + "program", + "project", + "promote", + "proof", + "property", + "prosper", + "protect", + "proud", + "provide", + "public", + "pudding", + "pull", + "pulp", + "pulse", + "pumpkin", + "punch", + "pupil", + "puppy", + "purchase", + "purity", + "purpose", + "purse", + "push", + "put", + "puzzle", + "pyramid", + "quality", + "quantum", + "quarter", + "question", + "quick", + "quit", + "quiz", + "quote", + "rabbit", + "raccoon", + "race", + "rack", + "radar", + "radio", + "rail", + "rain", + "raise", + "rally", + "ramp", + "ranch", + "random", + "range", + "rapid", + "rare", + "rate", + "rather", + "raven", + "raw", + "razor", + "ready", + "real", + "reason", + "rebel", + "rebuild", + "recall", + "receive", + "recipe", + "record", + "recycle", + "reduce", + "reflect", + "reform", + "refuse", + "region", + "regret", + "regular", + "reject", + "relax", + "release", + "relief", + "rely", + "remain", + "remember", + "remind", + "remove", + "render", + "renew", + "rent", + "reopen", + "repair", + "repeat", + "replace", + "report", + "require", + "rescue", + "resemble", + "resist", + "resource", + "response", + "result", + "retire", + "retreat", + "return", + "reunion", + "reveal", + "review", + "reward", + "rhythm", + "rib", + "ribbon", + "rice", + "rich", + "ride", + "ridge", + "rifle", + "right", + "rigid", + "ring", + "riot", + "ripple", + "risk", + "ritual", + "rival", + "river", + "road", + "roast", + "robot", + "robust", + "rocket", + "romance", + "roof", + "rookie", + "room", + "rose", + "rotate", + "rough", + "round", + "route", + "royal", + "rubber", + "rude", + "rug", + "rule", + "run", + "runway", + "rural", + "sad", + "saddle", + "sadness", + "safe", + "sail", + "salad", + "salmon", + "salon", + "salt", + "salute", + "same", + "sample", + "sand", + "satisfy", + "satoshi", + "sauce", + "sausage", + "save", + "say", + "scale", + "scan", + "scare", + "scatter", + "scene", + "scheme", + "school", + "science", + "scissors", + "scorpion", + "scout", + "scrap", + "screen", + "script", + "scrub", + "sea", + "search", + "season", + "seat", + "second", + "secret", + "section", + "security", + "seed", + "seek", + "segment", + "select", + "sell", + "seminar", + "senior", + "sense", + "sentence", + "series", + "service", + "session", + "settle", + "setup", + "seven", + "shadow", + "shaft", + "shallow", + "share", + "shed", + "shell", + "sheriff", + "shield", + "shift", + "shine", + "ship", + "shiver", + "shock", + "shoe", + "shoot", + "shop", + "short", + "shoulder", + "shove", + "shrimp", + "shrug", + "shuffle", + "shy", + "sibling", + "sick", + "side", + "siege", + "sight", + "sign", + "silent", + "silk", + "silly", + "silver", + "similar", + "simple", + "since", + "sing", + "siren", + "sister", + "situate", + "six", + "size", + "skate", + "sketch", + "ski", + "skill", + "skin", + "skirt", + "skull", + "slab", + "slam", + "sleep", + "slender", + "slice", + "slide", + "slight", + "slim", + "slogan", + "slot", + "slow", + "slush", + "small", + "smart", + "smile", + "smoke", + "smooth", + "snack", + "snake", + "snap", + "sniff", + "snow", + "soap", + "soccer", + "social", + "sock", + "soda", + "soft", + "solar", + "soldier", + "solid", + "solution", + "solve", + "someone", + "song", + "soon", + "sorry", + "sort", + "soul", + "sound", + "soup", + "source", + "south", + "space", + "spare", + "spatial", + "spawn", + "speak", + "special", + "speed", + "spell", + "spend", + "sphere", + "spice", + "spider", + "spike", + "spin", + "spirit", + "split", + "spoil", + "sponsor", + "spoon", + "sport", + "spot", + "spray", + "spread", + "spring", + "spy", + "square", + "squeeze", + "squirrel", + "stable", + "stadium", + "staff", + "stage", + "stairs", + "stamp", + "stand", + "start", + "state", + "stay", + "steak", + "steel", + "stem", + "step", + "stereo", + "stick", + "still", + "sting", + "stock", + "stomach", + "stone", + "stool", + "story", + "stove", + "strategy", + "street", + "strike", + "strong", + "struggle", + "student", + "stuff", + "stumble", + "style", + "subject", + "submit", + "subway", + "success", + "such", + "sudden", + "suffer", + "sugar", + "suggest", + "suit", + "summer", + "sun", + "sunny", + "sunset", + "super", + "supply", + "supreme", + "sure", + "surface", + "surge", + "surprise", + "surround", + "survey", + "suspect", + "sustain", + "swallow", + "swamp", + "swap", + "swarm", + "swear", + "sweet", + "swift", + "swim", + "swing", + "switch", + "sword", + "symbol", + "symptom", + "syrup", + "system", + "table", + "tackle", + "tag", + "tail", + "talent", + "talk", + "tank", + "tape", + "target", + "task", + "taste", + "tattoo", + "taxi", + "teach", + "team", + "tell", + "ten", + "tenant", + "tennis", + "tent", + "term", + "test", + "text", + "thank", + "that", + "theme", + "then", + "theory", + "there", + "they", + "thing", + "this", + "thought", + "three", + "thrive", + "throw", + "thumb", + "thunder", + "ticket", + "tide", + "tiger", + "tilt", + "timber", + "time", + "tiny", + "tip", + "tired", + "tissue", + "title", + "toast", + "tobacco", + "today", + "toddler", + "toe", + "together", + "toilet", + "token", + "tomato", + "tomorrow", + "tone", + "tongue", + "tonight", + "tool", + "tooth", + "top", + "topic", + "topple", + "torch", + "tornado", + "tortoise", + "toss", + "total", + "tourist", + "toward", + "tower", + "town", + "toy", + "track", + "trade", + "traffic", + "tragic", + "train", + "transfer", + "trap", + "trash", + "travel", + "tray", + "treat", + "tree", + "trend", + "trial", + "tribe", + "trick", + "trigger", + "trim", + "trip", + "trophy", + "trouble", + "truck", + "true", + "truly", + "trumpet", + "trust", + "truth", + "try", + "tube", + "tuition", + "tumble", + "tuna", + "tunnel", + "turkey", + "turn", + "turtle", + "twelve", + "twenty", + "twice", + "twin", + "twist", + "two", + "type", + "typical", + "ugly", + "umbrella", + "unable", + "unaware", + "uncle", + "uncover", + "under", + "undo", + "unfair", + "unfold", + "unhappy", + "uniform", + "unique", + "unit", + "universe", + "unknown", + "unlock", + "until", + "unusual", + "unveil", + "update", + "upgrade", + "uphold", + "upon", + "upper", + "upset", + "urban", + "urge", + "usage", + "use", + "used", + "useful", + "useless", + "usual", + "utility", + "vacant", + "vacuum", + "vague", + "valid", + "valley", + "valve", + "van", + "vanish", + "vapor", + "various", + "vast", + "vault", + "vehicle", + "velvet", + "vendor", + "venture", + "venue", + "verb", + "verify", + "version", + "very", + "vessel", + "veteran", + "viable", + "vibrant", + "vicious", + "victory", + "video", + "view", + "village", + "vintage", + "violin", + "virtual", + "virus", + "visa", + "visit", + "visual", + "vital", + "vivid", + "vocal", + "voice", + "void", + "volcano", + "volume", + "vote", + "voyage", + "wage", + "wagon", + "wait", + "walk", + "wall", + "walnut", + "want", + "warfare", + "warm", + "warrior", + "wash", + "wasp", + "waste", + "water", + "wave", + "way", + "wealth", + "weapon", + "wear", + "weasel", + "weather", + "web", + "wedding", + "weekend", + "weird", + "welcome", + "west", + "wet", + "whale", + "what", + "wheat", + "wheel", + "when", + "where", + "whip", + "whisper", + "wide", + "width", + "wife", + "wild", + "will", + "win", + "window", + "wine", + "wing", + "wink", + "winner", + "winter", + "wire", + "wisdom", + "wise", + "wish", + "witness", + "wolf", + "woman", + "wonder", + "wood", + "wool", + "word", + "work", + "world", + "worry", + "worth", + "wrap", + "wreck", + "wrestle", + "wrist", + "write", + "wrong", + "yard", + "year", + "yellow", + "you", + "young", + "youth", + "zebra", + "zero", + "zone", + "zoo" +] + +},{}],53:[function(require,module,exports){ +module.exports=[ + "あいこくしん", + "あいさつ", + "あいだ", + "あおぞら", + "あかちゃん", + "あきる", + "あけがた", + "あける", + "あこがれる", + "あさい", + "あさひ", + "あしあと", + "あじわう", + "あずかる", + "あずき", + "あそぶ", + "あたえる", + "あたためる", + "あたりまえ", + "あたる", + "あつい", + "あつかう", + "あっしゅく", + "あつまり", + "あつめる", + "あてな", + "あてはまる", + "あひる", + "あぶら", + "あぶる", + "あふれる", + "あまい", + "あまど", + "あまやかす", + "あまり", + "あみもの", + "あめりか", + "あやまる", + "あゆむ", + "あらいぐま", + "あらし", + "あらすじ", + "あらためる", + "あらゆる", + "あらわす", + "ありがとう", + "あわせる", + "あわてる", + "あんい", + "あんがい", + "あんこ", + "あんぜん", + "あんてい", + "あんない", + "あんまり", + "いいだす", + "いおん", + "いがい", + "いがく", + "いきおい", + "いきなり", + "いきもの", + "いきる", + "いくじ", + "いくぶん", + "いけばな", + "いけん", + "いこう", + "いこく", + "いこつ", + "いさましい", + "いさん", + "いしき", + "いじゅう", + "いじょう", + "いじわる", + "いずみ", + "いずれ", + "いせい", + "いせえび", + "いせかい", + "いせき", + "いぜん", + "いそうろう", + "いそがしい", + "いだい", + "いだく", + "いたずら", + "いたみ", + "いたりあ", + "いちおう", + "いちじ", + "いちど", + "いちば", + "いちぶ", + "いちりゅう", + "いつか", + "いっしゅん", + "いっせい", + "いっそう", + "いったん", + "いっち", + "いってい", + "いっぽう", + "いてざ", + "いてん", + "いどう", + "いとこ", + "いない", + "いなか", + "いねむり", + "いのち", + "いのる", + "いはつ", + "いばる", + "いはん", + "いびき", + "いひん", + "いふく", + "いへん", + "いほう", + "いみん", + "いもうと", + "いもたれ", + "いもり", + "いやがる", + "いやす", + "いよかん", + "いよく", + "いらい", + "いらすと", + "いりぐち", + "いりょう", + "いれい", + "いれもの", + "いれる", + "いろえんぴつ", + "いわい", + "いわう", + "いわかん", + "いわば", + "いわゆる", + "いんげんまめ", + "いんさつ", + "いんしょう", + "いんよう", + "うえき", + "うえる", + "うおざ", + "うがい", + "うかぶ", + "うかべる", + "うきわ", + "うくらいな", + "うくれれ", + "うけたまわる", + "うけつけ", + "うけとる", + "うけもつ", + "うける", + "うごかす", + "うごく", + "うこん", + "うさぎ", + "うしなう", + "うしろがみ", + "うすい", + "うすぎ", + "うすぐらい", + "うすめる", + "うせつ", + "うちあわせ", + "うちがわ", + "うちき", + "うちゅう", + "うっかり", + "うつくしい", + "うったえる", + "うつる", + "うどん", + "うなぎ", + "うなじ", + "うなずく", + "うなる", + "うねる", + "うのう", + "うぶげ", + "うぶごえ", + "うまれる", + "うめる", + "うもう", + "うやまう", + "うよく", + "うらがえす", + "うらぐち", + "うらない", + "うりあげ", + "うりきれ", + "うるさい", + "うれしい", + "うれゆき", + "うれる", + "うろこ", + "うわき", + "うわさ", + "うんこう", + "うんちん", + "うんてん", + "うんどう", + "えいえん", + "えいが", + "えいきょう", + "えいご", + "えいせい", + "えいぶん", + "えいよう", + "えいわ", + "えおり", + "えがお", + "えがく", + "えきたい", + "えくせる", + "えしゃく", + "えすて", + "えつらん", + "えのぐ", + "えほうまき", + "えほん", + "えまき", + "えもじ", + "えもの", + "えらい", + "えらぶ", + "えりあ", + "えんえん", + "えんかい", + "えんぎ", + "えんげき", + "えんしゅう", + "えんぜつ", + "えんそく", + "えんちょう", + "えんとつ", + "おいかける", + "おいこす", + "おいしい", + "おいつく", + "おうえん", + "おうさま", + "おうじ", + "おうせつ", + "おうたい", + "おうふく", + "おうべい", + "おうよう", + "おえる", + "おおい", + "おおう", + "おおどおり", + "おおや", + "おおよそ", + "おかえり", + "おかず", + "おがむ", + "おかわり", + "おぎなう", + "おきる", + "おくさま", + "おくじょう", + "おくりがな", + "おくる", + "おくれる", + "おこす", + "おこなう", + "おこる", + "おさえる", + "おさない", + "おさめる", + "おしいれ", + "おしえる", + "おじぎ", + "おじさん", + "おしゃれ", + "おそらく", + "おそわる", + "おたがい", + "おたく", + "おだやか", + "おちつく", + "おっと", + "おつり", + "おでかけ", + "おとしもの", + "おとなしい", + "おどり", + "おどろかす", + "おばさん", + "おまいり", + "おめでとう", + "おもいで", + "おもう", + "おもたい", + "おもちゃ", + "おやつ", + "おやゆび", + "およぼす", + "おらんだ", + "おろす", + "おんがく", + "おんけい", + "おんしゃ", + "おんせん", + "おんだん", + "おんちゅう", + "おんどけい", + "かあつ", + "かいが", + "がいき", + "がいけん", + "がいこう", + "かいさつ", + "かいしゃ", + "かいすいよく", + "かいぜん", + "かいぞうど", + "かいつう", + "かいてん", + "かいとう", + "かいふく", + "がいへき", + "かいほう", + "かいよう", + "がいらい", + "かいわ", + "かえる", + "かおり", + "かかえる", + "かがく", + "かがし", + "かがみ", + "かくご", + "かくとく", + "かざる", + "がぞう", + "かたい", + "かたち", + "がちょう", + "がっきゅう", + "がっこう", + "がっさん", + "がっしょう", + "かなざわし", + "かのう", + "がはく", + "かぶか", + "かほう", + "かほご", + "かまう", + "かまぼこ", + "かめれおん", + "かゆい", + "かようび", + "からい", + "かるい", + "かろう", + "かわく", + "かわら", + "がんか", + "かんけい", + "かんこう", + "かんしゃ", + "かんそう", + "かんたん", + "かんち", + "がんばる", + "きあい", + "きあつ", + "きいろ", + "ぎいん", + "きうい", + "きうん", + "きえる", + "きおう", + "きおく", + "きおち", + "きおん", + "きかい", + "きかく", + "きかんしゃ", + "ききて", + "きくばり", + "きくらげ", + "きけんせい", + "きこう", + "きこえる", + "きこく", + "きさい", + "きさく", + "きさま", + "きさらぎ", + "ぎじかがく", + "ぎしき", + "ぎじたいけん", + "ぎじにってい", + "ぎじゅつしゃ", + "きすう", + "きせい", + "きせき", + "きせつ", + "きそう", + "きぞく", + "きぞん", + "きたえる", + "きちょう", + "きつえん", + "ぎっちり", + "きつつき", + "きつね", + "きてい", + "きどう", + "きどく", + "きない", + "きなが", + "きなこ", + "きぬごし", + "きねん", + "きのう", + "きのした", + "きはく", + "きびしい", + "きひん", + "きふく", + "きぶん", + "きぼう", + "きほん", + "きまる", + "きみつ", + "きむずかしい", + "きめる", + "きもだめし", + "きもち", + "きもの", + "きゃく", + "きやく", + "ぎゅうにく", + "きよう", + "きょうりゅう", + "きらい", + "きらく", + "きりん", + "きれい", + "きれつ", + "きろく", + "ぎろん", + "きわめる", + "ぎんいろ", + "きんかくじ", + "きんじょ", + "きんようび", + "ぐあい", + "くいず", + "くうかん", + "くうき", + "くうぐん", + "くうこう", + "ぐうせい", + "くうそう", + "ぐうたら", + "くうふく", + "くうぼ", + "くかん", + "くきょう", + "くげん", + "ぐこう", + "くさい", + "くさき", + "くさばな", + "くさる", + "くしゃみ", + "くしょう", + "くすのき", + "くすりゆび", + "くせげ", + "くせん", + "ぐたいてき", + "くださる", + "くたびれる", + "くちこみ", + "くちさき", + "くつした", + "ぐっすり", + "くつろぐ", + "くとうてん", + "くどく", + "くなん", + "くねくね", + "くのう", + "くふう", + "くみあわせ", + "くみたてる", + "くめる", + "くやくしょ", + "くらす", + "くらべる", + "くるま", + "くれる", + "くろう", + "くわしい", + "ぐんかん", + "ぐんしょく", + "ぐんたい", + "ぐんて", + "けあな", + "けいかく", + "けいけん", + "けいこ", + "けいさつ", + "げいじゅつ", + "けいたい", + "げいのうじん", + "けいれき", + "けいろ", + "けおとす", + "けおりもの", + "げきか", + "げきげん", + "げきだん", + "げきちん", + "げきとつ", + "げきは", + "げきやく", + "げこう", + "げこくじょう", + "げざい", + "けさき", + "げざん", + "けしき", + "けしごむ", + "けしょう", + "げすと", + "けたば", + "けちゃっぷ", + "けちらす", + "けつあつ", + "けつい", + "けつえき", + "けっこん", + "けつじょ", + "けっせき", + "けってい", + "けつまつ", + "げつようび", + "げつれい", + "けつろん", + "げどく", + "けとばす", + "けとる", + "けなげ", + "けなす", + "けなみ", + "けぬき", + "げねつ", + "けねん", + "けはい", + "げひん", + "けぶかい", + "げぼく", + "けまり", + "けみかる", + "けむし", + "けむり", + "けもの", + "けらい", + "けろけろ", + "けわしい", + "けんい", + "けんえつ", + "けんお", + "けんか", + "げんき", + "けんげん", + "けんこう", + "けんさく", + "けんしゅう", + "けんすう", + "げんそう", + "けんちく", + "けんてい", + "けんとう", + "けんない", + "けんにん", + "げんぶつ", + "けんま", + "けんみん", + "けんめい", + "けんらん", + "けんり", + "こあくま", + "こいぬ", + "こいびと", + "ごうい", + "こうえん", + "こうおん", + "こうかん", + "ごうきゅう", + "ごうけい", + "こうこう", + "こうさい", + "こうじ", + "こうすい", + "ごうせい", + "こうそく", + "こうたい", + "こうちゃ", + "こうつう", + "こうてい", + "こうどう", + "こうない", + "こうはい", + "ごうほう", + "ごうまん", + "こうもく", + "こうりつ", + "こえる", + "こおり", + "ごかい", + "ごがつ", + "ごかん", + "こくご", + "こくさい", + "こくとう", + "こくない", + "こくはく", + "こぐま", + "こけい", + "こける", + "ここのか", + "こころ", + "こさめ", + "こしつ", + "こすう", + "こせい", + "こせき", + "こぜん", + "こそだて", + "こたい", + "こたえる", + "こたつ", + "こちょう", + "こっか", + "こつこつ", + "こつばん", + "こつぶ", + "こてい", + "こてん", + "ことがら", + "ことし", + "ことば", + "ことり", + "こなごな", + "こねこね", + "このまま", + "このみ", + "このよ", + "ごはん", + "こひつじ", + "こふう", + "こふん", + "こぼれる", + "ごまあぶら", + "こまかい", + "ごますり", + "こまつな", + "こまる", + "こむぎこ", + "こもじ", + "こもち", + "こもの", + "こもん", + "こやく", + "こやま", + "こゆう", + "こゆび", + "こよい", + "こよう", + "こりる", + "これくしょん", + "ころっけ", + "こわもて", + "こわれる", + "こんいん", + "こんかい", + "こんき", + "こんしゅう", + "こんすい", + "こんだて", + "こんとん", + "こんなん", + "こんびに", + "こんぽん", + "こんまけ", + "こんや", + "こんれい", + "こんわく", + "ざいえき", + "さいかい", + "さいきん", + "ざいげん", + "ざいこ", + "さいしょ", + "さいせい", + "ざいたく", + "ざいちゅう", + "さいてき", + "ざいりょう", + "さうな", + "さかいし", + "さがす", + "さかな", + "さかみち", + "さがる", + "さぎょう", + "さくし", + "さくひん", + "さくら", + "さこく", + "さこつ", + "さずかる", + "ざせき", + "さたん", + "さつえい", + "ざつおん", + "ざっか", + "ざつがく", + "さっきょく", + "ざっし", + "さつじん", + "ざっそう", + "さつたば", + "さつまいも", + "さてい", + "さといも", + "さとう", + "さとおや", + "さとし", + "さとる", + "さのう", + "さばく", + "さびしい", + "さべつ", + "さほう", + "さほど", + "さます", + "さみしい", + "さみだれ", + "さむけ", + "さめる", + "さやえんどう", + "さゆう", + "さよう", + "さよく", + "さらだ", + "ざるそば", + "さわやか", + "さわる", + "さんいん", + "さんか", + "さんきゃく", + "さんこう", + "さんさい", + "ざんしょ", + "さんすう", + "さんせい", + "さんそ", + "さんち", + "さんま", + "さんみ", + "さんらん", + "しあい", + "しあげ", + "しあさって", + "しあわせ", + "しいく", + "しいん", + "しうち", + "しえい", + "しおけ", + "しかい", + "しかく", + "じかん", + "しごと", + "しすう", + "じだい", + "したうけ", + "したぎ", + "したて", + "したみ", + "しちょう", + "しちりん", + "しっかり", + "しつじ", + "しつもん", + "してい", + "してき", + "してつ", + "じてん", + "じどう", + "しなぎれ", + "しなもの", + "しなん", + "しねま", + "しねん", + "しのぐ", + "しのぶ", + "しはい", + "しばかり", + "しはつ", + "しはらい", + "しはん", + "しひょう", + "しふく", + "じぶん", + "しへい", + "しほう", + "しほん", + "しまう", + "しまる", + "しみん", + "しむける", + "じむしょ", + "しめい", + "しめる", + "しもん", + "しゃいん", + "しゃうん", + "しゃおん", + "じゃがいも", + "しやくしょ", + "しゃくほう", + "しゃけん", + "しゃこ", + "しゃざい", + "しゃしん", + "しゃせん", + "しゃそう", + "しゃたい", + "しゃちょう", + "しゃっきん", + "じゃま", + "しゃりん", + "しゃれい", + "じゆう", + "じゅうしょ", + "しゅくはく", + "じゅしん", + "しゅっせき", + "しゅみ", + "しゅらば", + "じゅんばん", + "しょうかい", + "しょくたく", + "しょっけん", + "しょどう", + "しょもつ", + "しらせる", + "しらべる", + "しんか", + "しんこう", + "じんじゃ", + "しんせいじ", + "しんちく", + "しんりん", + "すあげ", + "すあし", + "すあな", + "ずあん", + "すいえい", + "すいか", + "すいとう", + "ずいぶん", + "すいようび", + "すうがく", + "すうじつ", + "すうせん", + "すおどり", + "すきま", + "すくう", + "すくない", + "すける", + "すごい", + "すこし", + "ずさん", + "すずしい", + "すすむ", + "すすめる", + "すっかり", + "ずっしり", + "ずっと", + "すてき", + "すてる", + "すねる", + "すのこ", + "すはだ", + "すばらしい", + "ずひょう", + "ずぶぬれ", + "すぶり", + "すふれ", + "すべて", + "すべる", + "ずほう", + "すぼん", + "すまい", + "すめし", + "すもう", + "すやき", + "すらすら", + "するめ", + "すれちがう", + "すろっと", + "すわる", + "すんぜん", + "すんぽう", + "せあぶら", + "せいかつ", + "せいげん", + "せいじ", + "せいよう", + "せおう", + "せかいかん", + "せきにん", + "せきむ", + "せきゆ", + "せきらんうん", + "せけん", + "せこう", + "せすじ", + "せたい", + "せたけ", + "せっかく", + "せっきゃく", + "ぜっく", + "せっけん", + "せっこつ", + "せっさたくま", + "せつぞく", + "せつだん", + "せつでん", + "せっぱん", + "せつび", + "せつぶん", + "せつめい", + "せつりつ", + "せなか", + "せのび", + "せはば", + "せびろ", + "せぼね", + "せまい", + "せまる", + "せめる", + "せもたれ", + "せりふ", + "ぜんあく", + "せんい", + "せんえい", + "せんか", + "せんきょ", + "せんく", + "せんげん", + "ぜんご", + "せんさい", + "せんしゅ", + "せんすい", + "せんせい", + "せんぞ", + "せんたく", + "せんちょう", + "せんてい", + "せんとう", + "せんぬき", + "せんねん", + "せんぱい", + "ぜんぶ", + "ぜんぽう", + "せんむ", + "せんめんじょ", + "せんもん", + "せんやく", + "せんゆう", + "せんよう", + "ぜんら", + "ぜんりゃく", + "せんれい", + "せんろ", + "そあく", + "そいとげる", + "そいね", + "そうがんきょう", + "そうき", + "そうご", + "そうしん", + "そうだん", + "そうなん", + "そうび", + "そうめん", + "そうり", + "そえもの", + "そえん", + "そがい", + "そげき", + "そこう", + "そこそこ", + "そざい", + "そしな", + "そせい", + "そせん", + "そそぐ", + "そだてる", + "そつう", + "そつえん", + "そっかん", + "そつぎょう", + "そっけつ", + "そっこう", + "そっせん", + "そっと", + "そとがわ", + "そとづら", + "そなえる", + "そなた", + "そふぼ", + "そぼく", + "そぼろ", + "そまつ", + "そまる", + "そむく", + "そむりえ", + "そめる", + "そもそも", + "そよかぜ", + "そらまめ", + "そろう", + "そんかい", + "そんけい", + "そんざい", + "そんしつ", + "そんぞく", + "そんちょう", + "ぞんび", + "ぞんぶん", + "そんみん", + "たあい", + "たいいん", + "たいうん", + "たいえき", + "たいおう", + "だいがく", + "たいき", + "たいぐう", + "たいけん", + "たいこ", + "たいざい", + "だいじょうぶ", + "だいすき", + "たいせつ", + "たいそう", + "だいたい", + "たいちょう", + "たいてい", + "だいどころ", + "たいない", + "たいねつ", + "たいのう", + "たいはん", + "だいひょう", + "たいふう", + "たいへん", + "たいほ", + "たいまつばな", + "たいみんぐ", + "たいむ", + "たいめん", + "たいやき", + "たいよう", + "たいら", + "たいりょく", + "たいる", + "たいわん", + "たうえ", + "たえる", + "たおす", + "たおる", + "たおれる", + "たかい", + "たかね", + "たきび", + "たくさん", + "たこく", + "たこやき", + "たさい", + "たしざん", + "だじゃれ", + "たすける", + "たずさわる", + "たそがれ", + "たたかう", + "たたく", + "ただしい", + "たたみ", + "たちばな", + "だっかい", + "だっきゃく", + "だっこ", + "だっしゅつ", + "だったい", + "たてる", + "たとえる", + "たなばた", + "たにん", + "たぬき", + "たのしみ", + "たはつ", + "たぶん", + "たべる", + "たぼう", + "たまご", + "たまる", + "だむる", + "ためいき", + "ためす", + "ためる", + "たもつ", + "たやすい", + "たよる", + "たらす", + "たりきほんがん", + "たりょう", + "たりる", + "たると", + "たれる", + "たれんと", + "たろっと", + "たわむれる", + "だんあつ", + "たんい", + "たんおん", + "たんか", + "たんき", + "たんけん", + "たんご", + "たんさん", + "たんじょうび", + "だんせい", + "たんそく", + "たんたい", + "だんち", + "たんてい", + "たんとう", + "だんな", + "たんにん", + "だんねつ", + "たんのう", + "たんぴん", + "だんぼう", + "たんまつ", + "たんめい", + "だんれつ", + "だんろ", + "だんわ", + "ちあい", + "ちあん", + "ちいき", + "ちいさい", + "ちえん", + "ちかい", + "ちから", + "ちきゅう", + "ちきん", + "ちけいず", + "ちけん", + "ちこく", + "ちさい", + "ちしき", + "ちしりょう", + "ちせい", + "ちそう", + "ちたい", + "ちたん", + "ちちおや", + "ちつじょ", + "ちてき", + "ちてん", + "ちぬき", + "ちぬり", + "ちのう", + "ちひょう", + "ちへいせん", + "ちほう", + "ちまた", + "ちみつ", + "ちみどろ", + "ちめいど", + "ちゃんこなべ", + "ちゅうい", + "ちゆりょく", + "ちょうし", + "ちょさくけん", + "ちらし", + "ちらみ", + "ちりがみ", + "ちりょう", + "ちるど", + "ちわわ", + "ちんたい", + "ちんもく", + "ついか", + "ついたち", + "つうか", + "つうじょう", + "つうはん", + "つうわ", + "つかう", + "つかれる", + "つくね", + "つくる", + "つけね", + "つける", + "つごう", + "つたえる", + "つづく", + "つつじ", + "つつむ", + "つとめる", + "つながる", + "つなみ", + "つねづね", + "つのる", + "つぶす", + "つまらない", + "つまる", + "つみき", + "つめたい", + "つもり", + "つもる", + "つよい", + "つるぼ", + "つるみく", + "つわもの", + "つわり", + "てあし", + "てあて", + "てあみ", + "ていおん", + "ていか", + "ていき", + "ていけい", + "ていこく", + "ていさつ", + "ていし", + "ていせい", + "ていたい", + "ていど", + "ていねい", + "ていひょう", + "ていへん", + "ていぼう", + "てうち", + "ておくれ", + "てきとう", + "てくび", + "でこぼこ", + "てさぎょう", + "てさげ", + "てすり", + "てそう", + "てちがい", + "てちょう", + "てつがく", + "てつづき", + "でっぱ", + "てつぼう", + "てつや", + "でぬかえ", + "てぬき", + "てぬぐい", + "てのひら", + "てはい", + "てぶくろ", + "てふだ", + "てほどき", + "てほん", + "てまえ", + "てまきずし", + "てみじか", + "てみやげ", + "てらす", + "てれび", + "てわけ", + "てわたし", + "でんあつ", + "てんいん", + "てんかい", + "てんき", + "てんぐ", + "てんけん", + "てんごく", + "てんさい", + "てんし", + "てんすう", + "でんち", + "てんてき", + "てんとう", + "てんない", + "てんぷら", + "てんぼうだい", + "てんめつ", + "てんらんかい", + "でんりょく", + "でんわ", + "どあい", + "といれ", + "どうかん", + "とうきゅう", + "どうぐ", + "とうし", + "とうむぎ", + "とおい", + "とおか", + "とおく", + "とおす", + "とおる", + "とかい", + "とかす", + "ときおり", + "ときどき", + "とくい", + "とくしゅう", + "とくてん", + "とくに", + "とくべつ", + "とけい", + "とける", + "とこや", + "とさか", + "としょかん", + "とそう", + "とたん", + "とちゅう", + "とっきゅう", + "とっくん", + "とつぜん", + "とつにゅう", + "とどける", + "ととのえる", + "とない", + "となえる", + "となり", + "とのさま", + "とばす", + "どぶがわ", + "とほう", + "とまる", + "とめる", + "ともだち", + "ともる", + "どようび", + "とらえる", + "とんかつ", + "どんぶり", + "ないかく", + "ないこう", + "ないしょ", + "ないす", + "ないせん", + "ないそう", + "なおす", + "ながい", + "なくす", + "なげる", + "なこうど", + "なさけ", + "なたでここ", + "なっとう", + "なつやすみ", + "ななおし", + "なにごと", + "なにもの", + "なにわ", + "なのか", + "なふだ", + "なまいき", + "なまえ", + "なまみ", + "なみだ", + "なめらか", + "なめる", + "なやむ", + "ならう", + "ならび", + "ならぶ", + "なれる", + "なわとび", + "なわばり", + "にあう", + "にいがた", + "にうけ", + "におい", + "にかい", + "にがて", + "にきび", + "にくしみ", + "にくまん", + "にげる", + "にさんかたんそ", + "にしき", + "にせもの", + "にちじょう", + "にちようび", + "にっか", + "にっき", + "にっけい", + "にっこう", + "にっさん", + "にっしょく", + "にっすう", + "にっせき", + "にってい", + "になう", + "にほん", + "にまめ", + "にもつ", + "にやり", + "にゅういん", + "にりんしゃ", + "にわとり", + "にんい", + "にんか", + "にんき", + "にんげん", + "にんしき", + "にんずう", + "にんそう", + "にんたい", + "にんち", + "にんてい", + "にんにく", + "にんぷ", + "にんまり", + "にんむ", + "にんめい", + "にんよう", + "ぬいくぎ", + "ぬかす", + "ぬぐいとる", + "ぬぐう", + "ぬくもり", + "ぬすむ", + "ぬまえび", + "ぬめり", + "ぬらす", + "ぬんちゃく", + "ねあげ", + "ねいき", + "ねいる", + "ねいろ", + "ねぐせ", + "ねくたい", + "ねくら", + "ねこぜ", + "ねこむ", + "ねさげ", + "ねすごす", + "ねそべる", + "ねだん", + "ねつい", + "ねっしん", + "ねつぞう", + "ねったいぎょ", + "ねぶそく", + "ねふだ", + "ねぼう", + "ねほりはほり", + "ねまき", + "ねまわし", + "ねみみ", + "ねむい", + "ねむたい", + "ねもと", + "ねらう", + "ねわざ", + "ねんいり", + "ねんおし", + "ねんかん", + "ねんきん", + "ねんぐ", + "ねんざ", + "ねんし", + "ねんちゃく", + "ねんど", + "ねんぴ", + "ねんぶつ", + "ねんまつ", + "ねんりょう", + "ねんれい", + "のいず", + "のおづま", + "のがす", + "のきなみ", + "のこぎり", + "のこす", + "のこる", + "のせる", + "のぞく", + "のぞむ", + "のたまう", + "のちほど", + "のっく", + "のばす", + "のはら", + "のべる", + "のぼる", + "のみもの", + "のやま", + "のらいぬ", + "のらねこ", + "のりもの", + "のりゆき", + "のれん", + "のんき", + "ばあい", + "はあく", + "ばあさん", + "ばいか", + "ばいく", + "はいけん", + "はいご", + "はいしん", + "はいすい", + "はいせん", + "はいそう", + "はいち", + "ばいばい", + "はいれつ", + "はえる", + "はおる", + "はかい", + "ばかり", + "はかる", + "はくしゅ", + "はけん", + "はこぶ", + "はさみ", + "はさん", + "はしご", + "ばしょ", + "はしる", + "はせる", + "ぱそこん", + "はそん", + "はたん", + "はちみつ", + "はつおん", + "はっかく", + "はづき", + "はっきり", + "はっくつ", + "はっけん", + "はっこう", + "はっさん", + "はっしん", + "はったつ", + "はっちゅう", + "はってん", + "はっぴょう", + "はっぽう", + "はなす", + "はなび", + "はにかむ", + "はぶらし", + "はみがき", + "はむかう", + "はめつ", + "はやい", + "はやし", + "はらう", + "はろうぃん", + "はわい", + "はんい", + "はんえい", + "はんおん", + "はんかく", + "はんきょう", + "ばんぐみ", + "はんこ", + "はんしゃ", + "はんすう", + "はんだん", + "ぱんち", + "ぱんつ", + "はんてい", + "はんとし", + "はんのう", + "はんぱ", + "はんぶん", + "はんぺん", + "はんぼうき", + "はんめい", + "はんらん", + "はんろん", + "ひいき", + "ひうん", + "ひえる", + "ひかく", + "ひかり", + "ひかる", + "ひかん", + "ひくい", + "ひけつ", + "ひこうき", + "ひこく", + "ひさい", + "ひさしぶり", + "ひさん", + "びじゅつかん", + "ひしょ", + "ひそか", + "ひそむ", + "ひたむき", + "ひだり", + "ひたる", + "ひつぎ", + "ひっこし", + "ひっし", + "ひつじゅひん", + "ひっす", + "ひつぜん", + "ぴったり", + "ぴっちり", + "ひつよう", + "ひてい", + "ひとごみ", + "ひなまつり", + "ひなん", + "ひねる", + "ひはん", + "ひびく", + "ひひょう", + "ひほう", + "ひまわり", + "ひまん", + "ひみつ", + "ひめい", + "ひめじし", + "ひやけ", + "ひやす", + "ひよう", + "びょうき", + "ひらがな", + "ひらく", + "ひりつ", + "ひりょう", + "ひるま", + "ひるやすみ", + "ひれい", + "ひろい", + "ひろう", + "ひろき", + "ひろゆき", + "ひんかく", + "ひんけつ", + "ひんこん", + "ひんしゅ", + "ひんそう", + "ぴんち", + "ひんぱん", + "びんぼう", + "ふあん", + "ふいうち", + "ふうけい", + "ふうせん", + "ぷうたろう", + "ふうとう", + "ふうふ", + "ふえる", + "ふおん", + "ふかい", + "ふきん", + "ふくざつ", + "ふくぶくろ", + "ふこう", + "ふさい", + "ふしぎ", + "ふじみ", + "ふすま", + "ふせい", + "ふせぐ", + "ふそく", + "ぶたにく", + "ふたん", + "ふちょう", + "ふつう", + "ふつか", + "ふっかつ", + "ふっき", + "ふっこく", + "ぶどう", + "ふとる", + "ふとん", + "ふのう", + "ふはい", + "ふひょう", + "ふへん", + "ふまん", + "ふみん", + "ふめつ", + "ふめん", + "ふよう", + "ふりこ", + "ふりる", + "ふるい", + "ふんいき", + "ぶんがく", + "ぶんぐ", + "ふんしつ", + "ぶんせき", + "ふんそう", + "ぶんぽう", + "へいあん", + "へいおん", + "へいがい", + "へいき", + "へいげん", + "へいこう", + "へいさ", + "へいしゃ", + "へいせつ", + "へいそ", + "へいたく", + "へいてん", + "へいねつ", + "へいわ", + "へきが", + "へこむ", + "べにいろ", + "べにしょうが", + "へらす", + "へんかん", + "べんきょう", + "べんごし", + "へんさい", + "へんたい", + "べんり", + "ほあん", + "ほいく", + "ぼうぎょ", + "ほうこく", + "ほうそう", + "ほうほう", + "ほうもん", + "ほうりつ", + "ほえる", + "ほおん", + "ほかん", + "ほきょう", + "ぼきん", + "ほくろ", + "ほけつ", + "ほけん", + "ほこう", + "ほこる", + "ほしい", + "ほしつ", + "ほしゅ", + "ほしょう", + "ほせい", + "ほそい", + "ほそく", + "ほたて", + "ほたる", + "ぽちぶくろ", + "ほっきょく", + "ほっさ", + "ほったん", + "ほとんど", + "ほめる", + "ほんい", + "ほんき", + "ほんけ", + "ほんしつ", + "ほんやく", + "まいにち", + "まかい", + "まかせる", + "まがる", + "まける", + "まこと", + "まさつ", + "まじめ", + "ますく", + "まぜる", + "まつり", + "まとめ", + "まなぶ", + "まぬけ", + "まねく", + "まほう", + "まもる", + "まゆげ", + "まよう", + "まろやか", + "まわす", + "まわり", + "まわる", + "まんが", + "まんきつ", + "まんぞく", + "まんなか", + "みいら", + "みうち", + "みえる", + "みがく", + "みかた", + "みかん", + "みけん", + "みこん", + "みじかい", + "みすい", + "みすえる", + "みせる", + "みっか", + "みつかる", + "みつける", + "みてい", + "みとめる", + "みなと", + "みなみかさい", + "みねらる", + "みのう", + "みのがす", + "みほん", + "みもと", + "みやげ", + "みらい", + "みりょく", + "みわく", + "みんか", + "みんぞく", + "むいか", + "むえき", + "むえん", + "むかい", + "むかう", + "むかえ", + "むかし", + "むぎちゃ", + "むける", + "むげん", + "むさぼる", + "むしあつい", + "むしば", + "むじゅん", + "むしろ", + "むすう", + "むすこ", + "むすぶ", + "むすめ", + "むせる", + "むせん", + "むちゅう", + "むなしい", + "むのう", + "むやみ", + "むよう", + "むらさき", + "むりょう", + "むろん", + "めいあん", + "めいうん", + "めいえん", + "めいかく", + "めいきょく", + "めいさい", + "めいし", + "めいそう", + "めいぶつ", + "めいれい", + "めいわく", + "めぐまれる", + "めざす", + "めした", + "めずらしい", + "めだつ", + "めまい", + "めやす", + "めんきょ", + "めんせき", + "めんどう", + "もうしあげる", + "もうどうけん", + "もえる", + "もくし", + "もくてき", + "もくようび", + "もちろん", + "もどる", + "もらう", + "もんく", + "もんだい", + "やおや", + "やける", + "やさい", + "やさしい", + "やすい", + "やすたろう", + "やすみ", + "やせる", + "やそう", + "やたい", + "やちん", + "やっと", + "やっぱり", + "やぶる", + "やめる", + "ややこしい", + "やよい", + "やわらかい", + "ゆうき", + "ゆうびんきょく", + "ゆうべ", + "ゆうめい", + "ゆけつ", + "ゆしゅつ", + "ゆせん", + "ゆそう", + "ゆたか", + "ゆちゃく", + "ゆでる", + "ゆにゅう", + "ゆびわ", + "ゆらい", + "ゆれる", + "ようい", + "ようか", + "ようきゅう", + "ようじ", + "ようす", + "ようちえん", + "よかぜ", + "よかん", + "よきん", + "よくせい", + "よくぼう", + "よけい", + "よごれる", + "よさん", + "よしゅう", + "よそう", + "よそく", + "よっか", + "よてい", + "よどがわく", + "よねつ", + "よやく", + "よゆう", + "よろこぶ", + "よろしい", + "らいう", + "らくがき", + "らくご", + "らくさつ", + "らくだ", + "らしんばん", + "らせん", + "らぞく", + "らたい", + "らっか", + "られつ", + "りえき", + "りかい", + "りきさく", + "りきせつ", + "りくぐん", + "りくつ", + "りけん", + "りこう", + "りせい", + "りそう", + "りそく", + "りてん", + "りねん", + "りゆう", + "りゅうがく", + "りよう", + "りょうり", + "りょかん", + "りょくちゃ", + "りょこう", + "りりく", + "りれき", + "りろん", + "りんご", + "るいけい", + "るいさい", + "るいじ", + "るいせき", + "るすばん", + "るりがわら", + "れいかん", + "れいぎ", + "れいせい", + "れいぞうこ", + "れいとう", + "れいぼう", + "れきし", + "れきだい", + "れんあい", + "れんけい", + "れんこん", + "れんさい", + "れんしゅう", + "れんぞく", + "れんらく", + "ろうか", + "ろうご", + "ろうじん", + "ろうそく", + "ろくが", + "ろこつ", + "ろじうら", + "ろしゅつ", + "ろせん", + "ろてん", + "ろめん", + "ろれつ", + "ろんぎ", + "ろんぱ", + "ろんぶん", + "ろんり", + "わかす", + "わかめ", + "わかやま", + "わかれる", + "わしつ", + "わじまし", + "わすれもの", + "わらう", + "われる" +] + +},{}],54:[function(require,module,exports){ +module.exports=[ + "abacate", + "abaixo", + "abalar", + "abater", + "abduzir", + "abelha", + "aberto", + "abismo", + "abotoar", + "abranger", + "abreviar", + "abrigar", + "abrupto", + "absinto", + "absoluto", + "absurdo", + "abutre", + "acabado", + "acalmar", + "acampar", + "acanhar", + "acaso", + "aceitar", + "acelerar", + "acenar", + "acervo", + "acessar", + "acetona", + "achatar", + "acidez", + "acima", + "acionado", + "acirrar", + "aclamar", + "aclive", + "acolhida", + "acomodar", + "acoplar", + "acordar", + "acumular", + "acusador", + "adaptar", + "adega", + "adentro", + "adepto", + "adequar", + "aderente", + "adesivo", + "adeus", + "adiante", + "aditivo", + "adjetivo", + "adjunto", + "admirar", + "adorar", + "adquirir", + "adubo", + "adverso", + "advogado", + "aeronave", + "afastar", + "aferir", + "afetivo", + "afinador", + "afivelar", + "aflito", + "afluente", + "afrontar", + "agachar", + "agarrar", + "agasalho", + "agenciar", + "agilizar", + "agiota", + "agitado", + "agora", + "agradar", + "agreste", + "agrupar", + "aguardar", + "agulha", + "ajoelhar", + "ajudar", + "ajustar", + "alameda", + "alarme", + "alastrar", + "alavanca", + "albergue", + "albino", + "alcatra", + "aldeia", + "alecrim", + "alegria", + "alertar", + "alface", + "alfinete", + "algum", + "alheio", + "aliar", + "alicate", + "alienar", + "alinhar", + "aliviar", + "almofada", + "alocar", + "alpiste", + "alterar", + "altitude", + "alucinar", + "alugar", + "aluno", + "alusivo", + "alvo", + "amaciar", + "amador", + "amarelo", + "amassar", + "ambas", + "ambiente", + "ameixa", + "amenizar", + "amido", + "amistoso", + "amizade", + "amolador", + "amontoar", + "amoroso", + "amostra", + "amparar", + "ampliar", + "ampola", + "anagrama", + "analisar", + "anarquia", + "anatomia", + "andaime", + "anel", + "anexo", + "angular", + "animar", + "anjo", + "anomalia", + "anotado", + "ansioso", + "anterior", + "anuidade", + "anunciar", + "anzol", + "apagador", + "apalpar", + "apanhado", + "apego", + "apelido", + "apertada", + "apesar", + "apetite", + "apito", + "aplauso", + "aplicada", + "apoio", + "apontar", + "aposta", + "aprendiz", + "aprovar", + "aquecer", + "arame", + "aranha", + "arara", + "arcada", + "ardente", + "areia", + "arejar", + "arenito", + "aresta", + "argiloso", + "argola", + "arma", + "arquivo", + "arraial", + "arrebate", + "arriscar", + "arroba", + "arrumar", + "arsenal", + "arterial", + "artigo", + "arvoredo", + "asfaltar", + "asilado", + "aspirar", + "assador", + "assinar", + "assoalho", + "assunto", + "astral", + "atacado", + "atadura", + "atalho", + "atarefar", + "atear", + "atender", + "aterro", + "ateu", + "atingir", + "atirador", + "ativo", + "atoleiro", + "atracar", + "atrevido", + "atriz", + "atual", + "atum", + "auditor", + "aumentar", + "aura", + "aurora", + "autismo", + "autoria", + "autuar", + "avaliar", + "avante", + "avaria", + "avental", + "avesso", + "aviador", + "avisar", + "avulso", + "axila", + "azarar", + "azedo", + "azeite", + "azulejo", + "babar", + "babosa", + "bacalhau", + "bacharel", + "bacia", + "bagagem", + "baiano", + "bailar", + "baioneta", + "bairro", + "baixista", + "bajular", + "baleia", + "baliza", + "balsa", + "banal", + "bandeira", + "banho", + "banir", + "banquete", + "barato", + "barbado", + "baronesa", + "barraca", + "barulho", + "baseado", + "bastante", + "batata", + "batedor", + "batida", + "batom", + "batucar", + "baunilha", + "beber", + "beijo", + "beirada", + "beisebol", + "beldade", + "beleza", + "belga", + "beliscar", + "bendito", + "bengala", + "benzer", + "berimbau", + "berlinda", + "berro", + "besouro", + "bexiga", + "bezerro", + "bico", + "bicudo", + "bienal", + "bifocal", + "bifurcar", + "bigorna", + "bilhete", + "bimestre", + "bimotor", + "biologia", + "biombo", + "biosfera", + "bipolar", + "birrento", + "biscoito", + "bisneto", + "bispo", + "bissexto", + "bitola", + "bizarro", + "blindado", + "bloco", + "bloquear", + "boato", + "bobagem", + "bocado", + "bocejo", + "bochecha", + "boicotar", + "bolada", + "boletim", + "bolha", + "bolo", + "bombeiro", + "bonde", + "boneco", + "bonita", + "borbulha", + "borda", + "boreal", + "borracha", + "bovino", + "boxeador", + "branco", + "brasa", + "braveza", + "breu", + "briga", + "brilho", + "brincar", + "broa", + "brochura", + "bronzear", + "broto", + "bruxo", + "bucha", + "budismo", + "bufar", + "bule", + "buraco", + "busca", + "busto", + "buzina", + "cabana", + "cabelo", + "cabide", + "cabo", + "cabrito", + "cacau", + "cacetada", + "cachorro", + "cacique", + "cadastro", + "cadeado", + "cafezal", + "caiaque", + "caipira", + "caixote", + "cajado", + "caju", + "calafrio", + "calcular", + "caldeira", + "calibrar", + "calmante", + "calota", + "camada", + "cambista", + "camisa", + "camomila", + "campanha", + "camuflar", + "canavial", + "cancelar", + "caneta", + "canguru", + "canhoto", + "canivete", + "canoa", + "cansado", + "cantar", + "canudo", + "capacho", + "capela", + "capinar", + "capotar", + "capricho", + "captador", + "capuz", + "caracol", + "carbono", + "cardeal", + "careca", + "carimbar", + "carneiro", + "carpete", + "carreira", + "cartaz", + "carvalho", + "casaco", + "casca", + "casebre", + "castelo", + "casulo", + "catarata", + "cativar", + "caule", + "causador", + "cautelar", + "cavalo", + "caverna", + "cebola", + "cedilha", + "cegonha", + "celebrar", + "celular", + "cenoura", + "censo", + "centeio", + "cercar", + "cerrado", + "certeiro", + "cerveja", + "cetim", + "cevada", + "chacota", + "chaleira", + "chamado", + "chapada", + "charme", + "chatice", + "chave", + "chefe", + "chegada", + "cheiro", + "cheque", + "chicote", + "chifre", + "chinelo", + "chocalho", + "chover", + "chumbo", + "chutar", + "chuva", + "cicatriz", + "ciclone", + "cidade", + "cidreira", + "ciente", + "cigana", + "cimento", + "cinto", + "cinza", + "ciranda", + "circuito", + "cirurgia", + "citar", + "clareza", + "clero", + "clicar", + "clone", + "clube", + "coado", + "coagir", + "cobaia", + "cobertor", + "cobrar", + "cocada", + "coelho", + "coentro", + "coeso", + "cogumelo", + "coibir", + "coifa", + "coiote", + "colar", + "coleira", + "colher", + "colidir", + "colmeia", + "colono", + "coluna", + "comando", + "combinar", + "comentar", + "comitiva", + "comover", + "complexo", + "comum", + "concha", + "condor", + "conectar", + "confuso", + "congelar", + "conhecer", + "conjugar", + "consumir", + "contrato", + "convite", + "cooperar", + "copeiro", + "copiador", + "copo", + "coquetel", + "coragem", + "cordial", + "corneta", + "coronha", + "corporal", + "correio", + "cortejo", + "coruja", + "corvo", + "cosseno", + "costela", + "cotonete", + "couro", + "couve", + "covil", + "cozinha", + "cratera", + "cravo", + "creche", + "credor", + "creme", + "crer", + "crespo", + "criada", + "criminal", + "crioulo", + "crise", + "criticar", + "crosta", + "crua", + "cruzeiro", + "cubano", + "cueca", + "cuidado", + "cujo", + "culatra", + "culminar", + "culpar", + "cultura", + "cumprir", + "cunhado", + "cupido", + "curativo", + "curral", + "cursar", + "curto", + "cuspir", + "custear", + "cutelo", + "damasco", + "datar", + "debater", + "debitar", + "deboche", + "debulhar", + "decalque", + "decimal", + "declive", + "decote", + "decretar", + "dedal", + "dedicado", + "deduzir", + "defesa", + "defumar", + "degelo", + "degrau", + "degustar", + "deitado", + "deixar", + "delator", + "delegado", + "delinear", + "delonga", + "demanda", + "demitir", + "demolido", + "dentista", + "depenado", + "depilar", + "depois", + "depressa", + "depurar", + "deriva", + "derramar", + "desafio", + "desbotar", + "descanso", + "desenho", + "desfiado", + "desgaste", + "desigual", + "deslize", + "desmamar", + "desova", + "despesa", + "destaque", + "desviar", + "detalhar", + "detentor", + "detonar", + "detrito", + "deusa", + "dever", + "devido", + "devotado", + "dezena", + "diagrama", + "dialeto", + "didata", + "difuso", + "digitar", + "dilatado", + "diluente", + "diminuir", + "dinastia", + "dinheiro", + "diocese", + "direto", + "discreta", + "disfarce", + "disparo", + "disquete", + "dissipar", + "distante", + "ditador", + "diurno", + "diverso", + "divisor", + "divulgar", + "dizer", + "dobrador", + "dolorido", + "domador", + "dominado", + "donativo", + "donzela", + "dormente", + "dorsal", + "dosagem", + "dourado", + "doutor", + "drenagem", + "drible", + "drogaria", + "duelar", + "duende", + "dueto", + "duplo", + "duquesa", + "durante", + "duvidoso", + "eclodir", + "ecoar", + "ecologia", + "edificar", + "edital", + "educado", + "efeito", + "efetivar", + "ejetar", + "elaborar", + "eleger", + "eleitor", + "elenco", + "elevador", + "eliminar", + "elogiar", + "embargo", + "embolado", + "embrulho", + "embutido", + "emenda", + "emergir", + "emissor", + "empatia", + "empenho", + "empinado", + "empolgar", + "emprego", + "empurrar", + "emulador", + "encaixe", + "encenado", + "enchente", + "encontro", + "endeusar", + "endossar", + "enfaixar", + "enfeite", + "enfim", + "engajado", + "engenho", + "englobar", + "engomado", + "engraxar", + "enguia", + "enjoar", + "enlatar", + "enquanto", + "enraizar", + "enrolado", + "enrugar", + "ensaio", + "enseada", + "ensino", + "ensopado", + "entanto", + "enteado", + "entidade", + "entortar", + "entrada", + "entulho", + "envergar", + "enviado", + "envolver", + "enxame", + "enxerto", + "enxofre", + "enxuto", + "epiderme", + "equipar", + "ereto", + "erguido", + "errata", + "erva", + "ervilha", + "esbanjar", + "esbelto", + "escama", + "escola", + "escrita", + "escuta", + "esfinge", + "esfolar", + "esfregar", + "esfumado", + "esgrima", + "esmalte", + "espanto", + "espelho", + "espiga", + "esponja", + "espreita", + "espumar", + "esquerda", + "estaca", + "esteira", + "esticar", + "estofado", + "estrela", + "estudo", + "esvaziar", + "etanol", + "etiqueta", + "euforia", + "europeu", + "evacuar", + "evaporar", + "evasivo", + "eventual", + "evidente", + "evoluir", + "exagero", + "exalar", + "examinar", + "exato", + "exausto", + "excesso", + "excitar", + "exclamar", + "executar", + "exemplo", + "exibir", + "exigente", + "exonerar", + "expandir", + "expelir", + "expirar", + "explanar", + "exposto", + "expresso", + "expulsar", + "externo", + "extinto", + "extrato", + "fabricar", + "fabuloso", + "faceta", + "facial", + "fada", + "fadiga", + "faixa", + "falar", + "falta", + "familiar", + "fandango", + "fanfarra", + "fantoche", + "fardado", + "farelo", + "farinha", + "farofa", + "farpa", + "fartura", + "fatia", + "fator", + "favorita", + "faxina", + "fazenda", + "fechado", + "feijoada", + "feirante", + "felino", + "feminino", + "fenda", + "feno", + "fera", + "feriado", + "ferrugem", + "ferver", + "festejar", + "fetal", + "feudal", + "fiapo", + "fibrose", + "ficar", + "ficheiro", + "figurado", + "fileira", + "filho", + "filme", + "filtrar", + "firmeza", + "fisgada", + "fissura", + "fita", + "fivela", + "fixador", + "fixo", + "flacidez", + "flamingo", + "flanela", + "flechada", + "flora", + "flutuar", + "fluxo", + "focal", + "focinho", + "fofocar", + "fogo", + "foguete", + "foice", + "folgado", + "folheto", + "forjar", + "formiga", + "forno", + "forte", + "fosco", + "fossa", + "fragata", + "fralda", + "frango", + "frasco", + "fraterno", + "freira", + "frente", + "fretar", + "frieza", + "friso", + "fritura", + "fronha", + "frustrar", + "fruteira", + "fugir", + "fulano", + "fuligem", + "fundar", + "fungo", + "funil", + "furador", + "furioso", + "futebol", + "gabarito", + "gabinete", + "gado", + "gaiato", + "gaiola", + "gaivota", + "galega", + "galho", + "galinha", + "galocha", + "ganhar", + "garagem", + "garfo", + "gargalo", + "garimpo", + "garoupa", + "garrafa", + "gasoduto", + "gasto", + "gata", + "gatilho", + "gaveta", + "gazela", + "gelado", + "geleia", + "gelo", + "gemada", + "gemer", + "gemido", + "generoso", + "gengiva", + "genial", + "genoma", + "genro", + "geologia", + "gerador", + "germinar", + "gesso", + "gestor", + "ginasta", + "gincana", + "gingado", + "girafa", + "girino", + "glacial", + "glicose", + "global", + "glorioso", + "goela", + "goiaba", + "golfe", + "golpear", + "gordura", + "gorjeta", + "gorro", + "gostoso", + "goteira", + "governar", + "gracejo", + "gradual", + "grafite", + "gralha", + "grampo", + "granada", + "gratuito", + "graveto", + "graxa", + "grego", + "grelhar", + "greve", + "grilo", + "grisalho", + "gritaria", + "grosso", + "grotesco", + "grudado", + "grunhido", + "gruta", + "guache", + "guarani", + "guaxinim", + "guerrear", + "guiar", + "guincho", + "guisado", + "gula", + "guloso", + "guru", + "habitar", + "harmonia", + "haste", + "haver", + "hectare", + "herdar", + "heresia", + "hesitar", + "hiato", + "hibernar", + "hidratar", + "hiena", + "hino", + "hipismo", + "hipnose", + "hipoteca", + "hoje", + "holofote", + "homem", + "honesto", + "honrado", + "hormonal", + "hospedar", + "humorado", + "iate", + "ideia", + "idoso", + "ignorado", + "igreja", + "iguana", + "ileso", + "ilha", + "iludido", + "iluminar", + "ilustrar", + "imagem", + "imediato", + "imenso", + "imersivo", + "iminente", + "imitador", + "imortal", + "impacto", + "impedir", + "implante", + "impor", + "imprensa", + "impune", + "imunizar", + "inalador", + "inapto", + "inativo", + "incenso", + "inchar", + "incidir", + "incluir", + "incolor", + "indeciso", + "indireto", + "indutor", + "ineficaz", + "inerente", + "infantil", + "infestar", + "infinito", + "inflamar", + "informal", + "infrator", + "ingerir", + "inibido", + "inicial", + "inimigo", + "injetar", + "inocente", + "inodoro", + "inovador", + "inox", + "inquieto", + "inscrito", + "inseto", + "insistir", + "inspetor", + "instalar", + "insulto", + "intacto", + "integral", + "intimar", + "intocado", + "intriga", + "invasor", + "inverno", + "invicto", + "invocar", + "iogurte", + "iraniano", + "ironizar", + "irreal", + "irritado", + "isca", + "isento", + "isolado", + "isqueiro", + "italiano", + "janeiro", + "jangada", + "janta", + "jararaca", + "jardim", + "jarro", + "jasmim", + "jato", + "javali", + "jazida", + "jejum", + "joaninha", + "joelhada", + "jogador", + "joia", + "jornal", + "jorrar", + "jovem", + "juba", + "judeu", + "judoca", + "juiz", + "julgador", + "julho", + "jurado", + "jurista", + "juro", + "justa", + "labareda", + "laboral", + "lacre", + "lactante", + "ladrilho", + "lagarta", + "lagoa", + "laje", + "lamber", + "lamentar", + "laminar", + "lampejo", + "lanche", + "lapidar", + "lapso", + "laranja", + "lareira", + "largura", + "lasanha", + "lastro", + "lateral", + "latido", + "lavanda", + "lavoura", + "lavrador", + "laxante", + "lazer", + "lealdade", + "lebre", + "legado", + "legendar", + "legista", + "leigo", + "leiloar", + "leitura", + "lembrete", + "leme", + "lenhador", + "lentilha", + "leoa", + "lesma", + "leste", + "letivo", + "letreiro", + "levar", + "leveza", + "levitar", + "liberal", + "libido", + "liderar", + "ligar", + "ligeiro", + "limitar", + "limoeiro", + "limpador", + "linda", + "linear", + "linhagem", + "liquidez", + "listagem", + "lisura", + "litoral", + "livro", + "lixa", + "lixeira", + "locador", + "locutor", + "lojista", + "lombo", + "lona", + "longe", + "lontra", + "lorde", + "lotado", + "loteria", + "loucura", + "lousa", + "louvar", + "luar", + "lucidez", + "lucro", + "luneta", + "lustre", + "lutador", + "luva", + "macaco", + "macete", + "machado", + "macio", + "madeira", + "madrinha", + "magnata", + "magreza", + "maior", + "mais", + "malandro", + "malha", + "malote", + "maluco", + "mamilo", + "mamoeiro", + "mamute", + "manada", + "mancha", + "mandato", + "manequim", + "manhoso", + "manivela", + "manobrar", + "mansa", + "manter", + "manusear", + "mapeado", + "maquinar", + "marcador", + "maresia", + "marfim", + "margem", + "marinho", + "marmita", + "maroto", + "marquise", + "marreco", + "martelo", + "marujo", + "mascote", + "masmorra", + "massagem", + "mastigar", + "matagal", + "materno", + "matinal", + "matutar", + "maxilar", + "medalha", + "medida", + "medusa", + "megafone", + "meiga", + "melancia", + "melhor", + "membro", + "memorial", + "menino", + "menos", + "mensagem", + "mental", + "merecer", + "mergulho", + "mesada", + "mesclar", + "mesmo", + "mesquita", + "mestre", + "metade", + "meteoro", + "metragem", + "mexer", + "mexicano", + "micro", + "migalha", + "migrar", + "milagre", + "milenar", + "milhar", + "mimado", + "minerar", + "minhoca", + "ministro", + "minoria", + "miolo", + "mirante", + "mirtilo", + "misturar", + "mocidade", + "moderno", + "modular", + "moeda", + "moer", + "moinho", + "moita", + "moldura", + "moleza", + "molho", + "molinete", + "molusco", + "montanha", + "moqueca", + "morango", + "morcego", + "mordomo", + "morena", + "mosaico", + "mosquete", + "mostarda", + "motel", + "motim", + "moto", + "motriz", + "muda", + "muito", + "mulata", + "mulher", + "multar", + "mundial", + "munido", + "muralha", + "murcho", + "muscular", + "museu", + "musical", + "nacional", + "nadador", + "naja", + "namoro", + "narina", + "narrado", + "nascer", + "nativa", + "natureza", + "navalha", + "navegar", + "navio", + "neblina", + "nebuloso", + "negativa", + "negociar", + "negrito", + "nervoso", + "neta", + "neural", + "nevasca", + "nevoeiro", + "ninar", + "ninho", + "nitidez", + "nivelar", + "nobreza", + "noite", + "noiva", + "nomear", + "nominal", + "nordeste", + "nortear", + "notar", + "noticiar", + "noturno", + "novelo", + "novilho", + "novo", + "nublado", + "nudez", + "numeral", + "nupcial", + "nutrir", + "nuvem", + "obcecado", + "obedecer", + "objetivo", + "obrigado", + "obscuro", + "obstetra", + "obter", + "obturar", + "ocidente", + "ocioso", + "ocorrer", + "oculista", + "ocupado", + "ofegante", + "ofensiva", + "oferenda", + "oficina", + "ofuscado", + "ogiva", + "olaria", + "oleoso", + "olhar", + "oliveira", + "ombro", + "omelete", + "omisso", + "omitir", + "ondulado", + "oneroso", + "ontem", + "opcional", + "operador", + "oponente", + "oportuno", + "oposto", + "orar", + "orbitar", + "ordem", + "ordinal", + "orfanato", + "orgasmo", + "orgulho", + "oriental", + "origem", + "oriundo", + "orla", + "ortodoxo", + "orvalho", + "oscilar", + "ossada", + "osso", + "ostentar", + "otimismo", + "ousadia", + "outono", + "outubro", + "ouvido", + "ovelha", + "ovular", + "oxidar", + "oxigenar", + "pacato", + "paciente", + "pacote", + "pactuar", + "padaria", + "padrinho", + "pagar", + "pagode", + "painel", + "pairar", + "paisagem", + "palavra", + "palestra", + "palheta", + "palito", + "palmada", + "palpitar", + "pancada", + "panela", + "panfleto", + "panqueca", + "pantanal", + "papagaio", + "papelada", + "papiro", + "parafina", + "parcial", + "pardal", + "parede", + "partida", + "pasmo", + "passado", + "pastel", + "patamar", + "patente", + "patinar", + "patrono", + "paulada", + "pausar", + "peculiar", + "pedalar", + "pedestre", + "pediatra", + "pedra", + "pegada", + "peitoral", + "peixe", + "pele", + "pelicano", + "penca", + "pendurar", + "peneira", + "penhasco", + "pensador", + "pente", + "perceber", + "perfeito", + "pergunta", + "perito", + "permitir", + "perna", + "perplexo", + "persiana", + "pertence", + "peruca", + "pescado", + "pesquisa", + "pessoa", + "petiscar", + "piada", + "picado", + "piedade", + "pigmento", + "pilastra", + "pilhado", + "pilotar", + "pimenta", + "pincel", + "pinguim", + "pinha", + "pinote", + "pintar", + "pioneiro", + "pipoca", + "piquete", + "piranha", + "pires", + "pirueta", + "piscar", + "pistola", + "pitanga", + "pivete", + "planta", + "plaqueta", + "platina", + "plebeu", + "plumagem", + "pluvial", + "pneu", + "poda", + "poeira", + "poetisa", + "polegada", + "policiar", + "poluente", + "polvilho", + "pomar", + "pomba", + "ponderar", + "pontaria", + "populoso", + "porta", + "possuir", + "postal", + "pote", + "poupar", + "pouso", + "povoar", + "praia", + "prancha", + "prato", + "praxe", + "prece", + "predador", + "prefeito", + "premiar", + "prensar", + "preparar", + "presilha", + "pretexto", + "prevenir", + "prezar", + "primata", + "princesa", + "prisma", + "privado", + "processo", + "produto", + "profeta", + "proibido", + "projeto", + "prometer", + "propagar", + "prosa", + "protetor", + "provador", + "publicar", + "pudim", + "pular", + "pulmonar", + "pulseira", + "punhal", + "punir", + "pupilo", + "pureza", + "puxador", + "quadra", + "quantia", + "quarto", + "quase", + "quebrar", + "queda", + "queijo", + "quente", + "querido", + "quimono", + "quina", + "quiosque", + "rabanada", + "rabisco", + "rachar", + "racionar", + "radial", + "raiar", + "rainha", + "raio", + "raiva", + "rajada", + "ralado", + "ramal", + "ranger", + "ranhura", + "rapadura", + "rapel", + "rapidez", + "raposa", + "raquete", + "raridade", + "rasante", + "rascunho", + "rasgar", + "raspador", + "rasteira", + "rasurar", + "ratazana", + "ratoeira", + "realeza", + "reanimar", + "reaver", + "rebaixar", + "rebelde", + "rebolar", + "recado", + "recente", + "recheio", + "recibo", + "recordar", + "recrutar", + "recuar", + "rede", + "redimir", + "redonda", + "reduzida", + "reenvio", + "refinar", + "refletir", + "refogar", + "refresco", + "refugiar", + "regalia", + "regime", + "regra", + "reinado", + "reitor", + "rejeitar", + "relativo", + "remador", + "remendo", + "remorso", + "renovado", + "reparo", + "repelir", + "repleto", + "repolho", + "represa", + "repudiar", + "requerer", + "resenha", + "resfriar", + "resgatar", + "residir", + "resolver", + "respeito", + "ressaca", + "restante", + "resumir", + "retalho", + "reter", + "retirar", + "retomada", + "retratar", + "revelar", + "revisor", + "revolta", + "riacho", + "rica", + "rigidez", + "rigoroso", + "rimar", + "ringue", + "risada", + "risco", + "risonho", + "robalo", + "rochedo", + "rodada", + "rodeio", + "rodovia", + "roedor", + "roleta", + "romano", + "roncar", + "rosado", + "roseira", + "rosto", + "rota", + "roteiro", + "rotina", + "rotular", + "rouco", + "roupa", + "roxo", + "rubro", + "rugido", + "rugoso", + "ruivo", + "rumo", + "rupestre", + "russo", + "sabor", + "saciar", + "sacola", + "sacudir", + "sadio", + "safira", + "saga", + "sagrada", + "saibro", + "salada", + "saleiro", + "salgado", + "saliva", + "salpicar", + "salsicha", + "saltar", + "salvador", + "sambar", + "samurai", + "sanar", + "sanfona", + "sangue", + "sanidade", + "sapato", + "sarda", + "sargento", + "sarjeta", + "saturar", + "saudade", + "saxofone", + "sazonal", + "secar", + "secular", + "seda", + "sedento", + "sediado", + "sedoso", + "sedutor", + "segmento", + "segredo", + "segundo", + "seiva", + "seleto", + "selvagem", + "semanal", + "semente", + "senador", + "senhor", + "sensual", + "sentado", + "separado", + "sereia", + "seringa", + "serra", + "servo", + "setembro", + "setor", + "sigilo", + "silhueta", + "silicone", + "simetria", + "simpatia", + "simular", + "sinal", + "sincero", + "singular", + "sinopse", + "sintonia", + "sirene", + "siri", + "situado", + "soberano", + "sobra", + "socorro", + "sogro", + "soja", + "solda", + "soletrar", + "solteiro", + "sombrio", + "sonata", + "sondar", + "sonegar", + "sonhador", + "sono", + "soprano", + "soquete", + "sorrir", + "sorteio", + "sossego", + "sotaque", + "soterrar", + "sovado", + "sozinho", + "suavizar", + "subida", + "submerso", + "subsolo", + "subtrair", + "sucata", + "sucesso", + "suco", + "sudeste", + "sufixo", + "sugador", + "sugerir", + "sujeito", + "sulfato", + "sumir", + "suor", + "superior", + "suplicar", + "suposto", + "suprimir", + "surdina", + "surfista", + "surpresa", + "surreal", + "surtir", + "suspiro", + "sustento", + "tabela", + "tablete", + "tabuada", + "tacho", + "tagarela", + "talher", + "talo", + "talvez", + "tamanho", + "tamborim", + "tampa", + "tangente", + "tanto", + "tapar", + "tapioca", + "tardio", + "tarefa", + "tarja", + "tarraxa", + "tatuagem", + "taurino", + "taxativo", + "taxista", + "teatral", + "tecer", + "tecido", + "teclado", + "tedioso", + "teia", + "teimar", + "telefone", + "telhado", + "tempero", + "tenente", + "tensor", + "tentar", + "termal", + "terno", + "terreno", + "tese", + "tesoura", + "testado", + "teto", + "textura", + "texugo", + "tiara", + "tigela", + "tijolo", + "timbrar", + "timidez", + "tingido", + "tinteiro", + "tiragem", + "titular", + "toalha", + "tocha", + "tolerar", + "tolice", + "tomada", + "tomilho", + "tonel", + "tontura", + "topete", + "tora", + "torcido", + "torneio", + "torque", + "torrada", + "torto", + "tostar", + "touca", + "toupeira", + "toxina", + "trabalho", + "tracejar", + "tradutor", + "trafegar", + "trajeto", + "trama", + "trancar", + "trapo", + "traseiro", + "tratador", + "travar", + "treino", + "tremer", + "trepidar", + "trevo", + "triagem", + "tribo", + "triciclo", + "tridente", + "trilogia", + "trindade", + "triplo", + "triturar", + "triunfal", + "trocar", + "trombeta", + "trova", + "trunfo", + "truque", + "tubular", + "tucano", + "tudo", + "tulipa", + "tupi", + "turbo", + "turma", + "turquesa", + "tutelar", + "tutorial", + "uivar", + "umbigo", + "unha", + "unidade", + "uniforme", + "urologia", + "urso", + "urtiga", + "urubu", + "usado", + "usina", + "usufruir", + "vacina", + "vadiar", + "vagaroso", + "vaidoso", + "vala", + "valente", + "validade", + "valores", + "vantagem", + "vaqueiro", + "varanda", + "vareta", + "varrer", + "vascular", + "vasilha", + "vassoura", + "vazar", + "vazio", + "veado", + "vedar", + "vegetar", + "veicular", + "veleiro", + "velhice", + "veludo", + "vencedor", + "vendaval", + "venerar", + "ventre", + "verbal", + "verdade", + "vereador", + "vergonha", + "vermelho", + "verniz", + "versar", + "vertente", + "vespa", + "vestido", + "vetorial", + "viaduto", + "viagem", + "viajar", + "viatura", + "vibrador", + "videira", + "vidraria", + "viela", + "viga", + "vigente", + "vigiar", + "vigorar", + "vilarejo", + "vinco", + "vinheta", + "vinil", + "violeta", + "virada", + "virtude", + "visitar", + "visto", + "vitral", + "viveiro", + "vizinho", + "voador", + "voar", + "vogal", + "volante", + "voleibol", + "voltagem", + "volumoso", + "vontade", + "vulto", + "vuvuzela", + "xadrez", + "xarope", + "xeque", + "xeretar", + "xerife", + "xingar", + "zangado", + "zarpar", + "zebu", + "zelador", + "zombar", + "zoologia", + "zumbido" +] + +},{}]},{},[50])(50) +}); diff --git a/src/index.js b/src/index.js index d5389d1..7230328 100644 --- a/src/index.js +++ b/src/index.js @@ -1,19 +1,22 @@ -import { TransactionBuilder } from './js/transactionBuilder'; -import { TransactionBatcher } from './js/transactionBatcher'; -import { Network } from './js/network'; -import { Encoder } from './js/encoder'; -import { Keystore } from './js/keystore'; -import { LamdenMasterNode_API as Masternode_API } from './js/masternode-api'; -import * as wallet from './js/wallet'; -import * as utils from './js/helpers'; +import { TransactionBuilder } from "./js/transactionBuilder"; +import { TransactionBatcher } from "./js/transactionBatcher"; +import { Network } from "./js/network"; +import { Encoder } from "./js/encoder"; +import { Keystore } from "./js/keystore"; +import { LamdenMasterNode_API as Masternode_API } from "./js/masternode-api"; +import * as wallet from "./js/wallet"; +import * as utils from "./js/helpers"; +import { Buffer } from "buffer"; + +globalThis.Buffer = Buffer; export default { - TransactionBuilder, - TransactionBatcher, - Masternode_API, - Network, - wallet, - Keystore, - Encoder, - utils -}; \ No newline at end of file + TransactionBuilder, + TransactionBatcher, + Masternode_API, + Network, + wallet, + Keystore, + Encoder, + utils, +}; diff --git a/src/js/encoder.js b/src/js/encoder.js index 442c24d..8939d95 100644 --- a/src/js/encoder.js +++ b/src/js/encoder.js @@ -1,184 +1,186 @@ -const BigNumber = require('bignumber.js'); -BigNumber.config({ RANGE: [-30, 30], EXPONENTIAL_AT: 1e+9 }) -BigNumber.set({ DECIMAL_PLACES: 30, ROUNDING_MODE: BigNumber.ROUND_DOWN }) // equivalent - -function Encoder (type, value) { - const throwError = (val) => { - throw new Error(`Error encoding ${val} to ${type}`) - } - const countDecimals = (n) => { - if(Math.floor(n) === n) return 0; - try{ - return n.toString().split(".")[1].length - }catch (e){ - return 0 - } - } - const isString = (val) => typeof val === 'string' || val instanceof String; - const isArray = (val) => val && typeof val === 'object' && val.constructor === Array; - const isObject = (val) => val && typeof val === 'object' && val.constructor === Object; - const isDate = (val) => val instanceof Date; - const isBoolean = (val) => typeof val === 'boolean'; - - const isNumber = (val) => { - if (isArray(val)) return false - return !isNaN(encodeBigNumber(val).toNumber()) - } - - const isInteger = (val) => { - if (!isNumber(val)) return false - if (countDecimals(val) === 0) return true - return false - } - const encodeInt = (val) => { - if (!isNumber(val)) throwError(val) - else return parseInt(val) - } - const isFloat = (val) => { - if (!isNumber(val)) return false - if (countDecimals(val) === 0) return false - return true - } - const encodeFloat = (val) => { - if(!isNumber(val)) throwError(val) - if (!BigNumber.isBigNumber(val)) val = new BigNumber(val) - - return {"__fixed__": val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, '$1$2')} - } - const encodeNumber = (val) => { - if(!isNumber(val)) throwError(val) - if (isFloat(val)) { - if (!BigNumber.isBigNumber(val)) val = new BigNumber(val) - return {"__fixed__": val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, '$1$2')} - } - if (isInteger(val)) return parseInt(val) - } - const encodeBigNumber = (val) => { - if (!BigNumber.isBigNumber(val)) val = new BigNumber(val) - return val - } - - const encodeBool = (val) => { - if (isBoolean(val)) return val - if (val === 'true' || val === 1) return true - if (val === 'false' || val === 0) return false - throwError(val) - } - const encodeStr = (val) => { - if (isString(val)) return val - if (isDate(val)) return val.toISOString() - return JSON.stringify(val) - } - const encodeDateTime = (val) => { - val = !isDate(val) ? new Date(val) : val - if (!isDate(val)) throwError(val) - return {'__time__': [ - val.getUTCFullYear(), - val.getUTCMonth(), - val.getUTCDate(), - val.getUTCHours(), - val.getUTCMinutes(), - val.getUTCSeconds(), - val.getUTCMilliseconds() - ]} - } - const encodeTimeDelta = (val) => { - const time = isDate(val) ? val.getTime() : new Date(val).getTime() - const days = parseInt(time / 1000 / 60 / 60 / 24) - const seconds = (time - (days * 24 * 60 * 60 * 1000)) / 1000 - return {'__delta__':[days, seconds]} - } - - const encodeList = (val) => { - if (isArray(val)) return parseObject(val) - try{ - val = JSON.parse(val) - }catch(e){ - throwError(val) - } - if (isArray(val)) return parseObject(val) - throwError(val) - } - - const encodeDict = (val) => { - if (isObject(val)) return parseObject(val) - try{ - val = JSON.parse(val) - }catch(e){ - throwError(val) - } - if (isObject(val)) return parseObject(val) - throwError(val) - } - - const encodeObject = (val) => { - try { - return encodeList(val) - }catch(e){ - return encodeDict(val) - } - } - - function parseObject (obj) { - const encode = (k, v) => { - if (k === "datetime" || k === "datetime.datetime" ) return Encoder("datetime.datetime", v) - if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v) - if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v) - return v - } - - const fixDatetime = (k, v) => { - const isDatetimeObject = (val) => { - let datetimeTypes = ['datetime.datetime', 'datetime', 'datetime.timedelta', 'timedelta'] - return Object.keys(val).length === 1 && datetimeTypes.filter(f => f === Object.keys(val)[0]).length > 0 - - } - - if (v.constructor === Array) { - v.map(val => { - if (Object.keys(val).length === 1 && isDatetimeObject(v)) return val[Object.keys(val)[0]] - //if (isFloat(val)) return encodeFloat(val) - return val - }) - } - if (v.constructor === Object) { - if (Object.keys(v).length === 1 && isDatetimeObject(v)) return v[Object.keys(v)[0]] - } - - //if (isFloat(v)) return encodeFloat(v) - - return v - } - - let encodeValues = JSON.stringify(obj, encode) - return JSON.parse(encodeValues, fixDatetime) - } - - const encoder = { - str: encodeStr, - string: encodeStr, - float: encodeFloat, - int: encodeInt, - bool: encodeBool, - boolean: encodeBool, - dict: encodeDict, - list: encodeList, - Any: () => value, - "datetime.timedelta": encodeTimeDelta, - "datetime.datetime": encodeDateTime, - timedelta: encodeTimeDelta, - datetime: encodeDateTime, - number: encodeNumber, - object: encodeObject, - bigNumber: encodeBigNumber, - } - - if (Object.keys(encoder).includes(type)) return encoder[type](value) - else throw new Error(`Error: ${type} is not a valid encoder type.`) +import BigNumber from "bignumber.js"; +BigNumber.config({ RANGE: [-30, 30], EXPONENTIAL_AT: 1e9 }); +BigNumber.set({ DECIMAL_PLACES: 30, ROUNDING_MODE: BigNumber.ROUND_DOWN }); // equivalent + +export function Encoder(type, value) { + const throwError = (val) => { + throw new Error(`Error encoding ${val} to ${type}`); + }; + const countDecimals = (n) => { + if (Math.floor(n) === n) return 0; + try { + return n.toString().split(".")[1].length; + } catch (e) { + return 0; + } + }; + const isString = (val) => typeof val === "string" || val instanceof String; + const isArray = (val) => val && typeof val === "object" && val.constructor === Array; + const isObject = (val) => val && typeof val === "object" && val.constructor === Object; + const isDate = (val) => val instanceof Date; + const isBoolean = (val) => typeof val === "boolean"; + + const isNumber = (val) => { + if (isArray(val)) return false; + return !isNaN(encodeBigNumber(val).toNumber()); + }; + + const isInteger = (val) => { + if (!isNumber(val)) return false; + if (countDecimals(val) === 0) return true; + return false; + }; + const encodeInt = (val) => { + if (!isNumber(val)) throwError(val); + else return parseInt(val); + }; + const isFloat = (val) => { + if (!isNumber(val)) return false; + if (countDecimals(val) === 0) return false; + return true; + }; + const encodeFloat = (val) => { + if (!isNumber(val)) throwError(val); + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + + return { __fixed__: val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, "$1$2") }; + }; + const encodeNumber = (val) => { + if (!isNumber(val)) throwError(val); + if (isFloat(val)) { + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + return { __fixed__: val.toFixed(30).replace(/^0+(\d)|(\d)0+$/gm, "$1$2") }; + } + if (isInteger(val)) return parseInt(val); + }; + const encodeBigNumber = (val) => { + if (!BigNumber.isBigNumber(val)) val = new BigNumber(val); + return val; + }; + + const encodeBool = (val) => { + if (isBoolean(val)) return val; + if (val === "true" || val === 1) return true; + if (val === "false" || val === 0) return false; + throwError(val); + }; + const encodeStr = (val) => { + if (isString(val)) return val; + if (isDate(val)) return val.toISOString(); + return JSON.stringify(val); + }; + const encodeDateTime = (val) => { + val = !isDate(val) ? new Date(val) : val; + if (!isDate(val)) throwError(val); + return { + __time__: [ + val.getUTCFullYear(), + val.getUTCMonth(), + val.getUTCDate(), + val.getUTCHours(), + val.getUTCMinutes(), + val.getUTCSeconds(), + val.getUTCMilliseconds(), + ], + }; + }; + const encodeTimeDelta = (val) => { + const time = isDate(val) ? val.getTime() : new Date(val).getTime(); + const days = parseInt(time / 1000 / 60 / 60 / 24); + const seconds = (time - days * 24 * 60 * 60 * 1000) / 1000; + return { __delta__: [days, seconds] }; + }; + + const encodeList = (val) => { + if (isArray(val)) return parseObject(val); + try { + val = JSON.parse(val); + } catch (e) { + throwError(val); + } + if (isArray(val)) return parseObject(val); + throwError(val); + }; + + const encodeDict = (val) => { + if (isObject(val)) return parseObject(val); + try { + val = JSON.parse(val); + } catch (e) { + throwError(val); + } + if (isObject(val)) return parseObject(val); + throwError(val); + }; + + const encodeObject = (val) => { + try { + return encodeList(val); + } catch (e) { + return encodeDict(val); + } + }; + + function parseObject(obj) { + const encode = (k, v) => { + if (k === "datetime" || k === "datetime.datetime") return Encoder("datetime.datetime", v); + if (k === "timedelta" || k === "datetime.timedelta") return Encoder("datetime.timedelta", v); + if (k !== "__fixed__" && isFloat(v)) return encodeFloat(v); + return v; + }; + + const fixDatetime = (k, v) => { + const isDatetimeObject = (val) => { + let datetimeTypes = ["datetime.datetime", "datetime", "datetime.timedelta", "timedelta"]; + return ( + Object.keys(val).length === 1 && + datetimeTypes.filter((f) => f === Object.keys(val)[0]).length > 0 + ); + }; + + if (v.constructor === Array) { + v.map((val) => { + if (Object.keys(val).length === 1 && isDatetimeObject(v)) return val[Object.keys(val)[0]]; + //if (isFloat(val)) return encodeFloat(val) + return val; + }); + } + if (v.constructor === Object) { + if (Object.keys(v).length === 1 && isDatetimeObject(v)) return v[Object.keys(v)[0]]; + } + + //if (isFloat(v)) return encodeFloat(v) + + return v; + }; + + let encodeValues = JSON.stringify(obj, encode); + return JSON.parse(encodeValues, fixDatetime); + } + + const encoder = { + str: encodeStr, + string: encodeStr, + float: encodeFloat, + int: encodeInt, + bool: encodeBool, + boolean: encodeBool, + dict: encodeDict, + list: encodeList, + Any: () => value, + "datetime.timedelta": encodeTimeDelta, + "datetime.datetime": encodeDateTime, + timedelta: encodeTimeDelta, + datetime: encodeDateTime, + number: encodeNumber, + object: encodeObject, + bigNumber: encodeBigNumber, + }; + + if (Object.keys(encoder).includes(type)) return encoder[type](value); + else throw new Error(`Error: ${type} is not a valid encoder type.`); } -Encoder.BigNumber = BigNumber +Encoder.BigNumber = BigNumber; -module.exports = { - Encoder -} \ No newline at end of file +export default { Encoder }; diff --git a/src/js/helpers.js b/src/js/helpers.js index 4c1ed9c..54f1c3f 100644 --- a/src/js/helpers.js +++ b/src/js/helpers.js @@ -1,136 +1,140 @@ -const nodeCryptoJs = require("node-cryptojs-aes") +import nodeCryptoJs from "node-cryptojs-aes"; const { CryptoJS, JsonFormatter } = nodeCryptoJs; -const validators = require('types-validate-assert') +import validators from "types-validate-assert"; const { validateTypes, assertTypes } = validators; /** - * Encrypt a Javascript object with a string password - * The object passed must pass JSON.stringify or the method will fail. - * - * @param {string} password A password to encrypt the object with - * @param {Object} obj A javascript object (must be JSON compatible) - * @return {string} Encrypted string + * Encrypt a Javascript object with a string password + * The object passed must pass JSON.stringify or the method will fail. + * + * @param {string} password A password to encrypt the object with + * @param {Object} obj A javascript object (must be JSON compatible) + * @return {string} Encrypted string */ -export function encryptObject ( password, obj ){ - assertTypes.isStringWithValue(password) - assertTypes.isObject(obj) +export function encryptObject(password, obj) { + assertTypes.isStringWithValue(password); + assertTypes.isObject(obj); - const encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), password, { format: JsonFormatter }).toString(); - return encrypted; -}; + const encrypted = CryptoJS.AES.encrypt(JSON.stringify(obj), password, { + format: JsonFormatter, + }).toString(); + return encrypted; +} /** - * Decrypt an Object using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} objString A javascript object as JSON string - * @return {string} Encrypted string -*/ -export function decryptObject ( password, objString ) { - assertTypes.isStringWithValue(password) - assertTypes.isStringWithValue(objString) + * Decrypt an Object using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} objString A javascript object as JSON string + * @return {string} Encrypted string + */ +export function decryptObject(password, objString) { + assertTypes.isStringWithValue(password); + assertTypes.isStringWithValue(objString); - try{ - const decrypt = CryptoJS.AES.decrypt(objString, password, { format: JsonFormatter }) - return JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt)); - } catch (e){ - return false; - } -}; + try { + const decrypt = CryptoJS.AES.decrypt(objString, password, { format: JsonFormatter }); + return JSON.parse(CryptoJS.enc.Utf8.stringify(decrypt)); + } catch (e) { + return false; + } +} /** - * Encrypt a string using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} string A string to be password encrypted - * @return {string} Encrypted string -*/ -export function encryptStrHash( password, string ){ - assertTypes.isStringWithValue(password) - assertTypes.isString(string) + * Encrypt a string using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} string A string to be password encrypted + * @return {string} Encrypted string + */ +export function encryptStrHash(password, string) { + assertTypes.isStringWithValue(password); + assertTypes.isString(string); - const encrypt = CryptoJS.AES.encrypt(string, password).toString(); - return encrypt; -}; + const encrypt = CryptoJS.AES.encrypt(string, password).toString(); + return encrypt; +} /** - * Decrypt a string using a password string - * - * @param {string} password A password to encrypt the object with - * @param {string} encryptedString A string to decrypt - * @return {string} Decrypted string -*/ -export function decryptStrHash ( password, encryptedString ){ - assertTypes.isStringWithValue(password) - assertTypes.isStringWithValue(encryptedString) - - try{ - const decrypted = CryptoJS.AES.decrypt(encryptedString, password); - return CryptoJS.enc.Utf8.stringify(decrypted) === '' ? false : CryptoJS.enc.Utf8.stringify(decrypted); - } catch (e) { - return false; - } -}; + * Decrypt a string using a password string + * + * @param {string} password A password to encrypt the object with + * @param {string} encryptedString A string to decrypt + * @return {string} Decrypted string + */ +export function decryptStrHash(password, encryptedString) { + assertTypes.isStringWithValue(password); + assertTypes.isStringWithValue(encryptedString); + + try { + const decrypted = CryptoJS.AES.decrypt(encryptedString, password); + return CryptoJS.enc.Utf8.stringify(decrypted) === "" + ? false + : CryptoJS.enc.Utf8.stringify(decrypted); + } catch (e) { + return false; + } +} export function buf2hex(buffer) { - return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join(''); + return Array.prototype.map + .call(new Uint8Array(buffer), (x) => ("00" + x.toString(16)).slice(-2)) + .join(""); } export function hex2buf(hexString) { - var bytes = new Uint8Array(Math.ceil(hexString.length / 2)); - for (var i = 0; i < bytes.length; i++) - bytes[i] = parseInt(hexString.substr(i * 2, 2), 16); - return bytes; + var bytes = new Uint8Array(Math.ceil(hexString.length / 2)); + for (var i = 0; i < bytes.length; i++) bytes[i] = parseInt(hexString.substr(i * 2, 2), 16); + return bytes; } export function str2buf(string) { - var buf = new Buffer.from(string); - return new Uint8Array(buf); + var buf = new Buffer.from(string); + return new Uint8Array(buf); } export function concatUint8Arrays(array1, array2) { - var arr = new Uint8Array(array1.length + array2.length); - arr.set(array1); - arr.set(array2, array1.length); - return arr; + var arr = new Uint8Array(array1.length + array2.length); + arr.set(array1); + arr.set(array2, array1.length); + return arr; } export function ab2str(buf) { - return String.fromCharCode.apply(null, new Uint8Array(buf)); + return String.fromCharCode.apply(null, new Uint8Array(buf)); } export function str2ab(str) { - var buf = new ArrayBuffer(str.length); - var bufView = new Uint8Array(buf); - for (var i = 0, strLen = str.length; i < strLen; i++) { - bufView[i] = str.charCodeAt(i); - } - return buf; + var buf = new ArrayBuffer(str.length); + var bufView = new Uint8Array(buf); + for (var i = 0, strLen = str.length; i < strLen; i++) { + bufView[i] = str.charCodeAt(i); + } + return buf; } export function str2hex(str) { - var hex = ''; - for (var i = 0; i < str.length; i++) { - hex += '' + str.charCodeAt(i).toString(16); - } - return hex; + var hex = ""; + for (var i = 0; i < str.length; i++) { + hex += "" + str.charCodeAt(i).toString(16); + } + return hex; } export function hex2str(hexx) { - var hex = hexx.toString(); //force conversion - var str = ''; - for (var i = 0; (i < hex.length && hex.substr(i, 2) !== '00'); i += 2) - str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); - return str; + var hex = hexx.toString(); //force conversion + var str = ""; + for (var i = 0; i < hex.length && hex.substr(i, 2) !== "00"; i += 2) + str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + return str; } export function randomString(length) { - var text = ""; - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (var i = 0; i < length; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } - return text; + var text = ""; + var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + for (var i = 0; i < length; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } + return text; } -export function isStringHex(string = '') { - let hexRegEx = /([0-9]|[a-f])/gim; - return typeof string === 'string' && - (string.match(hexRegEx) || []).length === string.length; +export function isStringHex(string = "") { + let hexRegEx = /([0-9]|[a-f])/gim; + return typeof string === "string" && (string.match(hexRegEx) || []).length === string.length; } -export function isLamdenKey( string ){ - if (validateTypes.isStringHex(string) && string.length === 64) return true; - return false; -}; \ No newline at end of file +export function isLamdenKey(string) { + if (validateTypes.isStringHex(string) && string.length === 64) return true; + return false; +} diff --git a/src/js/keystore.js b/src/js/keystore.js index 569c649..6d48796 100644 --- a/src/js/keystore.js +++ b/src/js/keystore.js @@ -85,7 +85,13 @@ export class Keystore { } /** * Add a list of keys to add to the keystore - * @param {Array.} keyList An array of 32 character long Lamden private keys + * @typedef {Object} keyinfo + * @property {string} sk - The private key. + * @property {string} nickname - The key nickname. + * @property {string} name - The key name. + * @property {string} network - Network name. + * @property {string} symbol - The token symbol. + * @param {Array.} keyList An array of keyinfo Object */ addKeys(keyList){ assertTypes.isArray(keyList) @@ -93,7 +99,13 @@ export class Keystore { } /** * Add a key to the keystore - * @param {string} key A 32 character long Lamden private key + * @typedef {Object} keyinfo + * @property {string} sk - The private key. + * @property {string} nickname - The key nickname. + * @property {string} name - The key name. + * @property {string} network - Network name. + * @property {string} symbol - The token symbol. + * @param {keyinfo} keyInfo A keyinfo Object */ addKey(keyInfo){ assertTypes.isObjectWithKeys(keyInfo) diff --git a/src/js/masternode-api.js b/src/js/masternode-api.js index c1661b0..bb7919d 100644 --- a/src/js/masternode-api.js +++ b/src/js/masternode-api.js @@ -1,204 +1,211 @@ -import validators from 'types-validate-assert' +import validators from "types-validate-assert"; const { validateTypes } = validators; -const fetch = require('node-fetch').default; -import { Encoder } from './encoder' - -export class LamdenMasterNode_API{ - constructor(networkInfoObj){ - if (!validateTypes.isObjectWithKeys(networkInfoObj)) throw new Error(`Expected Object and got Type: ${typeof networkInfoObj}`) - if (!validateTypes.isArrayWithValues(networkInfoObj.hosts)) throw new Error(`HOSTS Required (Type: Array)`) - - this.hosts = this.validateHosts(networkInfoObj.hosts); - } - //This will throw an error if the protocol wasn't included in the host string - vaidateProtocol(host){ - let protocols = ['https://', 'http://'] - if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host - throw new Error('Host String must include http:// or https://') +import fetch from "node-fetch"; +import { Encoder } from "./encoder"; + +export class LamdenMasterNode_API { + constructor(networkInfoObj) { + if (!validateTypes.isObjectWithKeys(networkInfoObj)) + throw new Error(`Expected Object and got Type: ${typeof networkInfoObj}`); + if (!validateTypes.isArrayWithValues(networkInfoObj.hosts)) + throw new Error(`HOSTS Required (Type: Array)`); + + this.hosts = this.validateHosts(networkInfoObj.hosts); + } + //This will throw an error if the protocol wasn't included in the host string + vaidateProtocol(host) { + let protocols = ["https://", "http://"]; + if (protocols.map((protocol) => host.includes(protocol)).includes(true)) return host; + throw new Error("Host String must include http:// or https://"); + } + validateHosts(hosts) { + return hosts.map((host) => this.vaidateProtocol(host.toLowerCase())); + } + + get host() { + return this.hosts[Math.floor(Math.random() * this.hosts.length)]; + } + get url() { + return this.host; + } + + send(method, path, data, overrideURL, callback) { + let parms = ""; + if (Object.keys(data).includes("parms")) { + parms = this.createParms(data.parms); } - validateHosts(hosts){ - return hosts.map(host => this.vaidateProtocol(host.toLowerCase())) - } - - get host() {return this.hosts[Math.floor(Math.random() * this.hosts.length)]} - get url() {return this.host} - send(method, path, data, overrideURL, callback){ - let parms = ''; - if (Object.keys(data).includes('parms')) { - parms = this.createParms(data.parms) - } - - let options = {} - if (method === 'POST'){ - let headers = {'Content-Type': 'application/json'} - options.method = method - options.headers = headers; - options.body = data; - } - - return fetch(`${overrideURL ? overrideURL : this.url}${path}${parms}`, options) - .then(async (res) => { - if (res.status === 200){ - let json = await res.json() - callback(json, undefined) - return json - }else{ - let error = validateTypes.isStringWithValue(res.statusText) ? res.statusText : false - callback(undefined, error) - return error - } - }) - .catch(err => { - return callback(undefined, err.toString()) - }) + let options = {}; + if (method === "POST") { + let headers = { "Content-Type": "application/json" }; + options.method = method; + options.headers = headers; + options.body = data; } - createParms(parms){ - if (Object.keys(parms).length === 0) return '' - let parmString = '?' - Object.keys(parms).forEach(key => { - parmString = `${parmString}${key}=${parms[key]}&` - }); - return parmString.slice(0, -1); - } - - async getContractInfo(contractName){ - const returnInfo = (res) => { - try{ - if (res.name) return res - } catch (e){} - return null; + return fetch(`${overrideURL ? overrideURL : this.url}${path}${parms}`, options) + .then(async (res) => { + if (res.status === 200) { + let json = await res.json(); + callback(json, undefined); + return json; + } else { + let error = validateTypes.isStringWithValue(res.statusText) ? res.statusText : false; + callback(undefined, error); + return error; } - let path = `/contracts/${contractName}` - return this.send('GET', path, {}, undefined, (res, err) => returnInfo(res)) - .then(res => returnInfo(res)) - } - - async getVariable(contract, variable, key = ''){ - let parms = {}; - if (validateTypes.isStringWithValue(key)) parms.key = key; - - let path = `/contracts/${contract}/${variable}/` - - const returnValue = (res) => { - try{ - if (res.value) return res.value - } catch (e){} - return null; + }) + .catch((err) => { + return callback(undefined, err.toString()); + }); + } + + createParms(parms) { + if (Object.keys(parms).length === 0) return ""; + let parmString = "?"; + Object.keys(parms).forEach((key) => { + parmString = `${parmString}${key}=${parms[key]}&`; + }); + return parmString.slice(0, -1); + } + + async getContractInfo(contractName) { + const returnInfo = (res) => { + try { + if (res.name) return res; + } catch (e) {} + return null; + }; + let path = `/contracts/${contractName}`; + return this.send("GET", path, {}, undefined, (res, err) => returnInfo(res)).then((res) => + returnInfo(res) + ); + } + + async getVariable(contract, variable, key = "") { + let parms = {}; + if (validateTypes.isStringWithValue(key)) parms.key = key; + + let path = `/contracts/${contract}/${variable}/`; + + const returnValue = (res) => { + try { + if (res.value) return res.value; + } catch (e) {} + return null; + }; + return this.send("GET", path, { parms }, undefined, (res, err) => returnValue(res)).then( + (res) => returnValue(res) + ); + } + + async getContractMethods(contract) { + const getMethods = (res) => { + try { + if (res.methods) return res.methods; + } catch (e) {} + return []; + }; + let path = `/contracts/${contract}/methods`; + return this.send("GET", path, {}, undefined, (res, err) => getMethods(res)).then((res) => + getMethods(res) + ); + } + + async getContractVariables(contract) { + const getVariables = (res) => { + try { + if (res.variables) return res; + } catch (e) {} + return {}; + }; + let path = `/contracts/${contract}/variables`; + return this.send("GET", path, {}, undefined, (res, err) => getVariables(res)).then((res) => + getVariables(res) + ); + } + + async pingServer() { + const getStatus = (res) => { + try { + if (res.status) return true; + } catch (e) {} + return false; + }; + let response = await this.send("GET", "/ping", {}, undefined, (res, err) => getStatus(res)); + return getStatus(response); + } + + async getCurrencyBalance(vk) { + let balanceRes = await this.getVariable("currency", "balances", vk); + if (!balanceRes) return Encoder("bigNumber", 0); + if (balanceRes.__fixed__) return Encoder("bigNumber", balanceRes.__fixed__); + return Encoder("bigNumber", balanceRes.toString()); + } + + async contractExists(contractName) { + const exists = (res) => { + try { + if (res.name) return true; + } catch (e) {} + return false; + }; + let path = `/contracts/${contractName}`; + return this.send("GET", path, {}, undefined, (res, err) => exists(res)).then((res) => + exists(res) + ); + } + + async sendTransaction(data, url = undefined, callback) { + return this.send("POST", "/", JSON.stringify(data), url, (res, err) => { + if (err) { + if (callback) { + callback(undefined, err); + return; + } else return err; + } + if (callback) { + callback(res, undefined); + return; + } + return res; + }); + } + + async getNonce(sender, callback) { + if (!validateTypes.isStringHex(sender)) return `${sender} is not a hex string.`; + let path = `/nonce/${sender}`; + let url = this.host; + return this.send("GET", path, {}, url, (res, err) => { + if (err) { + if (callback) { + callback(undefined, `Unable to get nonce for ${sender} on network ${url}`); + return; } - return this.send('GET', path, {parms}, undefined, (res, err) => returnValue(res)) - .then(res => returnValue(res)) - } - - async getContractMethods(contract){ - const getMethods = (res) => { - try{ - if (res.methods) return res.methods - } catch (e){} - return []; - } - let path = `/contracts/${contract}/methods` - return this.send('GET', path, {}, undefined, (res, err) => getMethods(res)) - .then(res => getMethods(res)) - } - - async getContractVariables(contract){ - const getVariables = (res) => { - try{ - if (res.variables) return res - } catch (e){} - return {}; - } - let path = `/contracts/${contract}/variables` - return this.send('GET', path, {}, undefined, (res, err) => getVariables(res)) - .then(res => getVariables(res)) - } - - async pingServer(){ - const getStatus = (res) => { - try { - if (res.status) return true; - } catch (e) {} - return false - } - let response = await this.send('GET', '/ping', {}, undefined, (res, err) => getStatus(res)) - return getStatus(response) - - } - - async getCurrencyBalance(vk){ - let balanceRes = await this.getVariable('currency', 'balances', vk); - if (!balanceRes) return Encoder('bigNumber', 0); - if (balanceRes.__fixed__) return Encoder('bigNumber', balanceRes.__fixed__) - return Encoder('bigNumber', balanceRes.toString()); - } - - async contractExists(contractName){ - const exists = (res) => { - try { - if (res.name) return true; - } catch (e) {} - return false - } - let path = `/contracts/${contractName}` - return this.send('GET', path, {}, undefined, (res, err) => exists(res)) - .then(res => exists(res)) - } - - async sendTransaction(data, url = undefined, callback){ - return this.send('POST', '/', JSON.stringify(data), url, (res, err) => { - if (err){ - if (callback) { - callback(undefined, err); - return; - } - else return err - } - if (callback) { - callback(res, undefined); - return - } - return res; - }) - } - - async getNonce(sender, callback){ - if (!validateTypes.isStringHex(sender)) return `${sender} is not a hex string.` - let path = `/nonce/${sender}` - let url = this.host - return this.send('GET', path, {}, url, (res, err) => { - if (err){ - if (callback) { - callback(undefined, `Unable to get nonce for ${sender} on network ${url}`) - return - } - return `Unable to get nonce for ${sender} on network ${url}` - } - res.masternode = url - if (callback) { - callback(res, undefined) - return - } - else return res; - }) - } - - async checkTransaction(hash, callback){ - const parms = {hash}; - return this.send('GET', '/tx', {parms}, undefined, (res, err) => { - if (err){ - if (callback) { - callback(undefined, err); - return; - } - else return err - } - if (callback) { - callback(res, undefined); - return - } - return res; - }) - } -} \ No newline at end of file + return `Unable to get nonce for ${sender} on network ${url}`; + } + res.masternode = url; + if (callback) { + callback(res, undefined); + return; + } else return res; + }); + } + + checkTransaction(hash, callback) { + const parms = { hash }; + return this.send("GET", "/tx", { parms }, undefined, (res, err) => { + if (err) { + if (callback) { + callback(undefined, err); + return; + } else return err; + } + if (callback) { + callback(res, undefined); + return; + } + return res; + }); + } +} diff --git a/src/js/network.js b/src/js/network.js index e5744af..949848f 100644 --- a/src/js/network.js +++ b/src/js/network.js @@ -1,63 +1,77 @@ -import { EventEmitter } from './eventEmitter' -import validators from 'types-validate-assert' +import { EventEmitter } from "./eventEmitter"; +import validators from "types-validate-assert"; const { validateTypes } = validators; -import { LamdenMasterNode_API } from './masternode-api' +import { LamdenMasterNode_API } from "./masternode-api"; export class Network { - // Constructor needs an Object with the following information to build Class. - // - // networkInfo: { - // hosts: list of masternode hostname/ip urls, - // type: "testnet", "mainnet" or "custom" - // }, - constructor(networkInfoObj){ - //Reject undefined or missing info - if (!validateTypes.isObjectWithKeys(networkInfoObj)) throw new Error(`Expected Network Info Object and got Type: ${typeof networkInfoObj}`) - if (!validateTypes.isArrayWithValues(networkInfoObj.hosts)) throw new Error(`HOSTS Required (Type: Array)`) + // Constructor needs an Object with the following information to build Class. + // + // networkInfo: { + // hosts: list of masternode hostname/ip urls, + // type: "testnet", "mainnet" or "custom" + // }, + constructor(networkInfoObj) { + //Reject undefined or missing info + if (!validateTypes.isObjectWithKeys(networkInfoObj)) + throw new Error(`Expected Network Info Object and got Type: ${typeof networkInfoObj}`); + if (!validateTypes.isArrayWithValues(networkInfoObj.hosts)) + throw new Error(`HOSTS Required (Type: Array)`); - this.type = validateTypes.isStringWithValue(networkInfoObj.type) ? networkInfoObj.type.toLowerCase() : "custom"; - this.events = new EventEmitter() - this.hosts = this.validateHosts(networkInfoObj.hosts); - this.currencySymbol = validateTypes.isStringWithValue(networkInfoObj.currencySymbol) ? networkInfoObj.currencySymbol : 'TAU' - this.name = validateTypes.isStringWithValue(networkInfoObj.name) ? networkInfoObj.name : 'lamden network'; - this.lamden = validateTypes.isBoolean(networkInfoObj.lamden) ? networkInfoObj.lamden : false; - this.blockExplorer = validateTypes.isStringWithValue(networkInfoObj.blockExplorer) ? networkInfoObj.blockExplorer : undefined; - - this.online = false; - try{ - this.API = new LamdenMasterNode_API(networkInfoObj) - } catch (e) { - throw new Error(e) - } - } - //This will throw an error if the protocol wasn't included in the host string - vaidateProtocol(host){ - let protocols = ['https://', 'http://'] - if (protocols.map(protocol => host.includes(protocol)).includes(true)) return host - throw new Error('Host String must include http:// or https://') - } - validateHosts(hosts){ - return hosts.map(host => this.vaidateProtocol(host.toLowerCase())) - } - //Check if the network is online - //Emits boolean as 'online' event - //Also returns status as well as passes status to a callback - async ping(callback = undefined){ - this.online = await this.API.pingServer() - this.events.emit('online', this.online); - if (validateTypes.isFunction(callback)) callback(this.online) - return this.online - } - get host() {return this.hosts[Math.floor(Math.random() * this.hosts.length)]} - get url() {return this.host} - getNetworkInfo(){ - return { - name: this.name, - lamden: this.lamden, - type: this.type, - hosts: this.hosts, - url: this.url, - online: this.online, - } + this.type = validateTypes.isStringWithValue(networkInfoObj.type) + ? networkInfoObj.type.toLowerCase() + : "custom"; + this.events = new EventEmitter(); + this.hosts = this.validateHosts(networkInfoObj.hosts); + this.currencySymbol = validateTypes.isStringWithValue(networkInfoObj.currencySymbol) + ? networkInfoObj.currencySymbol + : "TAU"; + this.name = validateTypes.isStringWithValue(networkInfoObj.name) + ? networkInfoObj.name + : "lamden network"; + this.lamden = validateTypes.isBoolean(networkInfoObj.lamden) ? networkInfoObj.lamden : false; + this.blockExplorer = validateTypes.isStringWithValue(networkInfoObj.blockExplorer) + ? networkInfoObj.blockExplorer + : undefined; + + this.online = false; + try { + this.API = new LamdenMasterNode_API(networkInfoObj); + } catch (e) { + throw new Error(e); } -} \ No newline at end of file + } + //This will throw an error if the protocol wasn't included in the host string + vaidateProtocol(host) { + let protocols = ["https://", "http://"]; + if (protocols.map((protocol) => host.includes(protocol)).includes(true)) return host; + throw new Error("Host String must include http:// or https://"); + } + validateHosts(hosts) { + return hosts.map((host) => this.vaidateProtocol(host.toLowerCase())); + } + //Check if the network is online + //Emits boolean as 'online' event + //Also returns status as well as passes status to a callback + async ping(callback = undefined) { + this.online = await this.API.pingServer(); + this.events.emit("online", this.online); + if (validateTypes.isFunction(callback)) callback(this.online); + return this.online; + } + get host() { + return this.hosts[Math.floor(Math.random() * this.hosts.length)]; + } + get url() { + return this.host; + } + getNetworkInfo() { + return { + name: this.name, + lamden: this.lamden, + type: this.type, + hosts: this.hosts, + url: this.url, + online: this.online, + }; + } +} diff --git a/src/js/transactionBuilder.js b/src/js/transactionBuilder.js index 9154761..1a1d53d 100644 --- a/src/js/transactionBuilder.js +++ b/src/js/transactionBuilder.js @@ -1,338 +1,369 @@ -import validators from 'types-validate-assert' +import validators from "types-validate-assert"; const { validateTypes } = validators; -import * as wallet from './wallet' -import { Network } from './network' +import * as wallet from "./wallet"; +import { Network } from "./network"; export class TransactionBuilder extends Network { - // Constructor needs an Object with the following information to build Class. - // - // arg[0] (networkInfo): { //Can also accpet a Lamden "Network Class" - // host: masternode webserver hostname/ip, - // type: "testnet", "mainnet" or "mockchain" - // } - // arg[1] (txInfo): { - // uid: [Optional] unique ID for tracking purposes, - // senderVk: public key of the transaction sender, - // contractName: name of lamden smart contract, - // methodName: name of method to call in contractName, - // kwargs: key/values of args to pass to methodName - // example: kwargs.to = "270add00fc708791c97aeb5255107c770434bd2ab71c2e103fbee75e202aa15e" - // kwargs.amount = 1000 - // stampLimit: the max amount of stamps the tx should use. tx could use less. if tx needs more the tx will fail. - // nonce: [Optional] send() will attempt to retrieve this info automatically - // processor [Optional] send() will attempt to retrieve this info automatically - // } - // arg[2] (txData): [Optional] state hydrating data - constructor(networkInfo, txInfo, txData) { - if (validateTypes.isSpecificClass(networkInfo, 'Network')) - super(networkInfo.getNetworkInfo()) - else super(networkInfo) + // Constructor needs an Object with the following information to build Class. + // + // arg[0] (networkInfo): { //Can also accpet a Lamden "Network Class" + // host: masternode webserver hostname/ip, + // type: "testnet", "mainnet" or "mockchain" + // } + // arg[1] (txInfo): { + // uid: [Optional] unique ID for tracking purposes, + // senderVk: public key of the transaction sender, + // contractName: name of lamden smart contract, + // methodName: name of method to call in contractName, + // kwargs: key/values of args to pass to methodName + // example: kwargs.to = "270add00fc708791c97aeb5255107c770434bd2ab71c2e103fbee75e202aa15e" + // kwargs.amount = 1000 + // stampLimit: the max amount of stamps the tx should use. tx could use less. if tx needs more the tx will fail. + // nonce: [Optional] send() will attempt to retrieve this info automatically + // processor [Optional] send() will attempt to retrieve this info automatically + // } + // arg[2] (txData): [Optional] state hydrating data + constructor(networkInfo, txInfo, txData) { + if (validateTypes.isSpecificClass(networkInfo, "Network")) super(networkInfo.getNetworkInfo()); + else super(networkInfo); - //Validate arguments - if(!validateTypes.isObjectWithKeys(txInfo)) throw new Error(`txInfo object not found`) - if(!validateTypes.isStringHex(txInfo.senderVk)) throw new Error(`Sender Public Key Required (Type: Hex String)`) - if(!validateTypes.isStringWithValue(txInfo.contractName)) throw new Error(`Contract Name Required (Type: String)`) - if(!validateTypes.isStringWithValue(txInfo.methodName)) throw new Error(`Method Required (Type: String)`) - if(!validateTypes.isInteger(txInfo.stampLimit)) throw new Error(`Stamps Limit Required (Type: Integer)`) + //Validate arguments + if (!validateTypes.isObjectWithKeys(txInfo)) throw new Error(`txInfo object not found`); + if (!validateTypes.isStringHex(txInfo.senderVk)) + throw new Error(`Sender Public Key Required (Type: Hex String)`); + if (!validateTypes.isStringWithValue(txInfo.contractName)) + throw new Error(`Contract Name Required (Type: String)`); + if (!validateTypes.isStringWithValue(txInfo.methodName)) + throw new Error(`Method Required (Type: String)`); + if (!validateTypes.isInteger(txInfo.stampLimit)) + throw new Error(`Stamps Limit Required (Type: Integer)`); - //Store variables in self for reference - this.uid = validateTypes.isStringWithValue(txInfo.uid) ? txInfo.uid : undefined; - this.sender = txInfo.senderVk; - this.contract = txInfo.contractName; - this.method = txInfo.methodName; - this.kwargs = {}; - if(validateTypes.isObject(txInfo.kwargs)) this.kwargs = txInfo.kwargs; - this.stampLimit = txInfo.stampLimit; + //Store variables in self for reference + this.uid = validateTypes.isStringWithValue(txInfo.uid) ? txInfo.uid : undefined; + this.sender = txInfo.senderVk; + this.contract = txInfo.contractName; + this.method = txInfo.methodName; + this.kwargs = {}; + if (validateTypes.isObject(txInfo.kwargs)) this.kwargs = txInfo.kwargs; + this.stampLimit = txInfo.stampLimit; - //validate and set nonce and processor if user provided them - if (typeof txInfo.nonce !== 'undefined'){ - if(!validateTypes.isInteger(txInfo.nonce)) throw new Error(`arg[6] Nonce is required to be an Integer, type ${typeof txInfo.none} was given`) - this.nonce = txInfo.nonce; - } - if (typeof txInfo.processor !== 'undefined'){ - if(!validateTypes.isStringWithValue(txInfo.processor)) throw new Error(`arg[7] Processor is required to be a String, type ${typeof txInfo.processor} was given`) - this.processor = txInfo.processor; - } - - this.signature; - this.transactionSigned = false; - - //Transaction result information - this.nonceResult = {}; - this.txSendResult = {errors:[]}; - this.txBlockResult = {}; - this.txHash; - this.txCheckResult = {}; - this.txCheckAttempts = 0; - this.txCheckLimit = 10; - - //Hydrate other items if passed - if (txData){ - if (txData.uid) this.uid = txData.uid - if (validateTypes.isObjectWithKeys(txData.txSendResult)) this.txSendResult = txData.txSendResult; - if (validateTypes.isObjectWithKeys(txData.nonceResult)){ - this.nonceResult = txData.nonceResult; - if (validateTypes.isInteger(this.nonceResult.nonce)) this.nonce = this.nonceResult.nonce; - if (validateTypes.isStringWithValue(this.nonceResult.processor)) this.processor = this.nonceResult.processor; - } - if (validateTypes.isObjectWithKeys(txData.txSendResult)){ - this.txSendResult = txData.txSendResult; - if (this.txSendResult.hash) this.txHash = this.txSendResult.hash - } - if (validateTypes.isObjectWithKeys(txData.txBlockResult)) this.txBlockResult = txData.txBlockResult; - if (validateTypes.isObjectWithKeys(txData.resultInfo)) this.resultInfo = txData.resultInfo; - } - //Create Capnp messages and transactionMessages - this.makePayload(); - } - makePayload(){ - this.payload = { - contract: this.contract, - function: this.method, - kwargs: this.kwargs, - nonce: this.nonce, - processor: this.processor, - sender: this.sender, - stamps_supplied: this.stampLimit - } - this.sortedPayload = this.sortObject(this.payload) - } - makeTransaction(){ - this.tx = { - metadata: { - signature: this.signature, - timestamp: parseInt(+new Date / 1000), - }, - payload: this.sortedPayload.orderedObj - } + //validate and set nonce and processor if user provided them + if (typeof txInfo.nonce !== "undefined") { + if (!validateTypes.isInteger(txInfo.nonce)) + throw new Error( + `arg[6] Nonce is required to be an Integer, type ${typeof txInfo.none} was given` + ); + this.nonce = txInfo.nonce; } - verifySignature(){ - //Verify the signature is correct - if (!this.transactionSigned) throw new Error('Transaction has not be been signed. Use the sign() method first.') - const stringBuffer = Buffer.from(this.sortedPayload.json) - const stringArray = new Uint8Array(stringBuffer) - return wallet.verify(this.sender, stringArray, this.signature) + if (typeof txInfo.processor !== "undefined") { + if (!validateTypes.isStringWithValue(txInfo.processor)) + throw new Error( + `arg[7] Processor is required to be a String, type ${typeof txInfo.processor} was given` + ); + this.processor = txInfo.processor; } - sign(sk = undefined, userWallet = undefined){ - const stringBuffer = Buffer.from(this.sortedPayload.json) - const stringArray = new Uint8Array(stringBuffer) - if (userWallet) this.signature = userWallet.sign(stringArray) - else this.signature = wallet.sign(sk, stringArray) - this.transactionSigned = true; + + this.signature; + this.transactionSigned = false; + + //Transaction result information + this.nonceResult = {}; + this.txSendResult = { errors: [] }; + this.txBlockResult = {}; + this.txHash; + this.txCheckResult = {}; + this.txCheckAttempts = 0; + this.txCheckLimit = 10; + + //Hydrate other items if passed + if (txData) { + if (txData.uid) this.uid = txData.uid; + if (validateTypes.isObjectWithKeys(txData.txSendResult)) + this.txSendResult = txData.txSendResult; + if (validateTypes.isObjectWithKeys(txData.nonceResult)) { + this.nonceResult = txData.nonceResult; + if (validateTypes.isInteger(this.nonceResult.nonce)) this.nonce = this.nonceResult.nonce; + if (validateTypes.isStringWithValue(this.nonceResult.processor)) + this.processor = this.nonceResult.processor; + } + if (validateTypes.isObjectWithKeys(txData.txSendResult)) { + this.txSendResult = txData.txSendResult; + if (this.txSendResult.hash) this.txHash = this.txSendResult.hash; + } + if (validateTypes.isObjectWithKeys(txData.txBlockResult)) + this.txBlockResult = txData.txBlockResult; + if (validateTypes.isObjectWithKeys(txData.resultInfo)) this.resultInfo = txData.resultInfo; } - sortObject(object){ - const processObj = (obj) => { - const getType = (value) => { - return Object.prototype.toString.call(value) - } - const isArray = (value) => { - if(getType(value) === "[object Array]") return true; - return false; - } - const isObject = (value) => { - if(getType(value) === "[object Object]") return true; - return false; - } - - const sortObjKeys = (unsorted) => { - const sorted = {}; - Object.keys(unsorted).sort().forEach(key => sorted[key] = unsorted[key]); - return sorted - } - - const formatKeys = (unformatted) => { - Object.keys(unformatted).forEach(key => { - if (isArray(unformatted[key])) unformatted[key] = unformatted[key].map(item => { - if (isObject(item)) return formatKeys(item) - return item - }) - if (isObject(unformatted[key])) unformatted[key] = formatKeys(unformatted[key]) - }) - return sortObjKeys(unformatted) - } - - if (!isObject(obj)) throw new TypeError('Not a valid Object') - try{ - obj = JSON.parse(JSON.stringify(obj)) - } catch (e) { - throw new TypeError('Not a valid JSON Object') - } - return formatKeys(obj) - } - const orderedObj = processObj(object) - return { - orderedObj, - json: JSON.stringify(orderedObj) - } + //Create Capnp messages and transactionMessages + this.makePayload(); + } + makePayload() { + this.payload = { + contract: this.contract, + function: this.method, + kwargs: this.kwargs, + nonce: this.nonce, + processor: this.processor, + sender: this.sender, + stamps_supplied: this.stampLimit, + }; + this.sortedPayload = this.sortObject(this.payload); + } + makeTransaction() { + this.tx = { + metadata: { + signature: this.signature, + timestamp: parseInt(+new Date() / 1000), + }, + payload: this.sortedPayload.orderedObj, + }; + } + verifySignature() { + //Verify the signature is correct + if (!this.transactionSigned) + throw new Error( + "Transaction has not be been signed. Use the sign() method first." + ); + const stringBuffer = Buffer.from(this.sortedPayload.json); + const stringArray = new Uint8Array(stringBuffer); + return wallet.verify(this.sender, stringArray, this.signature); + } + sign(sk = undefined, userWallet = undefined) { + const stringBuffer = Buffer.from(this.sortedPayload.json); + const stringArray = new Uint8Array(stringBuffer); + if (userWallet) this.signature = userWallet.sign(stringArray); + else this.signature = wallet.sign(sk, stringArray); + this.transactionSigned = true; + } + sortObject(object) { + const processObj = (obj) => { + const getType = (value) => { + return Object.prototype.toString.call(value); + }; + const isArray = (value) => { + if (getType(value) === "[object Array]") return true; + return false; + }; + const isObject = (value) => { + if (getType(value) === "[object Object]") return true; + return false; + }; + + const sortObjKeys = (unsorted) => { + const sorted = {}; + Object.keys(unsorted) + .sort() + .forEach((key) => (sorted[key] = unsorted[key])); + return sorted; + }; + + const formatKeys = (unformatted) => { + Object.keys(unformatted).forEach((key) => { + if (isArray(unformatted[key])) + unformatted[key] = unformatted[key].map((item) => { + if (isObject(item)) return formatKeys(item); + return item; + }); + if (isObject(unformatted[key])) unformatted[key] = formatKeys(unformatted[key]); + }); + return sortObjKeys(unformatted); + }; + + if (!isObject(obj)) throw new TypeError("Not a valid Object"); + try { + obj = JSON.parse(JSON.stringify(obj)); + } catch (e) { + throw new TypeError("Not a valid JSON Object"); + } + return formatKeys(obj); + }; + const orderedObj = processObj(object); + return { + orderedObj, + json: JSON.stringify(orderedObj), + }; + } + async getNonce(callback = undefined) { + let timestamp = new Date().toUTCString(); + this.nonceResult = await this.API.getNonce(this.sender); + if (typeof this.nonceResult.nonce === "undefined") { + throw new Error(this.nonceResult); } - async getNonce(callback = undefined) { - let timestamp = new Date().toUTCString(); - this.nonceResult = await this.API.getNonce(this.sender) - if (typeof this.nonceResult.nonce === 'undefined'){ - throw new Error(this.nonceResult) - } - this.nonceResult.timestamp = timestamp; - this.nonce = this.nonceResult.nonce; - this.processor = this.nonceResult.processor; - this.nonceMasternode = this.nonceResult.masternode - //Create payload object - this.makePayload() + this.nonceResult.timestamp = timestamp; + this.nonce = this.nonceResult.nonce; + this.processor = this.nonceResult.processor; + this.nonceMasternode = this.nonceResult.masternode; + //Create payload object + this.makePayload(); - if (!callback) return this.nonceResult; - return callback(this.nonceResult) + if (!callback) return this.nonceResult; + return callback(this.nonceResult); + } + async send(sk = undefined, callback = undefined, masternode = undefined) { + //Error if transaction is not signed and no sk provided to the send method to sign it before sending + if (!validateTypes.isStringWithValue(sk) && !this.transactionSigned) { + throw new Error( + `Transation Not Signed: Private key needed or call sign() first` + ); } - async send(sk = undefined, masternode = undefined, callback = undefined) { - //Error if transaction is not signed and no sk provided to the send method to sign it before sending - if (!validateTypes.isStringWithValue(sk) && !this.transactionSigned){ - throw new Error(`Transation Not Signed: Private key needed or call sign() first`); - } - let timestamp = new Date().toUTCString(); + let timestamp = new Date().toUTCString(); - try{ - //If the nonce isn't set attempt to get it - if (isNaN(this.nonce) || !validateTypes.isStringWithValue(this.processor)) await this.getNonce(); - //if the sk is provided then sign the transaction - if (validateTypes.isStringWithValue(sk)) this.sign(sk); - //Serialize transaction - this.makeTransaction(); - //Send transaction to the masternode - let masternodeURL = masternode - if (!masternodeURL && this.nonceMasternode) masternodeURL = this.nonceMasternode - let response = await this.API.sendTransaction(this.tx, masternodeURL) - //Set error if txSendResult doesn't exist - if (!response || validateTypes.isStringWithValue(response)){ - this.txSendResult.errors = [response || "Unknown Transaction Error"] - }else{ - if (response.error) this.txSendResult.errors = [response.error] - else this.txSendResult = response - } - } catch (e){ - this.txSendResult.errors = [e.message] - } - this.txSendResult.timestamp = timestamp - return this.handleMasterNodeResponse(this.txSendResult, callback) + try { + //If the nonce isn't set attempt to get it + if (isNaN(this.nonce) || !validateTypes.isStringWithValue(this.processor)) + await this.getNonce(); + //if the sk is provided then sign the transaction + if (validateTypes.isStringWithValue(sk)) this.sign(sk); + //Serialize transaction + this.makeTransaction(); + //Send transaction to the masternode + let masternodeURL = masternode; + if (!masternodeURL && this.nonceMasternode) masternodeURL = this.nonceMasternode; + let response = await this.API.sendTransaction(this.tx, masternodeURL); + //Set error if txSendResult doesn't exist + if (!response || validateTypes.isStringWithValue(response)) { + this.txSendResult.errors = [response || "Unknown Transaction Error"]; + } else { + if (response.error) this.txSendResult.errors = [response.error]; + else this.txSendResult = response; + } + } catch (e) { + this.txSendResult.errors = [e.message]; } - checkForTransactionResult(callback = undefined){ - return new Promise((resolve) => { - let timerId = setTimeout(async function checkTx() { - this.txCheckAttempts = this.txCheckAttempts + 1; - let res = await this.API.checkTransaction(this.txHash) - let checkAgain = false; - let timestamp = new Date().toUTCString(); - if (typeof res === 'string' || !res) { - if (this.txCheckAttempts < this.txCheckLimit){ - checkAgain = true - }else{ - this.txCheckResult.errors = [ - `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, - res - ] - } - }else{ - if (res.error){ - if (res.error === 'Transaction not found.'){ - if (this.txCheckAttempts < this.txCheckLimit){ - checkAgain = true - }else{ - this.txCheckResult.errors = [res.error, `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`] - } - }else{ - this.txCheckResult.errors = [res.error] - } - }else{ - this.txCheckResult = res; - } - } - if (checkAgain) timerId = setTimeout(checkTx.bind(this), 1000); - else{ - if (validateTypes.isNumber(this.txCheckResult.status)){ - if (this.txCheckResult.status > 0){ - if (!validateTypes.isArray(this.txCheckResult.errors)) this.txCheckResult.errors = [] - this.txCheckResult.errors.push('This transaction returned a non-zero status code') - } - } - this.txCheckResult.timestamp = timestamp - clearTimeout(timerId); - resolve(this.handleMasterNodeResponse(this.txCheckResult, callback)) + this.txSendResult.timestamp = timestamp; + return this.handleMasterNodeResponse(this.txSendResult, callback); + } + checkForTransactionResult(callback = undefined) { + return new Promise((resolve) => { + let timerId = setTimeout( + async function checkTx() { + this.txCheckAttempts = this.txCheckAttempts + 1; + let res = await this.API.checkTransaction(this.txHash); + let checkAgain = false; + let timestamp = new Date().toUTCString(); + if (typeof res === "string" || !res) { + if (this.txCheckAttempts < this.txCheckLimit) { + checkAgain = true; + } else { + this.txCheckResult.errors = [ + `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, + res, + ]; + } + } else { + if (res.error) { + if (res.error === "Transaction not found.") { + if (this.txCheckAttempts < this.txCheckLimit) { + checkAgain = true; + } else { + this.txCheckResult.errors = [ + res.error, + `Retry Attmpts ${this.txCheckAttempts} hit while checking for Tx Result.`, + ]; } - }.bind(this), 1000); - }) - } - handleMasterNodeResponse(result, callback = undefined){ - //Check to see if this is a successful transacation submission - if (validateTypes.isStringWithValue(result.hash) && validateTypes.isStringWithValue(result.success)){ - this.txHash = result.hash; - this.setPendingBlockInfo(); - }else{ - this.setBlockResultInfo(result) - this.txBlockResult = result; - } - this.events.emit('response', result, this.resultInfo.subtitle); - if (validateTypes.isFunction(callback)) callback(result) - return result - } - setPendingBlockInfo(){ - this.resultInfo = { - title: 'Transaction Pending', - subtitle: 'Your transaction was submitted and is being processed', - message: `Tx Hash: ${this.txHash}`, - type: 'success', - } - return this.resultInfo; - } - setBlockResultInfo(result){ - let erroredTx = false; - let errorText = `returned an error and ` - let statusCode = validateTypes.isNumber(result.status) ? result.status : undefined - let stamps = (result.stampsUsed || result.stamps_used) || 0; - let message = ''; - if(validateTypes.isArrayWithValues(result.errors)){ - erroredTx = true; - message = `This transaction returned ${result.errors.length} errors.`; - if (result.result){ - if (result.result.includes('AssertionError')) result.errors.push(result.result) + } else { + this.txCheckResult.errors = [res.error]; + } + } else { + this.txCheckResult = res; } - } - if (statusCode && erroredTx) errorText = `returned status code ${statusCode} and ` - - this.resultInfo = { - title: `Transaction ${erroredTx ? 'Failed' : 'Successful'}`, - subtitle: `Your transaction ${erroredTx ? `${errorText} ` : ''}used ${stamps} stamps`, - message, - type: `${erroredTx ? 'error' : 'success'}`, - errorInfo: erroredTx ? result.errors : undefined, - returnResult: result.result || "", - stampsUsed: stamps, - statusCode - }; - return this.resultInfo; - } - getResultInfo(){ - return this.resultInfo; - } - getTxInfo(){ - return { - senderVk: this.sender, - contractName: this.contract, - methodName: this.method, - kwargs: this.kwargs, - stampLimit: this.stampLimit - } + } + if (checkAgain) timerId = setTimeout(checkTx.bind(this), 1000); + else { + if (validateTypes.isNumber(this.txCheckResult.status)) { + if (this.txCheckResult.status > 0) { + if (!validateTypes.isArray(this.txCheckResult.errors)) + this.txCheckResult.errors = []; + this.txCheckResult.errors.push("This transaction returned a non-zero status code"); + } + } + this.txCheckResult.timestamp = timestamp; + clearTimeout(timerId); + resolve(this.handleMasterNodeResponse(this.txCheckResult, callback)); + } + }.bind(this), + 1000 + ); + }); + } + handleMasterNodeResponse(result, callback = undefined) { + //Check to see if this is a successful transacation submission + if ( + validateTypes.isStringWithValue(result.hash) && + validateTypes.isStringWithValue(result.success) + ) { + this.txHash = result.hash; + this.setPendingBlockInfo(); + } else { + this.setBlockResultInfo(result); + this.txBlockResult = result; } - getAllInfo(){ - return { - uid: this.uid, - txHash: this.txHash, - signed: this.transactionSigned, - tx: this.tx, - signature: this.signature, - networkInfo: this.getNetworkInfo(), - txInfo: this.getTxInfo(), - txSendResult: this.txSendResult, - txBlockResult: this.txBlockResult, - resultInfo: this.getResultInfo(), - nonceResult: this.nonceResult - } + this.events.emit("response", result, this.resultInfo.subtitle); + if (validateTypes.isFunction(callback)) callback(result); + return result; + } + setPendingBlockInfo() { + this.resultInfo = { + title: "Transaction Pending", + subtitle: "Your transaction was submitted and is being processed", + message: `Tx Hash: ${this.txHash}`, + type: "success", + }; + return this.resultInfo; + } + setBlockResultInfo(result) { + let erroredTx = false; + let errorText = `returned an error and `; + let statusCode = validateTypes.isNumber(result.status) ? result.status : undefined; + let stamps = result.stampsUsed || result.stamps_used || 0; + let message = ""; + if (validateTypes.isArrayWithValues(result.errors)) { + erroredTx = true; + message = `This transaction returned ${result.errors.length} errors.`; + if (result.result) { + if (result.result.includes("AssertionError")) result.errors.push(result.result); + } } + if (statusCode && erroredTx) errorText = `returned status code ${statusCode} and `; + + this.resultInfo = { + title: `Transaction ${erroredTx ? "Failed" : "Successful"}`, + subtitle: `Your transaction ${erroredTx ? `${errorText} ` : ""}used ${stamps} stamps`, + message, + type: `${erroredTx ? "error" : "success"}`, + errorInfo: erroredTx ? result.errors : undefined, + returnResult: result.result || "", + stampsUsed: stamps, + statusCode, + }; + return this.resultInfo; + } + getResultInfo() { + return this.resultInfo; + } + getTxInfo() { + return { + senderVk: this.sender, + contractName: this.contract, + methodName: this.method, + kwargs: this.kwargs, + stampLimit: this.stampLimit, + }; + } + getAllInfo() { + return { + uid: this.uid, + txHash: this.txHash, + signed: this.transactionSigned, + tx: this.tx, + signature: this.signature, + networkInfo: this.getNetworkInfo(), + txInfo: this.getTxInfo(), + txSendResult: this.txSendResult, + txBlockResult: this.txBlockResult, + resultInfo: this.getResultInfo(), + nonceResult: this.nonceResult, + }; + } } diff --git a/src/js/wallet.js b/src/js/wallet.js index 7a39c00..7dbe6ab 100644 --- a/src/js/wallet.js +++ b/src/js/wallet.js @@ -1,42 +1,41 @@ - -import * as helpers from './helpers'; -const nacl = require('tweetnacl') -const bip39 = require('bip39') -const bip32 = require('ed25519-hd-key') +import * as helpers from "./helpers"; +import nacl from "tweetnacl"; +import * as bip39 from "bip39"; +import bip32 from "ed25519-hd-key"; /** - * Create a wallet object for signing and verifying messages - * - * @param {Object} [args={}] Args Object - * @param {string} [args.sk=undefined] A 32 character long hex representation of a signing key (private key) to create wallet from - * @param {Uint8Array(length: 32)} [args.seed=null] A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be avoided by everyday users - * @param {boolean} [args.keepPrivate=false] No direct access to the sk. Will still allow the wallet to sign messages - * @return {Object} Wallet Object with sign and verify methods + * Create a wallet object for signing and verifying messages + * + * @param {Object} [args={}] Args Object + * @param {string} [args.sk=undefined] A 32 character long hex representation of a signing key (private key) to create wallet from + * @param {Uint8Array(length: 32)} [args.seed=null] A Uint8Array with a length of 32 to seed the keyPair with. This is advanced behavior and should be avoided by everyday users + * @param {boolean} [args.keepPrivate=false] No direct access to the sk. Will still allow the wallet to sign messages + * @return {Object} Wallet Object with sign and verify methods */ export let create_wallet = (args = {}) => { - let { sk = undefined, keepPrivate = false, seed = null } = args + let { sk = undefined, keepPrivate = false, seed = null } = args; - let vk; + let vk; - if (sk) { - vk = get_vk(sk) - }else{ - let keyPair = new_wallet(seed) - vk = keyPair.vk - sk = keyPair.sk - } + if (sk) { + vk = get_vk(sk); + } else { + let keyPair = new_wallet(seed); + vk = keyPair.vk; + sk = keyPair.sk; + } - const wallet = () => { - return { - sign: (msg) => sign(sk, msg), - verify: (msg, sig) => verify(vk, msg, sig), - vk, - sk: !keepPrivate ? sk : undefined - } - } + const wallet = () => { + return { + sign: (msg) => sign(sk, msg), + verify: (msg, sig) => verify(vk, msg, sig), + vk, + sk: !keepPrivate ? sk : undefined, + }; + }; - return wallet() -} + return wallet(); +}; /** * @param Uint8Array(length: 32) seed @@ -48,23 +47,22 @@ export let create_wallet = (args = {}) => { * vk: Verify Key (VK) represents a 32 byte verify key */ export function generate_keys(seed = null) { - var kp = null; - if (seed == null) { - kp = nacl.sign.keyPair(); - } - else { - kp = nacl.sign.keyPair.fromSeed(seed); - } - // In the JS implementation of the NaCL library the sk is the first 32 bytes of the secretKey - // and the vk is the last 32 bytes of the secretKey as well as the publicKey - // { - // 'publicKey': , - // 'secretKey': - // } - return { - sk: new Uint8Array(kp['secretKey'].slice(0, 32)), - vk: new Uint8Array(kp['secretKey'].slice(32, 64)) - }; + var kp = null; + if (seed == null) { + kp = nacl.sign.keyPair(); + } else { + kp = nacl.sign.keyPair.fromSeed(seed); + } + // In the JS implementation of the NaCL library the sk is the first 32 bytes of the secretKey + // and the vk is the last 32 bytes of the secretKey as well as the publicKey + // { + // 'publicKey': , + // 'secretKey': + // } + return { + sk: new Uint8Array(kp["secretKey"].slice(0, 32)), + vk: new Uint8Array(kp["secretKey"].slice(32, 64)), + }; } /** * @param String sk @@ -74,9 +72,9 @@ export function generate_keys(seed = null) { * vk: A 64 character long hex representation of a verify key (public key) */ export function get_vk(sk) { - var kp = format_to_keys(sk); - var kpf = keys_to_format(kp); - return kpf.vk; + var kp = format_to_keys(sk); + var kpf = keys_to_format(kp); + return kpf.vk; } /** * @param String sk @@ -87,9 +85,9 @@ export function get_vk(sk) { * vk: Verify Key (VK) represents a 32 byte verify key */ export function format_to_keys(sk) { - var skf = helpers.hex2buf(sk); - var kp = generate_keys(skf); - return kp; + var skf = helpers.hex2buf(sk); + var kp = generate_keys(skf); + return kp; } /** * @param Object kp @@ -102,10 +100,10 @@ export function format_to_keys(sk) { * vk: Verify Key (VK) represented as a 64 character hex string */ export function keys_to_format(kp) { - return { - vk: helpers.buf2hex(kp.vk), - sk: helpers.buf2hex(kp.sk) - }; + return { + vk: helpers.buf2hex(kp.vk), + sk: helpers.buf2hex(kp.sk), + }; } /** * @param Uint8Array(length: 32) seed @@ -117,62 +115,68 @@ export function keys_to_format(kp) { * vk: Verify Key (VK) represented as a 64 character hex string */ export function new_wallet(seed = null) { - const keys = generate_keys(seed); - return keys_to_format(keys); + const keys = generate_keys(seed); + return keys_to_format(keys); } /** * - * @param mnemonic 24 word seed phrase + * @param seed Bip39 seed phrase (128 characters in hex) * @param derivationIndex bip32 derivation key index * @returns {{derivationIndex: number, vk: string, sk: string, mnemonic: string}} * derivationIndex: bip32 derivation key index * vk: Verify Key (VK) represented as a 64 character hex string * sk: Signing Key (SK) represented as a 64 character hex string - * mnemonic: 24 word seed phrase - + * seed: Bip39 seed phrase (128 characters in hex) + * mnemonic: Bip39 24 words mnemonic */ -function generate_keys_bip39(mnemonic = undefined, derivationIndex = 0) { +function generate_keys_bip39(seed = undefined, derivationIndex = 0) { + let finalSeed; let finalMnemonic; - if (mnemonic !== undefined){ - finalMnemonic = mnemonic; + if (seed !== undefined){ + finalSeed = seed; }else { finalMnemonic = bip39.generateMnemonic(256) + finalSeed = bip39.mnemonicToSeedSync(finalMnemonic).toString('hex'); } - const seed = bip39.mnemonicToSeedSync(finalMnemonic).toString('hex'); - const derivationPath = "m/44'/789'/" + derivationIndex + "'/0'/0'"; - const { key, chainCode } = bip32.derivePath(derivationPath, seed, 0x80000000); + const { key, chainCode } = bip32.derivePath(derivationPath, finalSeed, 0x80000000); - const privateKey = key.toString('hex'); - const publicKey = bip32.getPublicKey(key, false).toString('hex'); + const privateKey = key.toString("hex"); + const publicKey = bip32.getPublicKey(key, false).toString("hex"); + + if (publicKey !== get_vk(privateKey)) { + throw Error("Bip32 public key does not match with Lamden public key!"); + } + + if (finalMnemonic !== undefined){ - if (publicKey !== get_vk(privateKey)){ - throw Error('Bip32 public key does not match with Lamden public key!') } return { sk: privateKey, vk: publicKey, derivationIndex: derivationIndex, - mnemonic: finalMnemonic + seed: seed !== undefined ? null : finalSeed, + mnemonic: seed !== undefined ? null : finalMnemonic, } } /** - * @param mnemonic 24 word seed phrase + * @param seed Bip39 seed phrase (128 characters in hex) * @param derivationIndex bip32 derivation key index * * @return {{derivationIndex: number, vk: string, sk: string, mnemonic: (string|undefined)}} { sk, vk, derivationIndex, mnemonic } * sk: Signing Key (SK) represented as a 64 character hex string * vk: Verify Key (VK) represented as a 64 character hex string * derivationIndex: Bip32 derivation index - * mnemonic: 24 word seed phrase + * seed: Bip39 seed phrase (128 characters in hex) + * mnemonic: Bip39 24 words mnemonic */ -export function new_wallet_bip39(mnemonic = undefined, derivationIndex = 0) { - return generate_keys_bip39(mnemonic, derivationIndex); +export function new_wallet_bip39(seed = undefined, derivationIndex = 0) { + return generate_keys_bip39(seed, derivationIndex); } /** @@ -185,14 +189,14 @@ export function new_wallet_bip39(mnemonic = undefined, derivationIndex = 0) { * sig: A 128 character long hex string representing the message's signature */ export function sign(sk, msg) { - var kp = format_to_keys(sk); - // This is required due to the secretKey required to sign a transaction - // in the js implementation of NaCL being the combination of the sk and - // vk for some stupid reason. That being said, we still want the sk and - // vk objects to exist in 32-byte string format (same as cilantro's - // python implementation) when presented to the user. - var jsnacl_sk = helpers.concatUint8Arrays(kp.sk, kp.vk); - return helpers.buf2hex(nacl.sign.detached(msg, jsnacl_sk)); + var kp = format_to_keys(sk); + // This is required due to the secretKey required to sign a transaction + // in the js implementation of NaCL being the combination of the sk and + // vk for some stupid reason. That being said, we still want the sk and + // vk objects to exist in 32-byte string format (same as cilantro's + // python implementation) when presented to the user. + var jsnacl_sk = helpers.concatUint8Arrays(kp.sk, kp.vk); + return helpers.buf2hex(nacl.sign.detached(msg, jsnacl_sk)); } /** * @param String vk @@ -206,13 +210,11 @@ export function sign(sk, msg) { * result: true if verify checked out, false if not */ export function verify(vk, msg, sig) { - var vkb = helpers.hex2buf(vk); - var sigb = helpers.hex2buf(sig); - try { - return nacl.sign.detached.verify(msg, sigb, vkb); - } - catch (_a) { - return false; - } + var vkb = helpers.hex2buf(vk); + var sigb = helpers.hex2buf(sig); + try { + return nacl.sign.detached.verify(msg, sigb, vkb); + } catch (_a) { + return false; + } } - diff --git a/test/browsers/encoder-test.js b/test/browsers/encoder-test.js new file mode 100644 index 0000000..29ef924 --- /dev/null +++ b/test/browsers/encoder-test.js @@ -0,0 +1,295 @@ +const { Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + +const dateString = "2020-07-28T19:16:35.059Z"; +const millisecondsDelta = 475200000; + +describe('Browsers Tests: Test Type Encoder', function () { + let driver; + let server; + const app = new Koa(); + const port = 6800; + + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + await driver.sleep(2000) + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("TYPES", () => { + it("Encoder rejects unknown TYPE", async () => { + await driver.executeScript("return Lamden.Encoder('nope', {})").catch(e=>{ + expect(e.toString()).to.contain("Error: nope is not a valid encoder type"); + }) + }); + }); + + context("BigNumber", () => { + it("Encoder can call BigNumber", async () => { + let val = await driver.executeScript("return Lamden.Encoder.BigNumber.sum(1, 2).toString()"); + expect(val).to.be("3"); + }); + }); + + context("Strings", () => { + it("encodes a string from a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('str', 'string')"); + expect(val).to.be("string"); + }); + it("encodes a number as a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('str', 1)"); + expect(val).to.be("1"); + }); + it("encodes a boolean as a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('str', true)"); + expect(val).to.be("true"); + }); + it("encodes a Date as a string", async () => { + let val = await driver.executeScript(`return Lamden.Encoder('str', new Date('${dateString}'))`); + expect(val).to.be("2020-07-28T19:16:35.059Z"); + }); + it("encodes a Dict as a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('str', {})"); + expect(val).to.be("{}"); + }); + it("encodes a List as a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('str', [])"); + expect(val).to.be("[]"); + }); + }); + +context("Integers", () => { + it("encodes a integer from an integer", async () => { + let val = await driver.executeScript("return Lamden.Encoder('int', 1)"); + expect(val).to.be(1); + }); + it("encodes a integer from a float", async () => { + let val = await driver.executeScript("return Lamden.Encoder('int', 1.5)"); + expect(val).to.be(1); + }); + it("encodes a integer from a string", async () => { + let val = await driver.executeScript("return Lamden.Encoder('int', '1.5')"); + expect(val).to.be(1); + }); + it("fails to encode non-integer values", async () => { + await driver.executeScript("return Lamden.Encoder('int', true)").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + }); + }); + context("Floats", () => { + it("encodes a __fixed__ object from an float", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', 1.5)"))).to.be(JSON.stringify({ __fixed__: "1.5" })); + }); + it("encodes a __fixed__ object to integer", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', 1)"))).to.be(JSON.stringify({ __fixed__: "1.0" })); + }); + it("encodes a __fixed__ object with zeros as decimals to an integer", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', 1.0)"))).to.be(JSON.stringify({ __fixed__: "1.0" })); + }); + it("encodes a __fixed__ object from a string", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', '1.5')"))).to.be(JSON.stringify({ __fixed__: "1.5" })); + }); + it("encodes a __fixed__ object from a float and loses percision", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', 0.9999999999999999999999999999999)"))).to.be(JSON.stringify({ __fixed__: "1.0" })); + }); + it("encodes __fixed__ object float from a string and retains precision", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', '0.9999999999999999999999999999999')"))).to.be(JSON.stringify({ __fixed__: "0.999999999999999999999999999999" })); + }); + it("encodes __fixed__ object float from a bigNumber Object and retains precision", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('float', Lamden.Encoder('bigNumber', '0.9999999999999999999999999999999'))"))).to.be(JSON.stringify({ __fixed__: "0.999999999999999999999999999999" })); + }); + it("fails to encode non-float values", async () => { + await driver.executeScript("return Lamden.Encoder('float', true)").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + }); + }); + context("Boolean", async () => { + it("encodes a boolean from a boolean", async () => { + expect(await driver.executeScript("return Lamden.Encoder('bool', true)")).to.be(true); + expect(await driver.executeScript("return Lamden.Encoder('bool', false)")).to.be(false); + }); + it("encodes a boolean from a number", async () => { + expect( await driver.executeScript("return Lamden.Encoder('bool', 1)")).to.be(true); + expect(await driver.executeScript("return Lamden.Encoder('bool', 0)")).to.be(false); + }); + it("encodes a boolean from a string", async () => { + expect(await driver.executeScript("return Lamden.Encoder('bool', 'true')")).to.be(true); + expect(await driver.executeScript("return Lamden.Encoder('bool', 'false')")).to.be(false); + }); + it("fails to encode non-boolean values", async () => { + await driver.executeScript("return Lamden.Encoder('bool', 'nope')").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + await driver.executeScript("return Lamden.Encoder('bool', 2)").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + await driver.executeScript("return Lamden.Encoder('bool', {})").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + }); + }); + context("Dict Object", () => { + it("encodes a dict from an Object", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('dict', {})"))).to.be(JSON.stringify({})); + }); + it("encodes a dict from a string", async () => { + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('dict','{\"vk\":\"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7\"}')"))).to.be( + JSON.stringify({ vk: "833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7" }) + ); + }); + it("encodes datetime and float inside a dict from a string", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder('dict', { datetime: new Date('${dateString}'), float: 1.1 })`))).to.be( + '{"datetime":{"__time__":[2020,6,28,19,16,35,59]},"float":{"__fixed__":"1.1"}}' + ); + }); + it("replaces datetime object with value in dict", async () => { + expect( + JSON.stringify(await driver.executeScript(`return Lamden.Encoder("dict", { DateTime: { datetime: new Date('${dateString}') } })`)) + ).to.be('{"DateTime":{"__time__":[2020,6,28,19,16,35,59]}}'); + }); + it("replaces timedelta object with value in dict", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder("dict", { TimeDelta: { timedelta: 1000 } })`))).to.be( + '{"TimeDelta":{"__delta__":[0,1]}}' + ); + }); + it("fails to encode non-objects", async () => { + expect(() => Encoder("dict", undefined)).to.throwError(); + await driver.executeScript("return Lamden.Encoder('dict', undefined)").catch(e=>{ + expect(e.toString()).to.contain("Error:"); + }) + }); + }); + context("Any Object", () => { + it("Any does not do any encoding", async () => { + expect(await driver.executeScript("return Lamden.Encoder('Any', 'string')")).to.be("string"); + expect(await driver.executeScript("return Lamden.Encoder('Any', 1)")).to.be(1); + expect(await driver.executeScript("return Lamden.Encoder('Any', 1.23456)")).to.be(1.23456); + expect(await driver.executeScript("return Lamden.Encoder('Any', true)")).to.be(true); + expect(await driver.executeScript(`return Lamden.Encoder('Any', new Date('${dateString}').toUTCString())`)).to.be( + new Date(dateString).toUTCString() + ); + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('Any', {})"))).to.be(JSON.stringify({})); + expect(JSON.stringify(await driver.executeScript("return Lamden.Encoder('Any', [])"))).to.be(JSON.stringify([])); + }); + }); + + context("DateTime", () => { + it("Encodes a Date into a value list", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder('datetime.datetime', new Date('${dateString}'))`))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + it("Encodes a Date string into a value list", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder('datetime.datetime', '${dateString}')`))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + it("Encodes milliseconds into a value list", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder('datetime.datetime', new Date('${dateString}').getTime())`))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + }); + + context("TimeDelta", () => { + it("Encodes a Date into days seconds", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder("datetime.timedelta", new Date(${millisecondsDelta}))`))).to.be( + JSON.stringify({ __delta__: [5, 43200] }) + ); + }); + it("Encodes a millisenconds into days seconds", async () => { + expect(JSON.stringify(await driver.executeScript(`return Lamden.Encoder("datetime.timedelta", ${millisecondsDelta})`))).to.be( + JSON.stringify({ __delta__: [5, 43200] }) + ); + }); + }); + + context("Stringify()- Parses object and encodes all values", async () => { + let testObj = { + integer: 1, + float: 1.1, + list: [ + 1, + 1.1, + "this is a string", + true, + [1, 2, 3, 4, 5, 6, 7], + [0, 1234567], + [1.1], + { + fixed: 1.1, + DateTime: { datetime: new Date(dateString) }, + TimeDelta: { "datetime.timedelta": millisecondsDelta }, + }, + ], + str: "this is a string", + bool: true, + "datetime.datetime": new Date(dateString), + "datetime.timedelta": millisecondsDelta, + }; + testObj.dict = JSON.parse(JSON.stringify(testObj)); + let temp = await driver.executeScript(`return Lamden.Encoder('object', ${testObj})`) + let encodedObj = JSON.stringify(temp); + + it("encodes an string", () => { + expect(encodedObj.includes('"str":"this is a string"')).to.be(true); + }); + it("encodes an integer", () => { + expect(encodedObj.includes('"integer":1')).to.be(true); + }); + it("encodes a float", () => { + expect(encodedObj.includes('"float":{"__fixed__":"1.1"}')).to.be(true); + }); + it("encodes an bool", () => { + expect(encodedObj.includes('"bool":true')).to.be(true); + }); + it("encodes a datetime.datetime", () => { + expect(encodedObj.includes('"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]}')).to.be( + true + ); + }); + it("encodes an datetime.timdelta", () => { + expect(encodedObj.includes('"datetime.timedelta":{"__delta__":[5,43200]}')).to.be(true); + }); + it("encodes an list", () => { + expect( + encodedObj.includes( + '"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}]' + ) + ).to.be(true); + }); + it("encodes a dict/object", () => { + expect( + encodedObj.includes( + '"dict":{"integer":1,"float":{"__fixed__":"1.1"},"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}],"str":"this is a string","bool":true,"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]},"datetime.timedelta":{"__delta__":[5,43200]}}' + ) + ).to.be(true); + }); + }); + +}) \ No newline at end of file diff --git a/test/browsers/keystore-test.js b/test/browsers/keystore-test.js new file mode 100644 index 0000000..802d83f --- /dev/null +++ b/test/browsers/keystore-test.js @@ -0,0 +1,378 @@ +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); +const validators = require("types-validate-assert"); +const { validateTypes, assertTypes } = validators; +const Lamden = require('../../dist/cjs/lamden.js') + +// define a plugin for koa to redirect some js resources which will enable the types-valid-assert work in the broswer. +const typeValidAssertMiddleware = async (ctx, next) => { + if (ctx.request.url.indexOf("types-validate-assert") >= 0 && ctx.request.url.indexOf(".js") === -1) { + ctx.redirect(`${ctx.request.url}.js`); + } + await next(); +} + + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + +let KEYSTORE_PASSWORD = "Testing010203"; +const KEYSTORE_HINT = "Testing010203"; + +// Overwritted in "createKeystore() - Can create a keystore" +let KEYSTORE_DATA = { + data: '{"ct":"s6M4AvQvklttEyGq5ebPj/PzAmjNtV6wlS9X8L0RCoZiaqyOz0Y80eZbdf1WRv7gm4Y9aN4vPEoU4oNVVbXoT7QYhuaxMZ+XUyPihcOOnxxmMMGckWD9QOROSgLovvm5yZxp6C2G47dWp7QLkJvubuPgZ+Ws0uexLnkvxXnCikwdZ20yUAFwGN+u3RhQvmgFagCLeuViFXSOtfkDRXmzX4k/7P6cWet8j5rn5gCBbOYHq8rFOxc34ihdhE/8N+x+3MyxGYk2QmwyfzTE9jDEXZwWRlz4GtMXi29ZccRi0z2XEeB7yBl1LTLvngpQM2QnCcX0AQNjHqlPb30bZtQD5shwzgNiRKRon41tKBAH7uvTjw6N39DVIABUkQCusQ1dWWkuvkt79kPjKI/oRF3RH101kXbejFLfDy0eXNUcV3U=","iv":"14e2a23a66fae00bb201f013e9ae1699","s":"5f4b1877b9d4235e"}', + w: "U2FsdGVkX19RU+1vmxcY5wDfbkn1Gq8zOsh9Y4ylvSs=", +}; + +let keyPairs = [Lamden.wallet.new_wallet(), Lamden.wallet.new_wallet()] +let keyList = [ + { + sk: keyPairs[0].sk, + nickname: "key1", + name: "lamden", + network: "lamden", + symbol: "TAU", + }, + { + sk: keyPairs[1].sk, + nickname: "key2", + name: "lamden", + network: "lamden", + symbol: "TAU", + }, +]; + +describe("Browsers Tests: Test Lamden Keystore Class", () => { + let driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(typeValidAssertMiddleware) + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + await driver.sleep(1000) + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + context("keystore construcutor: ", () => { + it("creates an instance with no constructor arguments", async () => { + let res = await driver.executeScript(function(){ + let keystore = new Lamden.Keystore() + return [assertTypes.isSpecificClass(keystore, "Keystore"), keystore.keyList.numOfKeys(), keystore.keyList.getWallets().length] + }); + expect(res[0]).to.be(true); + expect(res[1]).to.be(0); + expect(res[2]).to.be(0); + }); + it("creates an instance by passing a string to the key property", async () => { + let res = await driver.executeScript(function(){ + let keystore = new Lamden.Keystore(arguments[0]) + return [assertTypes.isSpecificClass(keystore, "Keystore"), keystore.keyList.numOfKeys(), keystore.keyList.getWallets().length] + }, { key: keyList[0] }) + expect(res[0]).to.be(true); + expect(res[1]).to.be(1); + expect(res[2]).to.be(1); + }); + it("creates an instance by passing an array to the keys property", async () => { + let res = await driver.executeScript(function(){ + let keystore = new Lamden.Keystore(arguments[0]) + return [assertTypes.isSpecificClass(keystore, "Keystore"), keystore.keyList.numOfKeys(), keystore.keyList.getWallets().length] + }, { keyList }) + expect(res[0]).to.be(true); + expect(res[1]).to.be(2); + expect(res[2]).to.be(2); + }); + it("creates an instance by passing a keystoreData object", async () => { + let res = await driver.executeScript(function(){ + let keystore = new Lamden.Keystore(arguments[0]) + return [assertTypes.isSpecificClass(keystore, "Keystore"), assertTypes.isObjectWithKeys(keystore.encryptedData)] + }, { keystoreData: KEYSTORE_DATA }) + expect(res[0]).to.be(true); + expect(res[1]).to.be(true); + }); + it("creates an instance by passing a keystoreData string", async () => { + let res = await driver.executeScript(function(){ + let keystore = new Lamden.Keystore(arguments[0]) + return [assertTypes.isSpecificClass(keystore, "Keystore"), assertTypes.isObjectWithKeys(keystore.encryptedData)] + }, { keystoreData: JSON.stringify(KEYSTORE_DATA) }) + expect(res[0]).to.be(true); + expect(res[1]).to.be(true); + }); + it('NEGATIVE - Errors on "keyArg" not Array', async () => { + await driver.executeScript(function(){ + new Lamden.Keystore(arguments[0]) + }, { keyList: { key1: "key1" } }).catch((e) => { + expect(e.message).to.contain('Expected type [object Array] but got [object Object]'); + }); + }); + it("NEGATIVE - Errors on if array value is not type string", async () => { + await driver.executeScript(function(){ + new Lamden.Keystore(arguments[0]) + }, { keyList: [keyList[0], 2] }).catch((e) => { + expect(e.message).to.contain('Expected "2" to be [object Object] and have keys'); + });; + }); + }); + context("Adding Keys to the Keystore", () => { + it('addKey() - Can add a single key to the internal "keyList"', async () => { + let res = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore(); + keystore.addKey(keyList[0]); + return keystore.keyList.numOfKeys() + }, keyList) + expect(res).to.be(1); + }); + it("NEGATIVE - addKey() - Errors if value passed is not type string", async () => { + await driver.executeScript(function(){ + let keystore = new Lamden.Keystore(); + keystore.addKey(1); + }).catch(e => { + expect(e.message).to.contain('Expected "1" to be [object Object] and have keys'); + }) + }); + it('addKeys() - Can add to the internal "keyList" via an array of keys', async () => { + let res = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore(); + keystore.addKeys(keyList); + return keystore.keyList.numOfKeys() + }, keyList) + expect(res).to.be(2); + }); + it("addKeys() - Wallets contain metadata", async () => { + let res = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore(); + keystore.addKeys(keyList); + return keystore.wallets + }, keyList) + res.forEach((walletInfo, index) => { + expect(walletInfo.name).to.be(keyList[index].name); + expect(walletInfo.nickname).to.be(keyList[index].nickname); + expect(walletInfo.network).to.be(keyList[index].network); + expect(walletInfo.symbol).to.be(keyList[index].symbol); + }); + }); + it("NEGATIVE - addKeys() - Errors if value passed is not type array", async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore(); + keystore.addKeys({ key1: "key1", key2: "key2" }) + }).catch((e) => { + expect(e.message).to.contain("Expected type [object Array] but got [object Object]"); + }); + }); + }); + context("Deleting Keys from the Keystore", () => { + it("deleteKey() - Can delete a key from the keystore", async () => { + let res = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(0); + return keystore.wallets[0].vk + }, keyList) + expect(res).to.be(keyPairs[1].vk); + }); + it("NEGATIVE - deleteKey() - Errors if argument is not an integer", async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(0.3) + }, keyList).catch(e => { + expect(e.message).to.contain('Expected "0.3" to be an integer but got non-integer value'); + }) + }); + it("NEGATIVE - deleteKey() - Errors if index is out of range, high", async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(2) + }, keyList).catch(e => { + expect(e.message).to.contain('Key index out of range.'); + }) + }); + it("NEGATIVE - deleteKey() - Errors if index is out of range, low", async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(-1) + }, keyList).catch(e => { + expect(e.message).to.contain('Key index out of range.'); + }) + }); + it("NEGATIVE - deleteKey() - Funtion returns no keys in list", async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(0) + },keyList) + + }); + }); + context("Using keystore wallets", () => { + it("keystore.wallets - Deletes keys from the keystore", async () => { + let res = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + return keystore.wallets.length; + }, keyList) + expect(res).to.be(2); + }); + it("getWallet() - Can get a specific wallet", async () => { + let keystoreWallet = await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + return keystore.getWallet(keystore.wallets[0].vk); + }, keyList) + expect(keystoreWallet).to.have.property("sign"); + expect(keystoreWallet).to.have.property("verify"); + expect(keystoreWallet).to.have.property("vk"); + expect(() => assertTypes.isStringHex(keystoreWallet.sk)).throwException(); + }); + }); + context("Clearing a keystore", () => { + it("clearKeys() - Deletes keys from the keystore", async () => { + let res = await driver.executeScript(function(keyList){ + let after, before; + let keystore = new Lamden.Keystore(); + keystore.addKey(keyList[0]); + before = keystore.keyList.numOfKeys(); + keystore.clearKeys(); + after = keystore.keyList.numOfKeys(); + return [before, after]; + }, keyList) + expect(res[0]).to.be(1); + expect(res[1]).to.be(0); + }); + }); + context("Creating a Keystore", () => { + it("createKeystore() - Can create a keystore", async () => { + let res = await driver.executeScript(function(keyList, KEYSTORE_PASSWORD, KEYSTORE_HINT){ + let keystore = new Lamden.Keystore({ keyList }); + let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD, KEYSTORE_HINT); + let keystoreObj = JSON.parse(encryptedKeystore); + return keystoreObj; + }, keyList, KEYSTORE_PASSWORD, KEYSTORE_HINT) + expect(res).to.have.property("data"); + assertTypes.isStringWithValue(res.data); + expect(res).to.have.property("w"); + assertTypes.isStringWithValue(res.w); + }); + it('createKeystore() - Can create a keystore without "hint"', async () => { + let res = await driver.executeScript(function(keyList, KEYSTORE_PASSWORD){ + let keystore = new Lamden.Keystore({ keyList }); + let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD); + let keystoreObj = JSON.parse(encryptedKeystore); + return keystoreObj; + }, keyList , KEYSTORE_PASSWORD) + + expect(res).to.have.property("data"); + assertTypes.isStringWithValue(res.data); + + expect(res).to.have.property("w"); + assertTypes.isString(res.w); + + expect(() => assertTypes.isStringWithValue(res.w)).throwException((e) => { + expect(e.message).to.be('Expected "" to be [object String] and not empty'); + }); + }); + it('NEGATIVE - createKeystore() - Errors if "password" value passed is not type string', async () => { + await driver.executeScript(function(keyList){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.createKeystore(12345); + }, keyList).catch(e => { + expect(e.message).to.contain('Expected "12345" to be [object String] and not empty'); + }) + }); + it('NEGATIVE - createKeystore() - Errors if a non-string value for "hint" is provided', async () => { + await driver.executeScript(function(keyList, KEYSTORE_PASSWORD){ + let keystore = new Lamden.Keystore({ keyList }); + keystore.createKeystore(KEYSTORE_PASSWORD, 12345); + }, keyList, KEYSTORE_PASSWORD).catch(e => { + expect(e.message).to.contain('Expected "12345" to be [object String] and not empty'); + }) + }); + }); + + context("Keystore password hints", () => { + it("getPasswordHint() - Can get the hint from the keystore instance", async () => { + let res = await driver.executeScript(function(KEYSTORE_DATA){ + let keystore = new Lamden.Keystore({ keystoreData: KEYSTORE_DATA }); + let hint = keystore.getPasswordHint(); + return hint; + }, KEYSTORE_DATA) + expect(res).to.be(KEYSTORE_HINT); + }); + it("getPasswordHint() - Can get the hint from a supplied keystore", async () => { + let res = await driver.executeScript(function(KEYSTORE_DATA){ + let keystore = new Lamden.Keystore(); + let hint = keystore.getPasswordHint(KEYSTORE_DATA); + return hint; + }, KEYSTORE_DATA) + expect(res).to.be(KEYSTORE_HINT); + }); + it("getPasswordHint() - Can get the hint from a supplied string keystore", async () => { + let res = await driver.executeScript(function(KEYSTORE_DATA){ + let keystore = new Lamden.Keystore(); + let hint = keystore.getPasswordHint(JSON.stringify(KEYSTORE_DATA)); + return hint; + }, KEYSTORE_DATA) + expect(res).to.be(KEYSTORE_HINT); + }); + }); + context("Decrypting a Keystore", () => { + it("decryptKeystore() - Can decrypte a keystore", async () => { + let res = await driver.executeScript(function(KEYSTORE_DATA, KEYSTORE_PASSWORD){ + let keystore = new Lamden.Keystore({ keystoreData: KEYSTORE_DATA }); + keystore.decryptKeystore(KEYSTORE_PASSWORD); + return [keystore.keyList.numOfKeys(), keystore.version]; + }, KEYSTORE_DATA, KEYSTORE_PASSWORD) + expect(res[0]).to.be(2); + expect(res[1]).to.be("1.0"); + }); + it("decryptKeystore() - Can decrypte a keystore passed as a string", async () => { + let res = await driver.executeScript(function(KEYSTORE_DATA ,KEYSTORE_PASSWORD){ + let keystore = new Lamden.Keystore({ keystoreData: JSON.stringify(KEYSTORE_DATA) }); + keystore.decryptKeystore(KEYSTORE_PASSWORD); + return [keystore.keyList.numOfKeys(), keystore.version]; + }, KEYSTORE_DATA, KEYSTORE_PASSWORD) + expect(res[0]).to.be(2); + expect(res[1]).to.be("1.0"); + }); + it("decryptKeystore() - Can decrypt a provided keystore", async () => { + let res = await driver.executeScript(function(KEYSTORE_PASSWORD, KEYSTORE_DATA){ + let keystore = new Lamden.Keystore(); + keystore.decryptKeystore(KEYSTORE_PASSWORD, KEYSTORE_DATA); + return [keystore.keyList.numOfKeys(), keystore.version]; + }, KEYSTORE_PASSWORD, KEYSTORE_DATA) + expect(res[0]).to.be(2); + expect(res[1]).to.be("1.0"); + }); + it("NEGATIVE - decryptKeystore() - Reports Incorrect Password", async () => { + await driver.executeScript(function(KEYSTORE_DATA){ + let keystore = new Lamden.Keystore(); + keystore.decryptKeystore("Nope", KEYSTORE_DATA); + }, KEYSTORE_DATA).catch((e) => { + expect(e.message).to.contain("Incorrect Keystore Password."); + }); + }); + it("NEGATIVE - decryptKeystore() - Errors if no keystoreData found", async () => { + await driver.executeScript(function(KEYSTORE_PASSWORD){ + let keystore = new Lamden.Keystore(); + keystore.decryptKeystore(KEYSTORE_PASSWORD); + }, KEYSTORE_PASSWORD).catch((e) => { + expect(e.message).to.contain("No keystoreData to decrypt."); + }); + }); + }); +}); diff --git a/test/browsers/masternode_api-test.js b/test/browsers/masternode_api-test.js new file mode 100644 index 0000000..9395883 --- /dev/null +++ b/test/browsers/masternode_api-test.js @@ -0,0 +1,341 @@ +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + +let goodNetwork = { + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], +}; + +let badNetwork = { + type: "testnet", + name: "Bad Network", + hosts: ["http://badnetwork.lamden.io:18080"], +}; + +function copyObject(object) { + return JSON.parse(JSON.stringify(object)); +} + +const balanceCheckWallet = { + float: "960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb", + int: "01930f6472916ae53c9ebbe7d3faf8979c24cac33d68041aa4ab986401bbf7c3", +}; + +describe("Browsers Tests: Test Masternode API returns", () => { + var driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("constructor", () => { + it("can create an instance", async () => { + let api = await driver.executeScript(function (goodNetwork) { + let api = new Lamden.Masternode_API(goodNetwork) + return { + hosts: api.hosts, + url: api.url + } + }, goodNetwork) + expect(api).to.exist; + expect(JSON.stringify(api.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); + expect(api.url).to.be(goodNetwork.hosts[0]); + }); + it("rejects arg not being an object", async () => { + let error; + try { + await driver.executeScript(function () { + new Lamden.Masternode_API("https://testnet.lamden.io:443") + }) + } catch (e) { + error = e; + } + expect(error.message).to.contain("Expected Object and got Type: string"); + }); + it("rejects missing hosts Array", async () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = []; + await driver.executeScript(function (networkInfo) { + new Lamden.Masternode_API(networkInfo) + }, networkInfo) + } catch (e) { + error = e; + } + expect(error.message).to.contain("HOSTS Required (Type: Array)"); + }); + it("rejects no protocol in host string", async () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = ["missing.protocol.com"]; + await driver.executeScript(function (networkInfo) { + new Lamden.Masternode_API(networkInfo) + }, networkInfo) + } catch (e) { + error = e; + } + expect(error.message).to.contain("Host String must include http:// or https://"); + }); + }); + + context("Masternode_API.pingServer()", async () => { + it("returns true if the server is online", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.pingServer(); + callback(response); + }, goodNetwork).then(res => { + expect(res).to.be(true); + }) + }); + it("returns false if provided network is unresponsive", async () => { + await driver.executeAsyncScript(async function (badNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(badNetwork); + let response = await api.pingServer(); + callback(response); + }, badNetwork).then(res => { + expect(res).to.be(false); + }) + }); + }); + + context("Masternode_API.getCurrencyBalance()", () => { + it("returns the float balance for a vk", async () => { + await driver.executeAsyncScript(async function (goodNetwork, balanceCheckWallet) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getCurrencyBalance(balanceCheckWallet.float); + callback(response); + }, goodNetwork, balanceCheckWallet).then(res => { + expect(res).to.above(0); + }) + }); + it("returns the int balance for a vk", async () => { + await driver.executeAsyncScript(async function (goodNetwork, balanceCheckWallet) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getCurrencyBalance(balanceCheckWallet.int); + callback(response); + }, goodNetwork, balanceCheckWallet).then(res => { + expect(res).to.above(0); + }) + }); + it("returns 0 if the vk does not exist yet", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getCurrencyBalance(Lamden.wallet.new_wallet().vk); + callback(response.toNumber()); + }, goodNetwork).then(res => { + expect(res).to.be(0); + }) + }); + it("returns 0 if provided network is unresponsive", async () => { + await driver.executeAsyncScript(async function (badNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(badNetwork); + let response = await api.getCurrencyBalance(); + callback(response.toNumber()); + }, badNetwork).then(res => { + expect(res).to.be(0); + }) + }); + }); + + context("Masternode_API.contractExists()", () => { + it("returns true if a contract exists on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.contractExists("currency"); + callback(response); + }, goodNetwork).then(res => { + expect(res).to.be(true); + }) + + }); + it("returns false if a contract does not exist on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.contractExists(Lamden.wallet.new_wallet().vk); + callback(response); + }, goodNetwork).then(res => { + expect(res).to.be(false); + }) + }); + it("returns false if provided network is unresponsive", async () => { + await driver.executeAsyncScript(async function (badNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(badNetwork); + let response = await api.contractExists("currency"); + callback(response); + }, badNetwork).then(res => { + expect(res).to.be(false); + }) + }); + }); + + context("Masternode_API.getContractMethods()", () => { + it("returns an array if a contract exists on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getContractMethods("currency"); + callback(response); + }, goodNetwork).then(res => { + expect(Array.isArray(res)).to.be(true); + expect(res.length > 0).to.be(true); + }) + }); + it("returns an empty array if a contract does not exist on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getContractMethods(Lamden.wallet.new_wallet().vk); + callback(response); + }, goodNetwork).then(res => { + expect(Array.isArray(res)).to.be(true); + expect(res.length === 0).to.be(true); + }); + }); + it("returns empty array if provided network is unresponsive", async () => { + await driver.executeAsyncScript(async function (badNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(badNetwork); + let response = await api.getContractMethods("currency"); + callback(response); + }, badNetwork).then(res => { + expect(Array.isArray(res)).to.be(true); + expect(res.length === 0).to.be(true); + }) + }); + }); + + context("Masternode_API.getContractVariables()", () => { + it("returns an array if a contract exists on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getContractVariables("currency"); + callback(response); + }, goodNetwork).then(res => { + expect(Array.isArray(res.variables)).to.be(true); + expect(Array.isArray(res.hashes)).to.be(true); + expect(res.hashes.length > 0).to.be(true); + }) + }); + it("returns an empty Object if a contract does not exist on the blockchain", async () => { + await driver.executeAsyncScript(async function (goodNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(goodNetwork); + let response = await api.getContractVariables(Lamden.wallet.new_wallet().vk); + callback(response); + }, goodNetwork).then(res => { + expect(Array.isArray(res.variables)).to.be(false); + expect(Array.isArray(res.hashes)).to.be(false); + expect(Object.keys(res).length === 0).to.be(true); + }) + }); + it("returns empty Object if provided network is unresponsive", async () => { + await driver.executeAsyncScript(async function (badNetwork) { + let callback = arguments[arguments.length-1]; + let api = new Lamden.Masternode_API(badNetwork); + let response = await api.getContractVariables("currency"); + callback(response); + }, badNetwork).then(res => { + expect(Array.isArray(res.variables)).to.be(false); + expect(Array.isArray(res.hashes)).to.be(false); + expect(Object.keys(res).length === 0).to.be(true); + }) + }); + }); + + // context("Masternode_API.getVariable()", () => { + // it("returns the value of the variable if the key exists", async () => { + // let key = balanceCheckWallet.float; + // let response = await goodNetwork_api.getVariable("currency", "balances", key); + // expect(parseFloat(response.__fixed__)).to.be.above(0); + // }); + // it("returns undefined if the key does not exist in the variable", async () => { + // let key = wallet.new_wallet().vk; + // let response = await goodNetwork_api.getVariable("currency", "balances", key); + // expect(response).to.be(null); + // }); + // it("returns undefined if the contract does not exist", async () => { + // let key = keyPair.vk; + // let response = await goodNetwork_api.getVariable(Lamden.wallet.new_wallet().vk, "balances", key); + // expect(response).to.be(null); + // }); + // it("returns undefined if the variable does not exist", async () => { + // let key = keyPair.vk; + // let response = await goodNetwork_api.getVariable("currency", wallet.new_wallet().vk, key); + // expect(response).to.be(null); + // }); + // it("returns undefined if provided network is unresponsive", async () => { + // let key = keyPair.vk; + // let response = await badNetwork_api.getVariable("currency", "balances", key); + // expect(response).to.be(null); + // }); + // }); + + // context("Masternode_API.getContractInfo()", () => { + // it("returns a contract info object", async () => { + // let response = await goodNetwork_api.getContractInfo("currency"); + // expect(response.name).to.be("currency"); + // expect(response.code.length > 0).to.be(true); + // }); + // it("returns undefined if provided network is unresponsive", async () => { + // let response = await badNetwork_api.getContractInfo("currency"); + // expect(response).to.be(null); + // }); + // }); + + // context("Masternode_API.getNonce()", () => { + // it("returns a nonce and processor value for a vk", async () => { + // let response = await goodNetwork_api.getNonce(keyPair.vk); + // expect(response.nonce).to.exist; + // expect(response.processor).to.exist; + // expect(response.sender).to.be(keyPair.vk); + // }); + // it("returns an error message if vk is not a hex string", async () => { + // let error = await goodNetwork_api.getNonce("this-is-not-a-vk"); + // expect(error).to.be(`this-is-not-a-vk is not a hex string.`); + // }); + // it("returns an error message if provided network is unresponsive", async () => { + // let error = await badNetwork_api.getNonce(keyPair.vk); + // expect(error.includes(`Unable to get nonce for ${keyPair.vk}`)).to.be(true); + // }); + // }); +}); diff --git a/test/browsers/network-test.js b/test/browsers/network-test.js new file mode 100644 index 0000000..a8b67ba --- /dev/null +++ b/test/browsers/network-test.js @@ -0,0 +1,132 @@ +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + + +let goodNetwork = { + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], + lamden: true, + blockExplorer: "https://testnet.lamden.io", +}; + +function copyObject(object) { + return JSON.parse(JSON.stringify(object)); +} + +describe("Browsers Tests: Test Netowrk class", () => { + var driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("Constructor", () => { + it("can create an instance", async () => { + let network = await driver.executeScript("return new Lamden.Network(arguments[0])", goodNetwork); + expect(network).to.exist; + expect(JSON.stringify(network.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); + expect(network.hosts[0]).to.be(goodNetwork.hosts[0]); + expect(network.hosts[0]).to.be(goodNetwork.hosts[0]); + expect(network.type).to.be(goodNetwork.type); + expect(network.name).to.be(goodNetwork.name); + expect(network.lamden).to.be(goodNetwork.lamden); + expect(network.blockExplorer).to.be(goodNetwork.blockExplorer); + }); + + it("rejects missing hosts Array", async () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + delete networkInfo.hosts; + await driver.executeScript("return new Lamden.Network(arguments[0])", networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.contain("HOSTS Required (Type: Array)"); + }); + it("rejects no protocol in host string", async () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = ["missing.protocol.com"]; + await driver.executeScript("return new Lamden.Network(arguments[0])", networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.contain("Host String must include http:// or https://"); + }); + it("defaults missing type to custom", async () => { + let networkInfo = copyObject(goodNetwork); + networkInfo.type = ""; + let network = await driver.executeScript("return new Lamden.Network(arguments[0])", networkInfo); + expect(network.type).to.be("custom"); + }); + it("rejects arg not being an object", async () => { + let error; + try { + await driver.executeScript("return new Lamden.Network(arguments[0])", "https://testnet-master-1.lamden.io:443"); + } catch (e) { + error = e; + } + expect(error.message).to.contain("Expected Network Info Object and got Type: string"); + }); + }); + context("Ping Network", () => { + it("emits online status", async () => { + function pingNetwork(goodNetwork) { + var callback = arguments[arguments.length - 1]; + let network = new Lamden.Network(goodNetwork); + network.events.on("online", (status) => callback(status)); + network.ping(); + } + await driver.executeAsyncScript(pingNetwork, goodNetwork).then(function(res) { + expect(res).to.be(true); + }); + }); + it("return value from method return", async () => { + await driver.executeAsyncScript(function () { + var callback = arguments[arguments.length - 1]; + let network = new Lamden.Network(arguments[0]); + network.ping().then(res => callback(res)); + }, goodNetwork).then(function(res) { + expect(res).to.be(true); + }); + }); + it("returns online status through callback", async () => { + await driver.executeAsyncScript(function () { + var callback = arguments[arguments.length - 1]; + let network = new Lamden.Network(arguments[0]); + network.ping(res => callback(res)); + }, goodNetwork).then(function(res) { + expect(res).to.be(true); + }); + }); + }); +}); diff --git a/test/browsers/test.html b/test/browsers/test.html new file mode 100644 index 0000000..9b04820 --- /dev/null +++ b/test/browsers/test.html @@ -0,0 +1,21 @@ + + + + + + + Document + + +
This is a test page
+ + + + \ No newline at end of file diff --git a/test/browsers/transactionBatcher-test.js b/test/browsers/transactionBatcher-test.js new file mode 100644 index 0000000..f0ab4dd --- /dev/null +++ b/test/browsers/transactionBatcher-test.js @@ -0,0 +1,242 @@ +/* + The Transaction Batcher is in alpha and so I disabled the test cases for it as they cause the suite to fail. + The nonces won't increment properly depending on network lag and I don't have a good solution to it. +*/ +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + +let networkInfo = { + hosts: ["https://testnet-master-1.lamden.io:443"], +}; + +let uid = "randomUIDstring"; + +const senderWallet1 = { + vk: "960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb", + sk: "c8a3c5333aa3b058c4fa16d48db52355ab62ddc8daa9a183706a912e522440b6", +}; +const senderWallet2 = { + vk: "6a91a9a65eb80829a360efc0555cad8841af64c78375bbf394f6ecb89d5644ee", + sk: "4166ed44f465c51d562895295cdcde64a3444b14ea2a3e477c60cf0ecde65230", +}; + +let recieverWallet = { + vk: "f16c130ceb7ed9bcebde301488cfd507717d5d511674bc269c39ad41fc15d780", +}; + +function sleep(milliseconds) { + const date = Date.now(); + let currentDate = null; + do { + currentDate = Date.now(); + } while (currentDate - date < milliseconds); +} + +const makeTxList = (senderVK, receiver, amount) => { + let txList = []; + for (i = 0; i <= amount - 1; i++) { + txList.push({ + uid, + senderVk: senderVK, + contractName: "currency", + methodName: "transfer", + kwargs: { + to: receiver, + amount: { __fixed__: "0.0005" }, + }, + stampLimit: 500, + }); + } + return txList; +}; + +let keyList = {}; +keyList[senderWallet1.vk] = senderWallet1.sk; +keyList[senderWallet2.vk] = senderWallet2.sk; + +describe("Browsers Tests: Test TransactionBuilder class", async () => { + var driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("new TransactionBuilder", () => { + it("can create an instance", async () => { + let txb = await driver.executeScript(function (networkInfo) { + return new Lamden.TransactionBatcher(networkInfo); + }, networkInfo) + expect(txb.running).to.be(false); + }); + }); /* + context('TransactionBatcher.addTransaction()', () => { + it('can add a list of transactions for 1 sender', () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + txList1.forEach(txInfo => txb.addTransaction(txInfo)) + + expect(txb.txBatches[senderWallet1.vk].length).to.be(txList1.length) + }) + it('can add a list of transactions for 2 sender', () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + const txList2 = makeTxList(senderWallet2.vk, recieverWallet.vk, 15) + + txList1.forEach(txInfo => txb.addTransaction(txInfo)) + txList2.forEach(txInfo => txb.addTransaction(txInfo)) + + expect(txb.txBatches[senderWallet1.vk].length).to.be(txList1.length) + expect(txb.txBatches[senderWallet2.vk].length).to.be(txList2.length) + expect(Object.keys(txb.txBatches).length).to.be(2) + }) + it('can add a list of transactions and split info into senders', () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + const txList2 = makeTxList(senderWallet2.vk, recieverWallet.vk, 15) + + txb.addTransactionList([...txList1, ...txList2]) + + expect(txb.txBatches[senderWallet1.vk].length).to.be(txList1.length) + expect(txb.txBatches[senderWallet2.vk].length).to.be(txList2.length) + expect(Object.keys(txb.txBatches).length).to.be(2) + }) + }) + context('TransactionBatcher.getStartingNonce()', () => { + it('can the starting nonce for a senderVk', async () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + let response = await txb.getStartingNonce(senderWallet1.vk) + + expect(response.nonce >= 0).to.be(true) + }) + }) + context('TransactionBatcher.setBatchNonces()', () => { + it('can increment the nonces in a txList', async () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + let response = await txb.getStartingNonce(senderWallet1.vk) + + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + + let newList = txb.setBatchNonces(response, txList1) + + newList.forEach((txbuilder, index) => { + expect(txbuilder.nonce).to.be(response.nonce + index) + }) + }) + }) + context('TransactionBatcher.signBatch()', () => { + it('can sign a list of transactions', async () => { + let txb = new Lamden.TransactionBatcher(networkInfo) + let response = await txb.getStartingNonce(senderWallet1.vk) + + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + + let newList = txb.setBatchNonces(response, txList1) + txb.signBatch(newList, senderWallet1.sk) + + newList.forEach((txbuilder) => { + expect(txbuilder.signature.length > 0).to.be(true) + expect(txbuilder.transactionSigned).to.be(true) + }) + }) + }) + context('TransactionBatcher.sendBatch()', () => { + it('can send a batch of successful transactions', async function () { + this.timeout(60000); + let txb = new Lamden.TransactionBatcher(networkInfo) + let response = await txb.getStartingNonce(senderWallet1.vk) + + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + + let newList = txb.setBatchNonces(response, txList1) + txb.signBatch(newList, senderWallet1.sk) + + let sentBatch = await txb.sendBatch(newList) + + sentBatch.forEach(async (promise) => { + let txBuilder = await promise + if (!txBuilder.txSendResult.hash) console.log(txBuilder.nonce + ": " + txBuilder.txSendResult.errors) + expect(typeof txBuilder.txSendResult.hash === 'string').to.be(true) + }) + + expect(txb.hasTransactions()).to.be(false) + }) + }) + + context('TransactionBatcher.sendAllBatches()', () => { + it('Can send batches from all senders', async function () { + this.timeout(60000); + sleep(1500) + let txb = new Lamden.TransactionBatcher(networkInfo) + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 15) + const txList2 = makeTxList(senderWallet2.vk, recieverWallet.vk, 15) + + txb.addTransactionList([...txList1, ...txList2]) + + let sentBatchs = await txb.sendAllBatches(keyList) + + sentBatchs.forEach(txBuilder => { + if (!txBuilder.txSendResult.hash) console.log(txBuilder.nonce + ": " + txBuilder.txSendResult.errors) + expect(typeof txBuilder.txSendResult.hash === 'string').to.be(true) + }) + + expect(txb.hasTransactions()).to.be(false) + }) + it('Can process overflow', async function () { + this.timeout(30000); + sleep(1500) + let txb = new Lamden.TransactionBatcher(networkInfo) + const txList1 = makeTxList(senderWallet1.vk, recieverWallet.vk, 1) + const txList2 = makeTxList(senderWallet2.vk, recieverWallet.vk, 1) + + txb.addTransactionList([...txList1, ...txList2]) + let txPromise = txb.sendAllBatches(keyList) + txb.addTransactionList([...txList1, ...txList2]) + + let sentBatchs1 = await txPromise + sentBatchs1.forEach(txBuilder => { + if (!txBuilder.txSendResult.hash) console.log(txBuilder.nonce + ": " + txBuilder.txSendResult.errors) + expect(typeof txBuilder.txSendResult.hash === 'string').to.be(true) + }) + + expect(txb.hasTransactions()).to.be(true) + + let sentBatchs2 = await txb.sendAllBatches(keyList) + sleep(1500) + sentBatchs2.forEach(txBuilder => { + if (!txBuilder.txSendResult.hash) console.log(txBuilder.nonce + ": " + txBuilder.txSendResult.errors) + expect(typeof txBuilder.txSendResult.hash === 'string').to.be(true) + }) + + expect(txb.hasTransactions()).to.be(false) + + }) + })*/ +}); diff --git a/test/browsers/transactionBuilder-test.js b/test/browsers/transactionBuilder-test.js new file mode 100644 index 0000000..175919a --- /dev/null +++ b/test/browsers/transactionBuilder-test.js @@ -0,0 +1,437 @@ +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); +const expect = require("expect.js"); +const Lamden = require("../../dist/cjs/lamden"); +require("dotenv").config(); + + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + + +const { vk, sk } = process.env; + +let goodNetwork = { + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], +}; + +let badNetwork = { + type: "testnet", + name: "Bad Network", + hosts: ["http://badnetwork.lamden.io:18080"], +}; + +let uid = "randomUIDstring"; + +const senderWallet = { vk, sk }; + +let recieverWallet = Lamden.wallet.new_wallet(); + +let senderVk = senderWallet.vk; +let contractName = "currency"; +let methodName = "transfer"; +let stampLimit = 100; +let nonce = 0; +let processor = "0000000000000000000000000000000000000000000000000000000000000000"; + +let kwargs = { + to: recieverWallet.vk, + amount: 1, +}; + +let valuesTxInfo = { + senderVk: senderWallet.vk, + contractName: "con_values_testing_2", + methodName: "test_values", + stampLimit: 100, + kwargs: { + UID: "lamdenjs-testing", + Str: "test string", + Int: 1, + Float: 1.01, + Bool: false, + Dict: { s: "test", i: 1, f: 1.1, b: true, d: { f: 1.1, l: [1, 1.1] }, l: [1, 1.1] }, + List: ["test", 1, 1.1, false, { f: 1.1, l: [1, 1.1] }, [1, 1.1]], + ANY: { f: 1.1, l: [1, 1.1] }, + DateTime: { datetime: "2020-07-28T19:16:35.059Z" }, + TimeDelta: { timedelta: 1000 }, + }, +}; + +let txInfo_noNonce = { uid, senderVk, contractName, methodName, kwargs, stampLimit }; +let txInfo_withNonce = { + uid, + senderVk, + contractName, + methodName, + kwargs, + stampLimit, + nonce, + processor, +}; + +describe("Browsers Tests: Test TransactionBuilder class", () => { + var driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("new TransactionBuilder", () => { + it("can create an instance without nonce or processor", async () => { + const {newTx, newTxInfo} = await driver.executeScript(function (goodNetwork, txInfo_noNonce) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + let newTxInfo = newTx.getAllInfo(); + return {newTx, newTxInfo} + }, goodNetwork, txInfo_noNonce) + expect(newTx).to.exist; + //Validate TX Info propagated in the class + expect(newTxInfo.uid).to.be(txInfo_noNonce.uid); + expect(newTxInfo.txInfo.senderVk).to.be(txInfo_noNonce.senderVk); + expect(newTxInfo.txInfo.contractName).to.be(txInfo_noNonce.contractName); + expect(newTxInfo.txInfo.methodName).to.be(txInfo_noNonce.methodName); + expect(newTxInfo.txInfo.kwargs.to).to.be(txInfo_noNonce.kwargs.to); + expect(newTxInfo.txInfo.kwargs.amount).to.be(txInfo_noNonce.kwargs.amount); + //Validate internal properties + expect(newTxInfo.signed).to.be(false); + expect(newTxInfo.signature).to.be(null); + expect(JSON.stringify(newTxInfo.txSendResult)).to.be(JSON.stringify({ errors: [] })); + expect(JSON.stringify(newTxInfo.txBlockResult)).to.be(JSON.stringify({})); + expect(JSON.stringify(newTxInfo.nonceResult)).to.be(JSON.stringify({})); + }); + it("can create an instance by providing nonce and processor", async () => { + const {newTx, newTxInfo} = await driver.executeScript(function (goodNetwork, txInfo_withNonce) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + let newTxInfo = newTx.getAllInfo(); + return {newTx, newTxInfo} + }, goodNetwork, txInfo_withNonce) + expect(newTx).to.exist; + expect(newTxInfo.txInfo.nonce).to.exist; + expect(newTxInfo.txInfo.processor).to.exist; + }); + + it("it throws error when missing arguments", async() => { + async function testValues( + argName, + networkInfo, + senderVk, + contractName, + methodName, + kwargs, + stampLimit + ) { + let txInfo = { senderVk, contractName, methodName, kwargs, stampLimit }; + try { + return await driver.executeScript(function (networkInfo, txInfo) { + return new Lamden.TransactionBuilder(networkInfo, txInfo) + }, networkInfo, txInfo) + } catch (e) { + expect(e.message.includes(argName)).to.be(true); + } + } + let newTx = undefined; + + newTx = await testValues( + "Network Info", + undefined, + senderWallet.vk, + "currency", + "transfer", + kwargs, + 50000 + ); + newTx = await testValues("Sender", goodNetwork, undefined, "currency", "transfer", kwargs, 50000); + newTx = await testValues( + "Contract", + goodNetwork, + senderWallet.vk, + undefined, + "transfer", + kwargs, + 50000 + ); + newTx = await testValues( + "Method", + goodNetwork, + senderWallet.vk, + "currency", + undefined, + kwargs, + 50000 + ); + newTx = await testValues( + "Stamps", + goodNetwork, + senderWallet.vk, + "currency", + "transfer", + kwargs, + undefined + ); + expect(typeof newTx).to.be("undefined"); + }); + + it("it can create an instance with a Lamden Network Object as first arg", async () => { + let error = ""; + let newTx = await driver.executeScript(function (goodNetwork, txInfo_withNonce) { + let network = new Lamden.Network(goodNetwork); + let newTx = new Lamden.TransactionBuilder(network, txInfo_withNonce); + return newTx + }, goodNetwork, txInfo_withNonce).catch(e => { + error = e; + }) + expect(newTx).to.exist; + expect(error === "").to.be(true); + }); + }); + + context("TransactionBuilder.sign()", () => { + it("can sign and verify a transaction", async () => { + let res = await driver.executeScript(function (goodNetwork, txInfo_withNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + newTx.sign(senderWallet.sk); + return [newTx.transactionSigned, newTx.verifySignature()]; + }, goodNetwork, txInfo_withNonce, senderWallet) + expect(res[0]).to.be(true); + expect(res[1]).to.be(true); + }); + it("can sign and verify a transaction using a keystore wallet", async () => { + let res = await driver.executeScript(function (goodNetwork, txInfo_withNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + let stringBuffer = Buffer.from(newTx.sortedPayload.json); + let message = new Uint8Array(stringBuffer); + let keystore = new Lamden.Keystore({ key: { sk: senderWallet.sk } }); + newTx.sign(null, keystore.wallets[0]); + return [newTx.transactionSigned, newTx.verifySignature(), keystore.wallets[0].verify(message, newTx.signature)]; + }, goodNetwork, txInfo_withNonce, senderWallet) + expect(res[0]).to.be(true); + expect(res[1]).to.be(true); + expect(res[2]).to.be(true); + }); + it("throws and error if nonce not set ", async () => { + let res = await driver.executeScript(function (goodNetwork, txInfo_noNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + let error = "" + try { + newTx.sign(senderWallet.sk); + } catch(e){ + error = e + } + return [newTx, error]; + }, goodNetwork, txInfo_noNonce, senderWallet) + expect(res[0].nonce).to.not.exist; + expect(res[0].processor).to.not.exist; + }); + }); + + context("TransactionBuilder.getNonce()", () => { + it("can retrieve nonce and processor from the masternode", async () => { + const {newTx, response} =await driver.executeScript(async function (goodNetwork, txInfo_noNonce){ + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + let response = await newTx.getNonce(); + return {newTx, response} + }, goodNetwork, txInfo_noNonce) + expect(newTx.nonce).to.not.exist; + expect(newTx.processor).to.not.exist; + + //Validate Nonce was retrieved + expect(response.nonce).to.exist; + expect(response.processor).to.exist; + expect(response.sender).to.exist; + expect(newTx.nonce).to.be(response.nonce); + expect(newTx.processor).to.be(response.processor); + expect(newTx.sender).to.be(response.sender); + expect(goodNetwork.hosts.includes(newTx.nonceMasternode)).to.be(true); + }); + it("throws error if vk is not correct type, missing or invalid", async () => { + await driver.executeScript(async function (goodNetwork, txInfo_noNonce){ + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.sender = "not-a-good-vk"; + await newTx.getNonce(); + }, goodNetwork, txInfo_noNonce).catch(e =>{ + expect(e.message).to.contain(`is not a hex string.`); + }); + }); + it("throws error if provided network is unresponsive", async () => { + let res = await driver.executeScript(async function (badNetwork, txInfo_noNonce){ + let flag = false; + let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_noNonce); + try{ + await newTx.getNonce(); + } catch(e) { + if(e.message.includes(`Unable to get nonce for ${newTx.sender} on network ${newTx.url}`)) { + flag = true + } + } + return flag + }, badNetwork, txInfo_noNonce) + expect(res).to.be(true); + }); + }); + + context("TransactionBuilder.send()", () => { + let oldResultInfo,resultInfo, txSendResult, txBlockResult, newTx1; + it("Sends a transaction and receives a hash back", async function () { + this.timeout(20000); + await driver.executeAsyncScript(async function (goodNetwork, txInfo_noNonce, senderWallet) { + let callback = arguments[arguments.length-1] + let newTx1 = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + await newTx1.getNonce(); + //Sign transaction + newTx1.sign(senderWallet.sk); + //Send Tx + await newTx1.send(); + let oldResultInfo = newTx1.resultInfo + let txSendResult = newTx1.txSendResult; + await newTx1.checkForTransactionResult(); + let txBlockResult = newTx1.txBlockResult; + callback([newTx1.transactionSigned, newTx1.verifySignature(), txSendResult, oldResultInfo, txBlockResult, newTx1.resultInfo, newTx1]) + }, goodNetwork, txInfo_noNonce, senderWallet).then(res => { + expect(res[0]).to.be(true); + expect(res[1]).to.be(true); + expect(res[2].success).to.contain("Transaction successfully submitted to the network."); + expect(res[2].hash).to.exist; + expect(res[2].timestamp).to.exist; + txSendResult = res[2]; + oldResultInfo = res[3]; + txBlockResult = res[4]; + resultInfo = res[5] + newTx1 = res[6]; + }) + }); + it("Creates ResultInfo object based on txSendResult", function () { + expect(oldResultInfo.title).to.equal("Transaction Pending"); + expect(oldResultInfo.subtitle).to.equal("Your transaction was submitted and is being processed"); + expect(oldResultInfo.message).to.equal(`Tx Hash: ${txSendResult.hash}`); + expect(oldResultInfo.type).to.equal("success"); + }); + it("Sends transactions and can get hash result from masternode", function () { + expect(txBlockResult.hash).to.equal(txSendResult.hash); + expect(txBlockResult.result).to.equal("None"); + expect(txBlockResult.stamps_used > 0).to.be(true); + expect(txBlockResult.state.length).to.equal(2); + expect(txBlockResult.status).to.equal(0); + expect(JSON.stringify(txBlockResult.transaction)).to.equal(JSON.stringify(newTx1.tx)); + expect(txBlockResult.timestamp).to.exist; + }); + it("Creates ResultInfo object based on txBlockResult", async function () { + expect(resultInfo.title).to.equal("Transaction Successful"); + expect(resultInfo.subtitle).to.equal(`Your transaction used ${resultInfo.stampsUsed} stamps`); + expect(resultInfo.message).to.equal(""); + expect(resultInfo.type).to.equal("success"); + expect(resultInfo.errorInfo).to.equal(null); + expect(resultInfo.stampsUsed?resultInfo.stampsUsed:undefined).to.equal(txBlockResult.stamps_used); + expect(resultInfo.statusCode).to.equal(0); + expect(resultInfo.returnResult).to.equal("None"); + }); + it("gets nonce and signs transacation automatically if sk is provided", async function () { + this.timeout(30000) + let txSendResult = await driver.executeScript(async function (goodNetwork, txInfo_noNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + await newTx.send(senderWallet.sk); + let txSendResult = newTx.txSendResult; + return txSendResult; + }, goodNetwork, txInfo_noNonce, senderWallet) + + expect(txSendResult.success).to.equal("Transaction successfully submitted to the network."); + expect(txSendResult.hash).to.exist; + expect(txSendResult.timestamp).to.exist; + }); + it("throws error if provided network is unresponsive", async function () { + let response = await driver.executeScript(async function (badNetwork, txInfo_withNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_withNonce) + let res = await newTx.send(senderWallet.sk); + return res + }, badNetwork, txInfo_withNonce, senderWallet) + expect(response.errors[0]).to.be( + "TypeError: Failed to fetch" + ); + }); + it("can return execution errors list", async function () { + this.timeout(30000) + let {resultInfo, txBlockResult} = await driver.executeScript(async function (goodNetwork, txInfo_noNonce, senderWallet) { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.stampLimit = 0; + //Send Tx + await newTx.send(senderWallet.sk); + await newTx.checkForTransactionResult(); + let resultInfo = newTx.resultInfo; + let txBlockResult = newTx.txBlockResult; + return {resultInfo, txBlockResult} + }, goodNetwork, txInfo_noNonce, senderWallet) + + expect(resultInfo.title).to.equal("Transaction Failed"); + expect(resultInfo.subtitle).to.equal( + `Your transaction returned status code 1 and used ${resultInfo.stampsUsed} stamps` + ); + expect(resultInfo.message).to.equal("This transaction returned 1 errors."); + expect(resultInfo.type).to.equal("error"); + expect(resultInfo.errorInfo.length).to.equal(2); + expect(resultInfo.errorInfo[0]).to.equal("This transaction returned a non-zero status code"); + expect(resultInfo.errorInfo[1].includes("The cost has exceeded the stamp supplied!")).to.be( + true + ); + expect(resultInfo.stampsUsed).to.equal(txBlockResult.stamps_used); + expect(resultInfo.statusCode).to.equal(1); + expect(resultInfo.returnResult.includes("The cost has exceeded the stamp supplied!")).to.be( + true + ); + }); + it("can return transaction validation errors list", async function () { + this.timeout(30000) + let response = await driver.executeScript(async function (goodNetwork, txInfo_noNonce) { + let sender = Lamden.wallet.new_wallet(); + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.sender = sender.vk; + //Send Transaction + let response = await newTx.send(sender.sk) + return response + }, goodNetwork, txInfo_noNonce) + expect(response.errors.length > 0).to.be(true); + expect(response.errors[0]).to.be( + "Transaction sender has too few stamps for this transaction." + ); + }); + it("can encode and send all annotation types", async function () { + this.timeout(30000); + const {response, check} = await driver.executeScript(async function (valuesTxInfo,goodNetwork,senderWallet){ + valuesTxInfo.kwargs = Lamden.Encoder("object", valuesTxInfo.kwargs); + + let newTx = new Lamden.TransactionBuilder(goodNetwork, valuesTxInfo); + + //Send Transaction + let response = await newTx.send(senderWallet.sk); + //Check Transaction + let check = await newTx.checkForTransactionResult(); + return {response, check} + },valuesTxInfo,goodNetwork,senderWallet) + + expect(response.success).to.be("Transaction successfully submitted to the network."); + expect(check.status).to.be(0); + }); + }); +}); diff --git a/test/browsers/wallet-test.js b/test/browsers/wallet-test.js new file mode 100644 index 0000000..50c216a --- /dev/null +++ b/test/browsers/wallet-test.js @@ -0,0 +1,168 @@ +const expect = require("expect.js"); +const validators = require("types-validate-assert"); +const { validateTypes, assertTypes } = validators; +const {Builder, logging, Capabilities } = require('selenium-webdriver'); +const Koa = require('koa'); +const KoaStatic = require('koa-static'); +const path = require('path'); + +// https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/lib/logging.html +const prefs = new logging.Preferences(); +prefs.setLevel(logging.Type.BROWSER, logging.Level.ALL); +const caps = Capabilities.chrome(); +caps.setLoggingPrefs(prefs); + + +describe("Browsers Tests: Test Lamden Wallet methods", async () => { + var driver; + let server; + const app = new Koa(); + const port = 6800; + before(async function() { + // Start a http server + app.use(KoaStatic(path.join(__dirname,'../../'))); + server = app.listen(port, () => console.log(`\n\x1B[32mKoa Server running at http://127.0.0.1:${port}/\x1B[0m`)) + + driver = await new Builder() + .withCapabilities(caps) + .forBrowser("chrome") + .build(); + + // Load the test.html + await driver.get(`http://127.0.0.1:${port}/test/browsers/test.html`); + }); + + after(() => { + driver && driver.quit(); + server && server.close(); + }); + + context("wallet.create_wallet_bip39: ", () => { + it("creates a bip39 / bip32 compatible lamden keypair", async () => { + let newWallet = await driver.executeScript("return Lamden.wallet.new_wallet_bip39()"); + + expect(validateTypes.isStringHex(newWallet.vk)).to.be(true); + expect(newWallet.vk.length).to.be(64); + expect(validateTypes.isStringHex(newWallet.sk)).to.be(true); + expect(newWallet.sk.length).to.be(64); + expect(validateTypes.isStringWithValue(newWallet.mnemonic)).to.be(true); + expect(validateTypes.isNumber(newWallet.derivationIndex)).to.be(true); + expect(newWallet.derivationIndex).to.be(0); + }), + it("creates a bip39 / bip32 compatible lamden keypair from seed", async () => { + const seed = 'd3ad26bd89d54d0c22bb32d34ea9f06c567ba060d8e1518974d807180b886c643bfb7f455bd3db2c767a17c089aab20db97cf0f0184d730b9d20be0c7b6cc6cc' + const derivationIndex = 127; + + let newWallet = await driver.executeScript(`return Lamden.wallet.new_wallet_bip39('${seed}', ${derivationIndex})`); + + expect(validateTypes.isStringHex(newWallet.vk)).to.be(true); + expect(newWallet.vk).to.be("d0d2de909bf7c2be3bafbcb3af0b1c50487b80ba48b5700bff35bb927921c607"); + expect(validateTypes.isStringHex(newWallet.sk)).to.be(true); + expect(newWallet.sk).to.be("86c77748edc039c672cf761d2db1e52d6255b16cd4d626d4b66c67eb224287a8"); + expect(newWallet.mnemonic).to.be(null); + expect(newWallet.seed).to.be( null ) + expect(validateTypes.isNumber(newWallet.derivationIndex)).to.be(true); + expect(newWallet.derivationIndex).to.be(127); + }); + }); + + context("wallet.new_wallet(): ", () => { + it("creates a lamden keypair", async () => { + let newWallet = await driver.executeScript("return Lamden.wallet.new_wallet();"); + expect(validateTypes.isStringHex(newWallet.vk)).to.be(true); + expect(newWallet.vk.length).to.be(64); + expect(validateTypes.isStringHex(newWallet.sk)).to.be(true); + expect(newWallet.sk.length).to.be(64); + }); + }); + + context("wallet.get_vk(): ", () => { + it("can create a vk from an sk", async () => { + let res = await driver.executeScript(function () { + let newWallet = Lamden.wallet.new_wallet(); + return [Lamden.wallet.get_vk(newWallet.sk), newWallet.vk] + }); + expect(res[0]).to.be(res[1]); + }); + }); + context("wallet.sign(): ", () => { + it("can sign a message", async () => { + let signedMessage = await driver.executeScript(function () { + let newWallet = Lamden.wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = Lamden.wallet.sign(newWallet.sk, message); + return signedMessage + }); + expect(validateTypes.isStringHex(signedMessage)).to.be(true); + }); + }); + + context("wallet.verify(): ", () => { + it("can validate a correct signature", async () => { + let res = await driver.executeScript(function () { + let newWallet = Lamden.wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = Lamden.wallet.sign(newWallet.sk, message); + return Lamden.wallet.verify(newWallet.vk, message, signedMessage) + }); + expect(res).to.be(true); + }); + it("can validate an incorrect signature", async () => { + let res = await driver.executeScript(function () { + let newWallet = Lamden.wallet.new_wallet(); + let newWallet2 = Lamden.wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = Lamden.wallet.sign(newWallet.sk, message); + return Lamden.wallet.verify(newWallet2.vk, message, signedMessage) + }); + expect(res).to.be(false); + }); + }); + + context("wallet.create_wallet(): ", () => { + it("can create a new wallet object", async () => { + let newWallet = await driver.executeScript("return Lamden.wallet.create_wallet();"); + expect(newWallet).to.have.property("sign"); + expect(newWallet).to.have.property("verify"); + expect(newWallet).to.have.property("vk"); + expect(newWallet).to.have.property("sk"); + assertTypes.isStringHex(newWallet.vk); + assertTypes.isStringHex(newWallet.sk); + }); + it("can create a new wallet from a private key", async () => { + let newWallet = await driver.executeScript(function () { + let keypair = Lamden.wallet.new_wallet(); + let newWallet = Lamden.wallet.create_wallet({ sk: keypair.sk }); + return newWallet + }); + expect(newWallet).to.have.property("sign"); + expect(newWallet).to.have.property("verify"); + expect(newWallet).to.have.property("vk"); + expect(newWallet).to.have.property("sk"); + assertTypes.isStringHex(newWallet.vk); + assertTypes.isStringHex(newWallet.sk); + }); + it("secret key is not accessible is set to private", async () => { + let newWallet = await driver.executeScript("return Lamden.wallet.create_wallet({ keepPrivate: true });"); + expect(() => assertTypes.isStringHex(newWallet.sk)).throwException(); + }); + it("wallet object can sign messages", async () => { + let res = await driver.executeScript(function () { + let newWallet = Lamden.wallet.create_wallet({ keepPrivate: true }); + let message = new Uint8Array("this is a message"); + let signedMessage = newWallet.sign(message); + return Lamden.wallet.verify(newWallet.vk, message, signedMessage) + }) + expect(res).to.be(true); + }); + it("wallet object can verify a messages", async () => { + let res = await driver.executeScript(function () { + let newWallet = Lamden.wallet.create_wallet({ keepPrivate: true }); + let message = new Uint8Array("this is a message"); + let signedMessage = newWallet.sign(message); + return newWallet.verify(message, signedMessage) + }) + expect(res).to.be(true); + }); + }); +}); diff --git a/test/encoder-test.js b/test/encoder-test.js index 94a4f72..80d6739 100644 --- a/test/encoder-test.js +++ b/test/encoder-test.js @@ -1,224 +1,287 @@ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); const { Encoder } = Lamden; -const dateString = "2020-07-28T19:16:35.059Z" -const millisecondsDelta = 475200000 +const dateString = "2020-07-28T19:16:35.059Z"; +const millisecondsDelta = 475200000; -describe('Test Type Encoder', () => { - context('TYPES', () => { - it('Encoder rejects unknown TYPE', () => { - expect(() => Encoder('nope', {})).to.throwError(); - }) - }) +describe("Test Type Encoder", () => { + context("TYPES", () => { + it("Encoder rejects unknown TYPE", () => { + expect(() => Encoder("nope", {})).to.throwError(); + }); + }); - context('BigNumber', () => { - it('Encoder can call BigNumber', () => { - expect(Encoder.BigNumber.sum(1,2).toString()).to.be( '3' ) - }) - }) + context("BigNumber", () => { + it("Encoder can call BigNumber", () => { + expect(Encoder.BigNumber.sum(1, 2).toString()).to.be("3"); + }); + }); - context('Strings', () => { - it('encodes a string from a string', () => { - expect( Encoder('str', 'string') ).to.be( 'string' ) - }) - it('encodes a number as a string', () => { - expect( Encoder('str', 1) ).to.be( '1' ) - }) - it('encodes a boolean as a string', () => { - expect( Encoder('str', true) ).to.be( 'true' ) - }) - it('encodes a Date as a string', () => { - expect( Encoder('str', new Date(dateString)) ).to.be( '2020-07-28T19:16:35.059Z' ) - }) - it('encodes a Dict as a string', () => { - expect( Encoder('str', {}) ).to.be( '{}' ) - }) - it('encodes a List as a string', () => { - expect( Encoder('str', []) ).to.be( '[]' ) - }) - }) + context("Strings", () => { + it("encodes a string from a string", () => { + expect(Encoder("str", "string")).to.be("string"); + }); + it("encodes a number as a string", () => { + expect(Encoder("str", 1)).to.be("1"); + }); + it("encodes a boolean as a string", () => { + expect(Encoder("str", true)).to.be("true"); + }); + it("encodes a Date as a string", () => { + expect(Encoder("str", new Date(dateString))).to.be("2020-07-28T19:16:35.059Z"); + }); + it("encodes a Dict as a string", () => { + expect(Encoder("str", {})).to.be("{}"); + }); + it("encodes a List as a string", () => { + expect(Encoder("str", [])).to.be("[]"); + }); + }); - context('Integers', () => { - it('encodes a integer from an integer', () => { - expect( Encoder('int', 1) ).to.be( 1 ) - }) - it('encodes a integer from a float', () => { - expect( Encoder('int', 1.5 ) ).to.be( 1 ) - }) - it('encodes a integer from a string', () => { - expect( Encoder('int', '1.5' ) ).to.be( 1 ) - }) - it('fails to encode non-integer values', () => { - expect(() => Encoder('int', true)).to.throwError(); - }) - }) - context('Floats', () => { - it('encodes a __fixed__ object from an float', () => { - expect( JSON.stringify(Encoder('float', 1.5)) ).to.be( JSON.stringify({"__fixed__": "1.5"}) ) - }) - it('encodes a __fixed__ object to integer', () => { - expect( JSON.stringify(Encoder('float', 1 )) ).to.be( JSON.stringify({"__fixed__": "1.0"}) ) - }) - it('encodes a __fixed__ object with zeros as decimals to an integer', () => { - expect( JSON.stringify(Encoder('float', 1.00 )) ).to.be( JSON.stringify({"__fixed__": "1.0"}) ) - }) - it('encodes a __fixed__ object from a string', () => { - expect( JSON.stringify(Encoder('float', '1.5' )) ).to.be( JSON.stringify({"__fixed__": "1.5"}) ) - }) - it('encodes a __fixed__ object from a float and loses percision', () => { - expect( JSON.stringify(Encoder('float', 0.9999999999999999999999999999999 )) ).to.be( JSON.stringify({"__fixed__": "1.0"}) ) - }) - it('encodes __fixed__ object float from a string and retains precision', () => { - expect( JSON.stringify(Encoder('float', '0.9999999999999999999999999999999' )) ).to.be( JSON.stringify({"__fixed__": "0.999999999999999999999999999999"}) ) - }) - it('encodes __fixed__ object float from a bigNumber Object and retains precision', () => { - let bn = Encoder('bigNumber', '0.9999999999999999999999999999999') - expect( JSON.stringify(Encoder('float', bn )) ).to.be( JSON.stringify({"__fixed__": "0.999999999999999999999999999999"}) ) - }) - it('fails to encode non-float values', () => { - expect(() => Encoder('float', true)).to.throwError(); - }) - }) - context('Boolean', () => { - it('encodes a boolean from a boolean', () => { - expect( Encoder('bool', true) ).to.be( true ) - expect( Encoder('bool', false) ).to.be( false ) - }) - it('encodes a boolean from a number', () => { - expect( Encoder('bool', 1 ) ).to.be( true ) - expect( Encoder('bool', 0 ) ).to.be( false ) - }) - it('encodes a boolean from a string', () => { - expect( Encoder('bool', 'true' ) ).to.be( true ) - expect( Encoder('bool', 'false' ) ).to.be( false ) - }) - it('fails to encode non-boolean values', () => { - expect(() => Encoder('bool', 'nope')).to.throwError(); - expect(() => Encoder('bool', 2)).to.throwError(); - expect(() => Encoder('bool', {})).to.throwError(); - }) - }) - context('Dict Object', () => { - it('encodes a dict from an Object', () => { - expect( JSON.stringify(Encoder('dict', {})) ).to.be( JSON.stringify({}) ) - }) - it('encodes a dict from a string', () => { - expect( JSON.stringify(Encoder('dict', '{"vk":"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7"}')) ).to.be( JSON.stringify({vk:"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7"}) ) - }) - it('encodes datetime and float inside a dict from a string', () => { - expect( JSON.stringify(Encoder('dict', {'datetime':new Date(dateString), 'float': 1.1})) ).to.be( '{"datetime":{"__time__":[2020,6,28,19,16,35,59]},"float":{"__fixed__":"1.1"}}' ) - }) - it('replaces datetime object with value in dict', () => { - expect( JSON.stringify( Encoder('dict', {'DateTime':{'datetime':new Date(dateString)}})) ).to.be('{"DateTime":{"__time__":[2020,6,28,19,16,35,59]}}'); - }) - it('replaces timedelta object with value in dict', () => { - expect( JSON.stringify( Encoder('dict', {'TimeDelta':{'timedelta':1000}})) ).to.be('{"TimeDelta":{"__delta__":[0,1]}}'); - }) - it('fails to encode non-objects', () => { - expect(() => Encoder('dict', undefined)).to.throwError(); - }) - }) + context("Integers", () => { + it("encodes a integer from an integer", () => { + expect(Encoder("int", 1)).to.be(1); + }); + it("encodes a integer from a float", () => { + expect(Encoder("int", 1.5)).to.be(1); + }); + it("encodes a integer from a string", () => { + expect(Encoder("int", "1.5")).to.be(1); + }); + it("fails to encode non-integer values", () => { + expect(() => Encoder("int", true)).to.throwError(); + }); + }); + context("Floats", () => { + it("encodes a __fixed__ object from an float", () => { + expect(JSON.stringify(Encoder("float", 1.5))).to.be(JSON.stringify({ __fixed__: "1.5" })); + }); + it("encodes a __fixed__ object to integer", () => { + expect(JSON.stringify(Encoder("float", 1))).to.be(JSON.stringify({ __fixed__: "1.0" })); + }); + it("encodes a __fixed__ object with zeros as decimals to an integer", () => { + expect(JSON.stringify(Encoder("float", 1.0))).to.be(JSON.stringify({ __fixed__: "1.0" })); + }); + it("encodes a __fixed__ object from a string", () => { + expect(JSON.stringify(Encoder("float", "1.5"))).to.be(JSON.stringify({ __fixed__: "1.5" })); + }); + it("encodes a __fixed__ object from a float and loses percision", () => { + expect(JSON.stringify(Encoder("float", 0.9999999999999999999999999999999))).to.be( + JSON.stringify({ __fixed__: "1.0" }) + ); + }); + it("encodes __fixed__ object float from a string and retains precision", () => { + expect(JSON.stringify(Encoder("float", "0.9999999999999999999999999999999"))).to.be( + JSON.stringify({ __fixed__: "0.999999999999999999999999999999" }) + ); + }); + it("encodes __fixed__ object float from a bigNumber Object and retains precision", () => { + let bn = Encoder("bigNumber", "0.9999999999999999999999999999999"); + expect(JSON.stringify(Encoder("float", bn))).to.be( + JSON.stringify({ __fixed__: "0.999999999999999999999999999999" }) + ); + }); + it("fails to encode non-float values", () => { + expect(() => Encoder("float", true)).to.throwError(); + }); + }); + context("Boolean", () => { + it("encodes a boolean from a boolean", () => { + expect(Encoder("bool", true)).to.be(true); + expect(Encoder("bool", false)).to.be(false); + }); + it("encodes a boolean from a number", () => { + expect(Encoder("bool", 1)).to.be(true); + expect(Encoder("bool", 0)).to.be(false); + }); + it("encodes a boolean from a string", () => { + expect(Encoder("bool", "true")).to.be(true); + expect(Encoder("bool", "false")).to.be(false); + }); + it("fails to encode non-boolean values", () => { + expect(() => Encoder("bool", "nope")).to.throwError(); + expect(() => Encoder("bool", 2)).to.throwError(); + expect(() => Encoder("bool", {})).to.throwError(); + }); + }); + context("Dict Object", () => { + it("encodes a dict from an Object", () => { + expect(JSON.stringify(Encoder("dict", {}))).to.be(JSON.stringify({})); + }); + it("encodes a dict from a string", () => { + expect( + JSON.stringify( + Encoder( + "dict", + '{"vk":"833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7"}' + ) + ) + ).to.be( + JSON.stringify({ vk: "833f3f66de0da4599ca60ae7854256f37404f543cf7a97c328d38aff9d3f8ac7" }) + ); + }); + it("encodes datetime and float inside a dict from a string", () => { + expect(JSON.stringify(Encoder("dict", { datetime: new Date(dateString), float: 1.1 }))).to.be( + '{"datetime":{"__time__":[2020,6,28,19,16,35,59]},"float":{"__fixed__":"1.1"}}' + ); + }); + it("replaces datetime object with value in dict", () => { + expect( + JSON.stringify(Encoder("dict", { DateTime: { datetime: new Date(dateString) } })) + ).to.be('{"DateTime":{"__time__":[2020,6,28,19,16,35,59]}}'); + }); + it("replaces timedelta object with value in dict", () => { + expect(JSON.stringify(Encoder("dict", { TimeDelta: { timedelta: 1000 } }))).to.be( + '{"TimeDelta":{"__delta__":[0,1]}}' + ); + }); + it("fails to encode non-objects", () => { + expect(() => Encoder("dict", undefined)).to.throwError(); + }); + }); - context('List Object', () => { - it('encodes a list from a list', () => { - expect( JSON.stringify(Encoder('list', [])) ).to.be( JSON.stringify([]) ) - }) - it('encodes a list from a string', () => { - expect( JSON.stringify(Encoder('list', '[]')) ).to.be( JSON.stringify([]) ) - }) - it('encodes a mixed list', () => { - expect( JSON.stringify(Encoder('list', ["1.1", 2])) ).to.be( JSON.stringify([{"__fixed__":"1.1"},2]) ) - }) - it('encodes fixed and datetime values in the list', () => { - expect( JSON.stringify(Encoder('list', [ 1.1, {'datetime':new Date(dateString)}] )) ) - .to.be( '[{"__fixed__":"1.1"},{"__time__":[2020,6,28,19,16,35,59]}]' ) - }) - it('encodes a list of all values and encodes accordingly', () => { - let testList = [1, 1.1, "string", {'datetime':new Date(dateString)}, {'timedelta':1000}, {'TimeDelta':{'timedelta':1000}}, true, [1.1]] - expect( JSON.stringify(Encoder('list', testList)) ) - .to.be( '[1,{"__fixed__":"1.1"},"string",{"__time__":[2020,6,28,19,16,35,59]},{"__delta__":[0,1]},{"TimeDelta":{"__delta__":[0,1]}},true,[{"__fixed__":"1.1"}]]' ) - }) - it('fails to encode non-list', () => { - expect(() => Encoder('list', {})).to.throwError(); - }) - }) + context("List Object", () => { + it("encodes a list from a list", () => { + expect(JSON.stringify(Encoder("list", []))).to.be(JSON.stringify([])); + }); + it("encodes a list from a string", () => { + expect(JSON.stringify(Encoder("list", "[]"))).to.be(JSON.stringify([])); + }); + it("encodes a mixed list", () => { + expect(JSON.stringify(Encoder("list", ["1.1", 2]))).to.be( + JSON.stringify([{ __fixed__: "1.1" }, 2]) + ); + }); + it("encodes fixed and datetime values in the list", () => { + expect(JSON.stringify(Encoder("list", [1.1, { datetime: new Date(dateString) }]))).to.be( + '[{"__fixed__":"1.1"},{"__time__":[2020,6,28,19,16,35,59]}]' + ); + }); + it("encodes a list of all values and encodes accordingly", () => { + let testList = [ + 1, + 1.1, + "string", + { datetime: new Date(dateString) }, + { timedelta: 1000 }, + { TimeDelta: { timedelta: 1000 } }, + true, + [1.1], + ]; + expect(JSON.stringify(Encoder("list", testList))).to.be( + '[1,{"__fixed__":"1.1"},"string",{"__time__":[2020,6,28,19,16,35,59]},{"__delta__":[0,1]},{"TimeDelta":{"__delta__":[0,1]}},true,[{"__fixed__":"1.1"}]]' + ); + }); + it("fails to encode non-list", () => { + expect(() => Encoder("list", {})).to.throwError(); + }); + }); - context('Any Object', () => { - it('Any does not do any encoding', () => { - expect( Encoder('Any', 'string') ).to.be( 'string' ) - expect( Encoder('Any', 1) ).to.be( 1 ) - expect( Encoder('Any', 1.23456) ).to.be( 1.23456 ) - expect( Encoder('Any', true) ).to.be( true ) - expect( Encoder('Any', new Date(dateString).toUTCString()) ).to.be( new Date(dateString).toUTCString() ) - expect( JSON.stringify(Encoder('Any', {})) ).to.be( JSON.stringify({}) ) - expect( JSON.stringify(Encoder('Any', [])) ).to.be( JSON.stringify([]) ) - }) - }) + context("Any Object", () => { + it("Any does not do any encoding", () => { + expect(Encoder("Any", "string")).to.be("string"); + expect(Encoder("Any", 1)).to.be(1); + expect(Encoder("Any", 1.23456)).to.be(1.23456); + expect(Encoder("Any", true)).to.be(true); + expect(Encoder("Any", new Date(dateString).toUTCString())).to.be( + new Date(dateString).toUTCString() + ); + expect(JSON.stringify(Encoder("Any", {}))).to.be(JSON.stringify({})); + expect(JSON.stringify(Encoder("Any", []))).to.be(JSON.stringify([])); + }); + }); - context('DateTime', () => { - it('Encodes a Date into a value list', () => { - expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString))) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]})) - }) - it('Encodes a Date string into a value list', () => { - expect( JSON.stringify(Encoder('datetime.datetime', dateString)) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]})) - }) - it('Encodes milliseconds into a value list', () => { - expect( JSON.stringify(Encoder('datetime.datetime', new Date(dateString).getTime())) ).to.be(JSON.stringify({'__time__':[2020, 6, 28, 19, 16, 35, 59]})) - }) - }) + context("DateTime", () => { + it("Encodes a Date into a value list", () => { + expect(JSON.stringify(Encoder("datetime.datetime", new Date(dateString)))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + it("Encodes a Date string into a value list", () => { + expect(JSON.stringify(Encoder("datetime.datetime", dateString))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + it("Encodes milliseconds into a value list", () => { + expect(JSON.stringify(Encoder("datetime.datetime", new Date(dateString).getTime()))).to.be( + JSON.stringify({ __time__: [2020, 6, 28, 19, 16, 35, 59] }) + ); + }); + }); - context('TimeDelta', () => { - it('Encodes a Date into days seconds', () => { - expect( JSON.stringify(Encoder('datetime.timedelta', new Date(millisecondsDelta))) ).to.be(JSON.stringify({'__delta__':[5, 43200]})) - }) - it('Encodes a millisenconds into days seconds', () => { - expect( JSON.stringify(Encoder('datetime.timedelta', millisecondsDelta)) ).to.be(JSON.stringify({'__delta__':[5, 43200]})) - }) - }) + context("TimeDelta", () => { + it("Encodes a Date into days seconds", () => { + expect(JSON.stringify(Encoder("datetime.timedelta", new Date(millisecondsDelta)))).to.be( + JSON.stringify({ __delta__: [5, 43200] }) + ); + }); + it("Encodes a millisenconds into days seconds", () => { + expect(JSON.stringify(Encoder("datetime.timedelta", millisecondsDelta))).to.be( + JSON.stringify({ __delta__: [5, 43200] }) + ); + }); + }); - context('Stringify()- Parses object and encodes all values', () => { - let testObj = { - 'integer': 1, - 'float': 1.1, - 'list': [1, 1.1, "this is a string", true, [1,2,3,4,5,6,7], [0, 1234567], [1.1], {fixed: 1.1, 'DateTime':{'datetime': new Date(dateString)}, 'TimeDelta': {"datetime.timedelta": millisecondsDelta}}], - 'str': "this is a string", - 'bool': true, - 'datetime.datetime': new Date(dateString), - 'datetime.timedelta': millisecondsDelta - } - testObj.dict = JSON.parse(JSON.stringify(testObj)) - let encodedObj = JSON.stringify(Encoder('object', testObj)) + context("Stringify()- Parses object and encodes all values", () => { + let testObj = { + integer: 1, + float: 1.1, + list: [ + 1, + 1.1, + "this is a string", + true, + [1, 2, 3, 4, 5, 6, 7], + [0, 1234567], + [1.1], + { + fixed: 1.1, + DateTime: { datetime: new Date(dateString) }, + TimeDelta: { "datetime.timedelta": millisecondsDelta }, + }, + ], + str: "this is a string", + bool: true, + "datetime.datetime": new Date(dateString), + "datetime.timedelta": millisecondsDelta, + }; + testObj.dict = JSON.parse(JSON.stringify(testObj)); + let encodedObj = JSON.stringify(Encoder("object", testObj)); - it('encodes an string', () => { - expect( encodedObj.includes('"str":"this is a string"') ).to.be(true) - }) - it('encodes an integer', () => { - expect( encodedObj.includes('"integer":1') ).to.be(true) - }) - it('encodes a float', () => { - expect( encodedObj.includes('"float":{"__fixed__":"1.1"}') ).to.be(true) - }) - it('encodes an bool', () => { - expect( encodedObj.includes('"bool":true') ).to.be(true) - }) - it('encodes a datetime.datetime', () => { - expect( encodedObj.includes('"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]}') ).to.be(true) - }) - it('encodes an datetime.timdelta', () => { - expect( encodedObj.includes('"datetime.timedelta":{"__delta__":[5,43200]}') ).to.be(true) - }) - it('encodes an list', () => { - expect( - encodedObj - .includes('"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}]') ) - .to.be(true) - }) - it('encodes a dict/object', () => { - expect( - encodedObj - .includes('"dict":{"integer":1,"float":{"__fixed__":"1.1"},"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}],"str":"this is a string","bool":true,"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]},"datetime.timedelta":{"__delta__":[5,43200]}}') ) - .to.be(true) - }) - }) -}) \ No newline at end of file + it("encodes an string", () => { + expect(encodedObj.includes('"str":"this is a string"')).to.be(true); + }); + it("encodes an integer", () => { + expect(encodedObj.includes('"integer":1')).to.be(true); + }); + it("encodes a float", () => { + expect(encodedObj.includes('"float":{"__fixed__":"1.1"}')).to.be(true); + }); + it("encodes an bool", () => { + expect(encodedObj.includes('"bool":true')).to.be(true); + }); + it("encodes a datetime.datetime", () => { + expect(encodedObj.includes('"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]}')).to.be( + true + ); + }); + it("encodes an datetime.timdelta", () => { + expect(encodedObj.includes('"datetime.timedelta":{"__delta__":[5,43200]}')).to.be(true); + }); + it("encodes an list", () => { + expect( + encodedObj.includes( + '"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}]' + ) + ).to.be(true); + }); + it("encodes a dict/object", () => { + expect( + encodedObj.includes( + '"dict":{"integer":1,"float":{"__fixed__":"1.1"},"list":[1,{"__fixed__":"1.1"},"this is a string",true,[1,2,3,4,5,6,7],[0,1234567],[{"__fixed__":"1.1"}],{"fixed":{"__fixed__":"1.1"},"DateTime":{"__time__":[2020,6,28,19,16,35,59]},"TimeDelta":{"__delta__":[5,43200]}}],"str":"this is a string","bool":true,"datetime.datetime":{"__time__":[2020,6,28,19,16,35,59]},"datetime.timedelta":{"__delta__":[5,43200]}}' + ) + ).to.be(true); + }); + }); +}); diff --git a/test/keystore-test.js b/test/keystore-test.js index 10e4411..6e0ce78 100644 --- a/test/keystore-test.js +++ b/test/keystore-test.js @@ -1,264 +1,249 @@ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); -const validators = require('types-validate-assert') +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); +const validators = require("types-validate-assert"); const { validateTypes, assertTypes } = validators; const { wallet } = Lamden; -const KEYSTORE_PASSWORD = "Testing010203" -const KEYSTORE_HINT = "Testing010203" +const KEYSTORE_PASSWORD = "Testing010203"; +const KEYSTORE_HINT = "Testing010203"; // Overwritted in "createKeystore() - Can create a keystore" let KEYSTORE_DATA = { - data: '{"ct":"s6M4AvQvklttEyGq5ebPj/PzAmjNtV6wlS9X8L0RCoZiaqyOz0Y80eZbdf1WRv7gm4Y9aN4vPEoU4oNVVbXoT7QYhuaxMZ+XUyPihcOOnxxmMMGckWD9QOROSgLovvm5yZxp6C2G47dWp7QLkJvubuPgZ+Ws0uexLnkvxXnCikwdZ20yUAFwGN+u3RhQvmgFagCLeuViFXSOtfkDRXmzX4k/7P6cWet8j5rn5gCBbOYHq8rFOxc34ihdhE/8N+x+3MyxGYk2QmwyfzTE9jDEXZwWRlz4GtMXi29ZccRi0z2XEeB7yBl1LTLvngpQM2QnCcX0AQNjHqlPb30bZtQD5shwzgNiRKRon41tKBAH7uvTjw6N39DVIABUkQCusQ1dWWkuvkt79kPjKI/oRF3RH101kXbejFLfDy0eXNUcV3U=","iv":"14e2a23a66fae00bb201f013e9ae1699","s":"5f4b1877b9d4235e"}', - w: 'U2FsdGVkX19RU+1vmxcY5wDfbkn1Gq8zOsh9Y4ylvSs=' -} + data: '{"ct":"s6M4AvQvklttEyGq5ebPj/PzAmjNtV6wlS9X8L0RCoZiaqyOz0Y80eZbdf1WRv7gm4Y9aN4vPEoU4oNVVbXoT7QYhuaxMZ+XUyPihcOOnxxmMMGckWD9QOROSgLovvm5yZxp6C2G47dWp7QLkJvubuPgZ+Ws0uexLnkvxXnCikwdZ20yUAFwGN+u3RhQvmgFagCLeuViFXSOtfkDRXmzX4k/7P6cWet8j5rn5gCBbOYHq8rFOxc34ihdhE/8N+x+3MyxGYk2QmwyfzTE9jDEXZwWRlz4GtMXi29ZccRi0z2XEeB7yBl1LTLvngpQM2QnCcX0AQNjHqlPb30bZtQD5shwzgNiRKRon41tKBAH7uvTjw6N39DVIABUkQCusQ1dWWkuvkt79kPjKI/oRF3RH101kXbejFLfDy0eXNUcV3U=","iv":"14e2a23a66fae00bb201f013e9ae1699","s":"5f4b1877b9d4235e"}', + w: "U2FsdGVkX19RU+1vmxcY5wDfbkn1Gq8zOsh9Y4ylvSs=", +}; -const keyPairs = [wallet.new_wallet(), wallet.new_wallet()] +const keyPairs = [wallet.new_wallet(), wallet.new_wallet()]; const keyList = [ - { - sk: keyPairs[0].sk, - nickname: "key1", - name: "lamden", - network: "lamden", - symbol: "TAU" - }, - { - sk: keyPairs[1].sk, - nickname: "key2", - name: "lamden", - network: "lamden", - symbol: "TAU" - } + { + sk: keyPairs[0].sk, + nickname: "key1", + name: "lamden", + network: "lamden", + symbol: "TAU", + }, + { + sk: keyPairs[1].sk, + nickname: "key2", + name: "lamden", + network: "lamden", + symbol: "TAU", + }, +]; -] +describe("Test Lamden Keystore Class", () => { + context("keystore construcutor: ", () => { + it("creates an instance with no constructor arguments", () => { + let keystore = new Lamden.Keystore(); + assertTypes.isSpecificClass(keystore, "Keystore"); + expect(keystore.keyList.numOfKeys()).to.be(0); + expect(keystore.keyList.getWallets().length).to.be(0); + }); + it("creates an instance by passing a string to the key property", () => { + let keystore = new Lamden.Keystore({ key: keyList[0] }); + assertTypes.isSpecificClass(keystore, "Keystore"); + expect(keystore.keyList.numOfKeys()).to.be(1); + expect(keystore.keyList.getWallets().length).to.be(1); + }); + it("creates an instance by passing an array to the keys property", () => { + let keystore = new Lamden.Keystore({ keyList }); + assertTypes.isSpecificClass(keystore, "Keystore"); + expect(keystore.keyList.numOfKeys()).to.be(2); + expect(keystore.keyList.getWallets().length).to.be(2); + }); + it("creates an instance by passing a keystoreData object", () => { + let keystore = new Lamden.Keystore({ keystoreData: KEYSTORE_DATA }); + assertTypes.isSpecificClass(keystore, "Keystore"); + assertTypes.isObjectWithKeys(keystore.encryptedData); + }); + it("creates an instance by passing a keystoreData string", () => { + let keystore = new Lamden.Keystore({ keystoreData: JSON.stringify(KEYSTORE_DATA) }); + assertTypes.isSpecificClass(keystore, "Keystore"); + assertTypes.isObjectWithKeys(keystore.encryptedData); + }); + it('NEGATIVE - Errors on "keyArg" not Array', () => { + expect(() => new Lamden.Keystore({ keyList: { key1: "key1" } })).throwException(); + }); + it("NEGATIVE - Errors on if array value is not type string", () => { + expect(() => new Lamden.Keystore({ keyList: [keyList[0], 2] })).throwException((e) => { + expect(e.message).to.be('Expected "2" to be [object Object] and have keys'); + }); + }); + }); + context("Adding Keys to the Keystore", () => { + it('addKey() - Can add a single key to the internal "keyList"', () => { + let keystore = new Lamden.Keystore(); + keystore.addKey(keyList[0]); + expect(keystore.keyList.numOfKeys()).to.be(1); + }); + it("NEGATIVE - addKey() - Errors if value passed is not type string", () => { + let keystore = new Lamden.Keystore(); + expect(() => keystore.addKey(1)).throwException((e) => { + expect(e.message).to.be('Expected "1" to be [object Object] and have keys'); + }); + }); + it('addKeys() - Can add to the internal "keyList" via an array of keys', () => { + let keystore = new Lamden.Keystore(); + keystore.addKeys(keyList); + expect(keystore.keyList.numOfKeys()).to.be(2); + }); + it("addKeys() - Wallets contain metadata", () => { + let keystore = new Lamden.Keystore(); + keystore.addKeys(keyList); + keystore.wallets.forEach((walletInfo, index) => { + expect(walletInfo.name).to.be(keyList[index].name); + expect(walletInfo.nickname).to.be(keyList[index].nickname); + expect(walletInfo.network).to.be(keyList[index].network); + expect(walletInfo.symbol).to.be(keyList[index].symbol); + }); + }); + it("NEGATIVE - addKeys() - Errors if value passed is not type array", () => { + let keystore = new Lamden.Keystore(); + expect(() => keystore.addKeys({ key1: "key1", key2: "key2" })).throwException((e) => { + expect(e.message).to.be("Expected type [object Array] but got [object Object]"); + }); + }); + }); + context("Deleting Keys from the Keystore", () => { + it("deleteKey() - Can delete a key from the keystore", () => { + let keystore = new Lamden.Keystore({ keyList }); + keystore.deleteKey(0); + expect(keystore.wallets[0].vk).to.be(keyPairs[1].vk); + }); + it("NEGATIVE - deleteKey() - Errors if argument is not an integer", () => { + let keystore = new Lamden.Keystore({ keyList }); -describe('Test Lamden Keystore Class', () => { - context('keystore construcutor: ', () => { - it('creates an instance with no constructor arguments', () => { - let keystore = new Lamden.Keystore() - assertTypes.isSpecificClass(keystore, "Keystore") - expect( keystore.keyList.numOfKeys() ).to.be( 0 ) - expect( keystore.keyList.getWallets().length ).to.be( 0 ) - }) - it('creates an instance by passing a string to the key property', () => { - let keystore = new Lamden.Keystore({key:keyList[0]}) - assertTypes.isSpecificClass(keystore, "Keystore") - expect( keystore.keyList.numOfKeys() ).to.be( 1 ) - expect( keystore.keyList.getWallets().length ).to.be( 1 ) - }) - it('creates an instance by passing an array to the keys property', () => { - let keystore = new Lamden.Keystore({keyList}) - assertTypes.isSpecificClass(keystore, "Keystore") - expect( keystore.keyList.numOfKeys() ).to.be( 2 ) - expect( keystore.keyList.getWallets().length ).to.be( 2 ) - }) - it('creates an instance by passing a keystoreData object', () => { - let keystore = new Lamden.Keystore({keystoreData: KEYSTORE_DATA}) - assertTypes.isSpecificClass(keystore, "Keystore") - assertTypes.isObjectWithKeys(keystore.encryptedData) - }) - it('creates an instance by passing a keystoreData string', () => { - let keystore = new Lamden.Keystore({keystoreData: JSON.stringify(KEYSTORE_DATA)}) - assertTypes.isSpecificClass(keystore, "Keystore") - assertTypes.isObjectWithKeys(keystore.encryptedData) - }) - it('NEGATIVE - Errors on "keyArg" not Array', () => { - expect(() => new Lamden.Keystore({keyList: {key1: "key1"}})).throwException(); - }) - it('NEGATIVE - Errors on if array value is not type string', () => { - expect(() => new Lamden.Keystore({keyList: [keyList[0], 2]})) - .throwException((e) => { - expect(e.message).to.be('Expected "2" to be [object Object] and have keys'); - }); - }) - }) - context('Adding Keys to the Keystore', () => { - it('addKey() - Can add a single key to the internal "keyList"', () => { - let keystore = new Lamden.Keystore() - keystore.addKey(keyList[0]) - expect( keystore.keyList.numOfKeys() ).to.be( 1 ) - }) - it('NEGATIVE - addKey() - Errors if value passed is not type string', () => { - let keystore = new Lamden.Keystore() - expect(() => keystore.addKey(1)) - .throwException((e) => { - expect(e.message).to.be('Expected "1" to be [object Object] and have keys'); - }); - }) - it('addKeys() - Can add to the internal "keyList" via an array of keys', () => { - let keystore = new Lamden.Keystore() - keystore.addKeys(keyList) - expect( keystore.keyList.numOfKeys() ).to.be( 2 ) - }) - it('addKeys() - Wallets contain metadata', () => { - let keystore = new Lamden.Keystore() - keystore.addKeys(keyList) - keystore.wallets.forEach((walletInfo, index) => { - expect(walletInfo.name ).to.be( keyList[index].name ) - expect(walletInfo.nickname ).to.be( keyList[index].nickname ) - expect(walletInfo.network ).to.be( keyList[index].network ) - expect(walletInfo.symbol ).to.be( keyList[index].symbol ) - }) - - }) - it('NEGATIVE - addKeys() - Errors if value passed is not type array', () => { - let keystore = new Lamden.Keystore() - expect(() => keystore.addKeys({key1: "key1", key2: "key2"})) - .throwException((e) => { - expect(e.message).to.be("Expected type [object Array] but got [object Object]"); - }); - }) - }) - context('Deleting Keys from the Keystore', () => { - it('deleteKey() - Can delete a key from the keystore', () => { - let keystore = new Lamden.Keystore({keyList}) - keystore.deleteKey(0) - expect( keystore.wallets[0].vk ).to.be( keyPairs[1].vk ) - }) - it('NEGATIVE - deleteKey() - Errors if argument is not an integer', () => { - let keystore = new Lamden.Keystore({keyList}) - - expect(() => keystore.deleteKey(0.3)) - .throwException((e) => { - expect(e.message).to.be('Expected "0.3" to be an integer but got non-integer value'); - }); - }) - it('NEGATIVE - deleteKey() - Errors if index is out of range, high', () => { - let keystore = new Lamden.Keystore({keyList}) - expect(() => keystore.deleteKey(2)) - .throwException((e) => { - expect(e.message).to.be("Key index out of range."); - }); - }) - it('NEGATIVE - deleteKey() - Errors if index is out of range, low', () => { - let keystore = new Lamden.Keystore({keyList}) - expect(() => keystore.deleteKey(-1)) - .throwException((e) => { - expect(e.message).to.be("Key index out of range."); - }); - }) - it('NEGATIVE - deleteKey() - Funtion returns no keys in list', () => { - let keystore = new Lamden.Keystore() - keystore.deleteKey(0) - }) - }) - context('Using keystore wallets', () => { - it('keystore.wallets - Deletes keys from the keystore', () => { - let keystore = new Lamden.Keystore({keyList}) - expect( keystore.wallets.length ).to.be( 2 ) - }) - it('getWallet() - Can get a specific wallet', () => { - let keystore = new Lamden.Keystore({keyList}) - let keystoreWallet = keystore.getWallet(keystore.wallets[0].vk) - expect(keystoreWallet).to.have.property('sign') - expect(keystoreWallet).to.have.property('verify') - expect(keystoreWallet).to.have.property('vk') - expect(() => assertTypes.isStringHex(keystoreWallet.sk)).throwException(); - }) - }) - context('Clearing a keystore', () => { - it('clearKeys() - Deletes keys from the keystore', () => { - let keystore = new Lamden.Keystore() - keystore.addKey(keyList[0]) - expect( keystore.keyList.numOfKeys() ).to.be( 1 ) - keystore.clearKeys() - expect( keystore.keyList.numOfKeys() ).to.be( 0 ) - }) - }) - context('Creating a Keystore', () => { - it('createKeystore() - Can create a keystore', () => { - let keystore = new Lamden.Keystore({keyList}) - let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD, KEYSTORE_HINT) - let keystoreObj = JSON.parse(encryptedKeystore) - KEYSTORE_DATA = JSON.parse(encryptedKeystore) - expect(keystoreObj).to.have.property('data') - assertTypes.isStringWithValue(keystoreObj.data) - expect(keystoreObj).to.have.property('w') - assertTypes.isStringWithValue(keystoreObj.w) - }) - it('createKeystore() - Can create a keystore without "hint"', () => { - let keystore = new Lamden.Keystore({keyList}) - let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD) - let keystoreObj = JSON.parse(encryptedKeystore) + expect(() => keystore.deleteKey(0.3)).throwException((e) => { + expect(e.message).to.be('Expected "0.3" to be an integer but got non-integer value'); + }); + }); + it("NEGATIVE - deleteKey() - Errors if index is out of range, high", () => { + let keystore = new Lamden.Keystore({ keyList }); + expect(() => keystore.deleteKey(2)).throwException((e) => { + expect(e.message).to.be("Key index out of range."); + }); + }); + it("NEGATIVE - deleteKey() - Errors if index is out of range, low", () => { + let keystore = new Lamden.Keystore({ keyList }); + expect(() => keystore.deleteKey(-1)).throwException((e) => { + expect(e.message).to.be("Key index out of range."); + }); + }); + it("NEGATIVE - deleteKey() - Funtion returns no keys in list", () => { + let keystore = new Lamden.Keystore(); + keystore.deleteKey(0); + }); + }); + context("Using keystore wallets", () => { + it("keystore.wallets - Deletes keys from the keystore", () => { + let keystore = new Lamden.Keystore({ keyList }); + expect(keystore.wallets.length).to.be(2); + }); + it("getWallet() - Can get a specific wallet", () => { + let keystore = new Lamden.Keystore({ keyList }); + let keystoreWallet = keystore.getWallet(keystore.wallets[0].vk); + expect(keystoreWallet).to.have.property("sign"); + expect(keystoreWallet).to.have.property("verify"); + expect(keystoreWallet).to.have.property("vk"); + expect(() => assertTypes.isStringHex(keystoreWallet.sk)).throwException(); + }); + }); + context("Clearing a keystore", () => { + it("clearKeys() - Deletes keys from the keystore", () => { + let keystore = new Lamden.Keystore(); + keystore.addKey(keyList[0]); + expect(keystore.keyList.numOfKeys()).to.be(1); + keystore.clearKeys(); + expect(keystore.keyList.numOfKeys()).to.be(0); + }); + }); + context("Creating a Keystore", () => { + it("createKeystore() - Can create a keystore", () => { + let keystore = new Lamden.Keystore({ keyList }); + let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD, KEYSTORE_HINT); + let keystoreObj = JSON.parse(encryptedKeystore); + KEYSTORE_DATA = JSON.parse(encryptedKeystore); + expect(keystoreObj).to.have.property("data"); + assertTypes.isStringWithValue(keystoreObj.data); + expect(keystoreObj).to.have.property("w"); + assertTypes.isStringWithValue(keystoreObj.w); + }); + it('createKeystore() - Can create a keystore without "hint"', () => { + let keystore = new Lamden.Keystore({ keyList }); + let encryptedKeystore = keystore.createKeystore(KEYSTORE_PASSWORD); + let keystoreObj = JSON.parse(encryptedKeystore); - expect(keystoreObj).to.have.property('data') - assertTypes.isStringWithValue(keystoreObj.data) + expect(keystoreObj).to.have.property("data"); + assertTypes.isStringWithValue(keystoreObj.data); - expect(keystoreObj).to.have.property('w') - assertTypes.isString(keystoreObj.w) + expect(keystoreObj).to.have.property("w"); + assertTypes.isString(keystoreObj.w); - expect(() => assertTypes.isStringWithValue(keystoreObj.w)) - .throwException((e) => { - expect(e.message).to.be('Expected "" to be [object String] and not empty'); - }); - - }) - it('NEGATIVE - createKeystore() - Errors if "password" value passed is not type string', () => { - let keystore = new Lamden.Keystore({keyList}) - expect(() => keystore.createKeystore(12345)) - .throwException((e) => { - expect(e.message).to.be('Expected "12345" to be [object String] and not empty'); - }); - }) - it('NEGATIVE - createKeystore() - Errors if a non-string value for "hint" is provided', () => { - let keystore = new Lamden.Keystore({keyList}) - expect(() => keystore.createKeystore(KEYSTORE_PASSWORD, 12345)) - .throwException((e) => { - expect(e.message).to.be('Expected "12345" to be [object String] and not empty'); - }); - }) - }) + expect(() => assertTypes.isStringWithValue(keystoreObj.w)).throwException((e) => { + expect(e.message).to.be('Expected "" to be [object String] and not empty'); + }); + }); + it('NEGATIVE - createKeystore() - Errors if "password" value passed is not type string', () => { + let keystore = new Lamden.Keystore({ keyList }); + expect(() => keystore.createKeystore(12345)).throwException((e) => { + expect(e.message).to.be('Expected "12345" to be [object String] and not empty'); + }); + }); + it('NEGATIVE - createKeystore() - Errors if a non-string value for "hint" is provided', () => { + let keystore = new Lamden.Keystore({ keyList }); + expect(() => keystore.createKeystore(KEYSTORE_PASSWORD, 12345)).throwException((e) => { + expect(e.message).to.be('Expected "12345" to be [object String] and not empty'); + }); + }); + }); - context('Keystore password hints', () => { - it('getPasswordHint() - Can get the hint from the keystore instance', () => { - let keystore = new Lamden.Keystore({keystoreData: KEYSTORE_DATA}) - let hint = keystore.getPasswordHint() - expect( hint ).to.be( KEYSTORE_HINT ) - }) - it('getPasswordHint() - Can get the hint from a supplied keystore', () => { - let keystore = new Lamden.Keystore() - let hint = keystore.getPasswordHint(KEYSTORE_DATA) - expect( hint ).to.be( KEYSTORE_HINT ) - }) - it('getPasswordHint() - Can get the hint from a supplied string keystore', () => { - let keystore = new Lamden.Keystore() - let hint = keystore.getPasswordHint(JSON.stringify(KEYSTORE_DATA)) - expect( hint ).to.be( KEYSTORE_HINT ) - }) - }) - context('Decrypting a Keystore', () => { - it('decryptKeystore() - Can decrypte a keystore', () => { - let keystore = new Lamden.Keystore({keystoreData: KEYSTORE_DATA}) - keystore.decryptKeystore(KEYSTORE_PASSWORD) - expect( keystore.keyList.numOfKeys() ).to.be( 2 ) - expect( keystore.version ).to.be( "1.0" ) - }) - it('decryptKeystore() - Can decrypte a keystore passed as a string', () => { - let keystore = new Lamden.Keystore({keystoreData: JSON.stringify(KEYSTORE_DATA)}) - keystore.decryptKeystore(KEYSTORE_PASSWORD) - expect( keystore.keyList.numOfKeys() ).to.be( 2 ) - expect( keystore.version ).to.be( "1.0" ) - }) - it('decryptKeystore() - Can decrypt a provided keystore', () => { - let keystore = new Lamden.Keystore() - keystore.decryptKeystore(KEYSTORE_PASSWORD, KEYSTORE_DATA) - expect( keystore.keyList.numOfKeys() ).to.be( 2 ) - expect( keystore.version ).to.be( "1.0" ) - }) - it('NEGATIVE - decryptKeystore() - Reports Incorrect Password', () => { - let keystore = new Lamden.Keystore() - expect(() => keystore.decryptKeystore("Nope", KEYSTORE_DATA)) - .throwException((e) => { - expect(e.message).to.be('Incorrect Keystore Password.'); - }); - }) - it('NEGATIVE - decryptKeystore() - Errors if no keystoreData found', () => { - let keystore = new Lamden.Keystore() - expect(() => keystore.decryptKeystore(KEYSTORE_PASSWORD)) - .throwException((e) => { - expect(e.message).to.be('No keystoreData to decrypt.'); - }); - }) - }) - -}) + context("Keystore password hints", () => { + it("getPasswordHint() - Can get the hint from the keystore instance", () => { + let keystore = new Lamden.Keystore({ keystoreData: KEYSTORE_DATA }); + let hint = keystore.getPasswordHint(); + expect(hint).to.be(KEYSTORE_HINT); + }); + it("getPasswordHint() - Can get the hint from a supplied keystore", () => { + let keystore = new Lamden.Keystore(); + let hint = keystore.getPasswordHint(KEYSTORE_DATA); + expect(hint).to.be(KEYSTORE_HINT); + }); + it("getPasswordHint() - Can get the hint from a supplied string keystore", () => { + let keystore = new Lamden.Keystore(); + let hint = keystore.getPasswordHint(JSON.stringify(KEYSTORE_DATA)); + expect(hint).to.be(KEYSTORE_HINT); + }); + }); + context("Decrypting a Keystore", () => { + it("decryptKeystore() - Can decrypte a keystore", () => { + let keystore = new Lamden.Keystore({ keystoreData: KEYSTORE_DATA }); + keystore.decryptKeystore(KEYSTORE_PASSWORD); + expect(keystore.keyList.numOfKeys()).to.be(2); + expect(keystore.version).to.be("1.0"); + }); + it("decryptKeystore() - Can decrypte a keystore passed as a string", () => { + let keystore = new Lamden.Keystore({ keystoreData: JSON.stringify(KEYSTORE_DATA) }); + keystore.decryptKeystore(KEYSTORE_PASSWORD); + expect(keystore.keyList.numOfKeys()).to.be(2); + expect(keystore.version).to.be("1.0"); + }); + it("decryptKeystore() - Can decrypt a provided keystore", () => { + let keystore = new Lamden.Keystore(); + keystore.decryptKeystore(KEYSTORE_PASSWORD, KEYSTORE_DATA); + expect(keystore.keyList.numOfKeys()).to.be(2); + expect(keystore.version).to.be("1.0"); + }); + it("NEGATIVE - decryptKeystore() - Reports Incorrect Password", () => { + let keystore = new Lamden.Keystore(); + expect(() => keystore.decryptKeystore("Nope", KEYSTORE_DATA)).throwException((e) => { + expect(e.message).to.be("Incorrect Keystore Password."); + }); + }); + it("NEGATIVE - decryptKeystore() - Errors if no keystoreData found", () => { + let keystore = new Lamden.Keystore(); + expect(() => keystore.decryptKeystore(KEYSTORE_PASSWORD)).throwException((e) => { + expect(e.message).to.be("No keystoreData to decrypt."); + }); + }); + }); +}); diff --git a/test/masternode_api-test.js b/test/masternode_api-test.js index 0a9c62d..dfb3750 100644 --- a/test/masternode_api-test.js +++ b/test/masternode_api-test.js @@ -1,207 +1,212 @@ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); const { Masternode_API, wallet } = Lamden; let goodNetwork = { - type: 'testnet', - name: 'Lamden Public Testnet', - hosts: ['https://testnet-master-1.lamden.io:443'] -} -let goodNetwork_api = new Masternode_API(goodNetwork) + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], +}; +let goodNetwork_api = new Masternode_API(goodNetwork); let badNetwork = { - type: 'testnet', - name: 'Bad Network', - hosts: ['http://badnetwork.lamden.io:18080'] -} + type: "testnet", + name: "Bad Network", + hosts: ["http://badnetwork.lamden.io:18080"], +}; -let badNetwork_api = new Masternode_API(badNetwork) +let badNetwork_api = new Masternode_API(badNetwork); -function copyObject(object){ - return JSON.parse(JSON.stringify(object)) +function copyObject(object) { + return JSON.parse(JSON.stringify(object)); } -let keyPair = wallet.new_wallet() +let keyPair = wallet.new_wallet(); const balanceCheckWallet = { - float: '960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb', - int: '01930f6472916ae53c9ebbe7d3faf8979c24cac33d68041aa4ab986401bbf7c3' -} - -describe('Test Masternode API returns', () => { - context('constructor', () => { - it('can create an instance', () => { - let api = new Masternode_API(goodNetwork) - expect(api).to.exist; - expect(JSON.stringify(api.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); - expect(api.url).to.be(goodNetwork.hosts[0]); - }) - it('rejects arg not being an object', () => { - let error; - try{ - new Masternode_API('https://testnet.lamden.io:443') - } catch (e) {error = e} - expect(error.message).to.be('Expected Object and got Type: string') - }) - it('rejects missing hosts Array', () => { - let error; - try{ - let networkInfo = copyObject(goodNetwork) - networkInfo.hosts = [] - new Masternode_API(networkInfo) - } catch (e) {error = e} - expect(error.message).to.be('HOSTS Required (Type: Array)') - - }) - it('rejects no protocol in host string', () => { - let error; - try{ - let networkInfo = copyObject(goodNetwork) - networkInfo.hosts = ['missing.protocol.com'] - new Masternode_API(networkInfo) - } catch (e) {error = e} - expect(error.message).to.be('Host String must include http:// or https://') - }) - }) - - context('Masternode_API.pingServer()', () => { - it('returns true if the server is online', async () => { - let response = await goodNetwork_api.pingServer() - expect(response).to.be(true); - }) - it('returns false if provided network is unresponsive', async () => { - let response = await badNetwork_api.pingServer() - expect(response).to.be(false); - }) - }) - - context('Masternode_API.getCurrencyBalance()', () => { - it('returns the float balance for a vk', async () => { - let response = await goodNetwork_api.getCurrencyBalance(balanceCheckWallet.float) - expect(response).to.be.above(0); - }) - it('returns the int balance for a vk', async () => { - let response = await goodNetwork_api.getCurrencyBalance(balanceCheckWallet.int) - expect(response).to.be.above(0); - }) - it('returns 0 if the vk does not exist yet', async () => { - let response = await goodNetwork_api.getCurrencyBalance(wallet.new_wallet().vk) - expect(response.toNumber()).to.be(0); - }) - it('returns 0 if provided network is unresponsive', async () => { - let response = await badNetwork_api.getCurrencyBalance() - expect(response.toNumber()).to.be(0); - }) - }) - - context('Masternode_API.contractExists()', () => { - it('returns true if a contract exists on the blockchain', async () => { - let response = await goodNetwork_api.contractExists('currency') - expect(response).to.be(true); - }) - it('returns false if a contract does not exist on the blockchain', async () => { - let response = await goodNetwork_api.contractExists(wallet.new_wallet().vk) - expect(response).to.be(false); - }) - it('returns false if provided network is unresponsive', async () => { - let response = await badNetwork_api.contractExists('currency') - expect(response).to.be(false); - }) - }) - - context('Masternode_API.getContractMethods()', () => { - it('returns an array if a contract exists on the blockchain', async () => { - let response = await goodNetwork_api.getContractMethods('currency') - expect(Array.isArray(response)).to.be(true); - expect(response.length > 0).to.be(true); - }) - it('returns an empty array if a contract does not exist on the blockchain', async () => { - let response = await goodNetwork_api.getContractMethods(wallet.new_wallet().vk) - expect(Array.isArray(response)).to.be(true); - expect(response.length === 0).to.be(true); - }) - it('returns empty array if provided network is unresponsive', async () => { - let response = await badNetwork_api.getContractMethods('currency') - expect(Array.isArray(response)).to.be(true); - expect(response.length === 0).to.be(true); - }) - }) - - context('Masternode_API.getContractVariables()', () => { - it('returns an array if a contract exists on the blockchain', async () => { - let response = await goodNetwork_api.getContractVariables('currency') - expect(Array.isArray(response.variables)).to.be(true); - expect(Array.isArray(response.hashes)).to.be(true); - expect(response.hashes.length > 0).to.be(true); - }) - it('returns an empty Object if a contract does not exist on the blockchain', async () => { - let response = await goodNetwork_api.getContractVariables(wallet.new_wallet().vk) - expect(Array.isArray(response.variables)).to.be(false); - expect(Array.isArray(response.hashes)).to.be(false); - expect(Object.keys(response).length === 0).to.be(true); - }) - it('returns empty Object if provided network is unresponsive', async () => { - let response = await badNetwork_api.getContractVariables('currency') - expect(Array.isArray(response.variables)).to.be(false); - expect(Array.isArray(response.hashes)).to.be(false); - expect(Object.keys(response).length === 0).to.be(true); - }) - }) - - context('Masternode_API.getVariable()', () => { - it('returns the value of the variable if the key exists', async () => { - let key = balanceCheckWallet.float; - let response = await goodNetwork_api.getVariable('currency', 'balances', key) - expect(parseFloat(response.__fixed__)).to.be.above(0); - }) - it('returns undefined if the key does not exist in the variable', async () => { - let key = wallet.new_wallet().vk; - let response = await goodNetwork_api.getVariable('currency', 'balances', key) - expect(response).to.be(null); - }) - it('returns undefined if the contract does not exist', async () => { - let key = keyPair.vk; - let response = await goodNetwork_api.getVariable(wallet.new_wallet().vk, 'balances', key) - expect(response).to.be(null); - }) - it('returns undefined if the variable does not exist', async () => { - let key = keyPair.vk; - let response = await goodNetwork_api.getVariable('currency', wallet.new_wallet().vk, key) - expect(response).to.be(null); - }) - it('returns undefined if provided network is unresponsive', async () => { - let key = keyPair.vk; - let response = await badNetwork_api.getVariable('currency', 'balances', key) - expect(response).to.be(null); - }) - }) - - context('Masternode_API.getContractInfo()', () => { - it('returns a contract info object', async () => { - let response = await goodNetwork_api.getContractInfo('currency') - expect(response.name).to.be('currency'); - expect(response.code.length > 0).to.be(true); - }) - it('returns undefined if provided network is unresponsive', async () => { - let response = await badNetwork_api.getContractInfo('currency') - expect(response).to.be(null); - }) - }) - - context('Masternode_API.getNonce()', () => { - it('returns a nonce and processor value for a vk', async () => { - let response = await goodNetwork_api.getNonce(keyPair.vk) - expect(response.nonce).to.exist - expect(response.processor).to.exist - expect(response.sender).to.be(keyPair.vk) - }) - it('returns an error message if vk is not a hex string', async () => { - let error = await goodNetwork_api.getNonce('this-is-not-a-vk') - expect(error).to.be(`this-is-not-a-vk is not a hex string.`) - }) - it('returns an error message if provided network is unresponsive', async () => { - let error = await badNetwork_api.getNonce(keyPair.vk) - expect(error.includes(`Unable to get nonce for ${keyPair.vk}`)).to.be(true) - }) - }) -}) \ No newline at end of file + float: "960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb", + int: "01930f6472916ae53c9ebbe7d3faf8979c24cac33d68041aa4ab986401bbf7c3", +}; + +describe("Test Masternode API returns", () => { + context("constructor", () => { + it("can create an instance", () => { + let api = new Masternode_API(goodNetwork); + expect(api).to.exist; + expect(JSON.stringify(api.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); + expect(api.url).to.be(goodNetwork.hosts[0]); + }); + it("rejects arg not being an object", () => { + let error; + try { + new Masternode_API("https://testnet.lamden.io:443"); + } catch (e) { + error = e; + } + expect(error.message).to.be("Expected Object and got Type: string"); + }); + it("rejects missing hosts Array", () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = []; + new Masternode_API(networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.be("HOSTS Required (Type: Array)"); + }); + it("rejects no protocol in host string", () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = ["missing.protocol.com"]; + new Masternode_API(networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.be("Host String must include http:// or https://"); + }); + }); + + context("Masternode_API.pingServer()", () => { + it("returns true if the server is online", async () => { + let response = await goodNetwork_api.pingServer(); + expect(response).to.be(true); + }); + it("returns false if provided network is unresponsive", async () => { + let response = await badNetwork_api.pingServer(); + expect(response).to.be(false); + }); + }); + + context("Masternode_API.getCurrencyBalance()", () => { + it("returns the float balance for a vk", async () => { + let response = await goodNetwork_api.getCurrencyBalance(balanceCheckWallet.float); + expect(response).to.be.above(0); + }); + it("returns the int balance for a vk", async () => { + let response = await goodNetwork_api.getCurrencyBalance(balanceCheckWallet.int); + expect(response).to.be.above(0); + }); + it("returns 0 if the vk does not exist yet", async () => { + let response = await goodNetwork_api.getCurrencyBalance(wallet.new_wallet().vk); + expect(response.toNumber()).to.be(0); + }); + it("returns 0 if provided network is unresponsive", async () => { + let response = await badNetwork_api.getCurrencyBalance(); + expect(response.toNumber()).to.be(0); + }); + }); + + context("Masternode_API.contractExists()", () => { + it("returns true if a contract exists on the blockchain", async () => { + let response = await goodNetwork_api.contractExists("currency"); + expect(response).to.be(true); + }); + it("returns false if a contract does not exist on the blockchain", async () => { + let response = await goodNetwork_api.contractExists(wallet.new_wallet().vk); + expect(response).to.be(false); + }); + it("returns false if provided network is unresponsive", async () => { + let response = await badNetwork_api.contractExists("currency"); + expect(response).to.be(false); + }); + }); + + context("Masternode_API.getContractMethods()", () => { + it("returns an array if a contract exists on the blockchain", async () => { + let response = await goodNetwork_api.getContractMethods("currency"); + expect(Array.isArray(response)).to.be(true); + expect(response.length > 0).to.be(true); + }); + it("returns an empty array if a contract does not exist on the blockchain", async () => { + let response = await goodNetwork_api.getContractMethods(wallet.new_wallet().vk); + expect(Array.isArray(response)).to.be(true); + expect(response.length === 0).to.be(true); + }); + it("returns empty array if provided network is unresponsive", async () => { + let response = await badNetwork_api.getContractMethods("currency"); + expect(Array.isArray(response)).to.be(true); + expect(response.length === 0).to.be(true); + }); + }); + + context("Masternode_API.getContractVariables()", () => { + it("returns an array if a contract exists on the blockchain", async () => { + let response = await goodNetwork_api.getContractVariables("currency"); + expect(Array.isArray(response.variables)).to.be(true); + expect(Array.isArray(response.hashes)).to.be(true); + expect(response.hashes.length > 0).to.be(true); + }); + it("returns an empty Object if a contract does not exist on the blockchain", async () => { + let response = await goodNetwork_api.getContractVariables(wallet.new_wallet().vk); + expect(Array.isArray(response.variables)).to.be(false); + expect(Array.isArray(response.hashes)).to.be(false); + expect(Object.keys(response).length === 0).to.be(true); + }); + it("returns empty Object if provided network is unresponsive", async () => { + let response = await badNetwork_api.getContractVariables("currency"); + expect(Array.isArray(response.variables)).to.be(false); + expect(Array.isArray(response.hashes)).to.be(false); + expect(Object.keys(response).length === 0).to.be(true); + }); + }); + + context("Masternode_API.getVariable()", () => { + it("returns the value of the variable if the key exists", async () => { + let key = balanceCheckWallet.float; + let response = await goodNetwork_api.getVariable("currency", "balances", key); + expect(parseFloat(response.__fixed__)).to.be.above(0); + }); + it("returns undefined if the key does not exist in the variable", async () => { + let key = wallet.new_wallet().vk; + let response = await goodNetwork_api.getVariable("currency", "balances", key); + expect(response).to.be(null); + }); + it("returns undefined if the contract does not exist", async () => { + let key = keyPair.vk; + let response = await goodNetwork_api.getVariable(wallet.new_wallet().vk, "balances", key); + expect(response).to.be(null); + }); + it("returns undefined if the variable does not exist", async () => { + let key = keyPair.vk; + let response = await goodNetwork_api.getVariable("currency", wallet.new_wallet().vk, key); + expect(response).to.be(null); + }); + it("returns undefined if provided network is unresponsive", async () => { + let key = keyPair.vk; + let response = await badNetwork_api.getVariable("currency", "balances", key); + expect(response).to.be(null); + }); + }); + + context("Masternode_API.getContractInfo()", () => { + it("returns a contract info object", async () => { + let response = await goodNetwork_api.getContractInfo("currency"); + expect(response.name).to.be("currency"); + expect(response.code.length > 0).to.be(true); + }); + it("returns undefined if provided network is unresponsive", async () => { + let response = await badNetwork_api.getContractInfo("currency"); + expect(response).to.be(null); + }); + }); + + context("Masternode_API.getNonce()", () => { + it("returns a nonce and processor value for a vk", async () => { + let response = await goodNetwork_api.getNonce(keyPair.vk); + expect(response.nonce).to.exist; + expect(response.processor).to.exist; + expect(response.sender).to.be(keyPair.vk); + }); + it("returns an error message if vk is not a hex string", async () => { + let error = await goodNetwork_api.getNonce("this-is-not-a-vk"); + expect(error).to.be(`this-is-not-a-vk is not a hex string.`); + }); + it("returns an error message if provided network is unresponsive", async () => { + let error = await badNetwork_api.getNonce(keyPair.vk); + expect(error.includes(`Unable to get nonce for ${keyPair.vk}`)).to.be(true); + }); + }); +}); diff --git a/test/network-test.js b/test/network-test.js index 48e801f..167ad43 100644 --- a/test/network-test.js +++ b/test/network-test.js @@ -1,89 +1,94 @@ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); let goodNetwork = { - type: 'testnet', - name: 'Lamden Public Testnet', - hosts: ['https://testnet-master-1.lamden.io:443'] , - lamden: true, - blockExplorer: 'https://testnet.lamden.io' -} + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], + lamden: true, + blockExplorer: "https://testnet.lamden.io", +}; -function copyObject(object){ - return JSON.parse(JSON.stringify(object)) +function copyObject(object) { + return JSON.parse(JSON.stringify(object)); } -describe('Test Netowrk class', () => { - context('Constructor', () => { - it('can create an instance', () => { - let network = new Lamden.Network(goodNetwork) - expect(network).to.exist; - expect(JSON.stringify(network.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); - expect(network.host).to.be(goodNetwork.hosts[0]); - expect(network.url).to.be(goodNetwork.hosts[0]); - expect(network.type).to.be(goodNetwork.type); - expect(network.name).to.be(goodNetwork.name); - expect(network.lamden).to.be(goodNetwork.lamden); - expect(network.blockExplorer).to.be(goodNetwork.blockExplorer); - }) - - it('rejects missing hosts Array', () => { - let error; - try{ - let networkInfo = copyObject(goodNetwork) - delete networkInfo.hosts - new Lamden.Network(networkInfo) - } catch (e) {error = e} - expect(error.message).to.be('HOSTS Required (Type: Array)') +describe("Test Netowrk class", () => { + context("Constructor", () => { + it("can create an instance", () => { + let network = new Lamden.Network(goodNetwork); + expect(network).to.exist; + expect(JSON.stringify(network.hosts)).to.be(JSON.stringify(goodNetwork.hosts)); + expect(network.host).to.be(goodNetwork.hosts[0]); + expect(network.url).to.be(goodNetwork.hosts[0]); + expect(network.type).to.be(goodNetwork.type); + expect(network.name).to.be(goodNetwork.name); + expect(network.lamden).to.be(goodNetwork.lamden); + expect(network.blockExplorer).to.be(goodNetwork.blockExplorer); + }); - }) - it('rejects no protocol in host string', () => { - let error; - try{ - let networkInfo = copyObject(goodNetwork) - networkInfo.hosts = ['missing.protocol.com'] - new Lamden.Network(networkInfo) - } catch (e) {error = e} - expect(error.message).to.be('Host String must include http:// or https://') - }) - it('defaults missing type to custom', () => { - let networkInfo = copyObject(goodNetwork) - networkInfo.type = '' - let network = new Lamden.Network(networkInfo) - expect(network.type).to.be("custom"); - }) - it('rejects arg not being an object', () => { - let error; - try{ - new Lamden.Network('https://testnet-master-1.lamden.io:443') - } catch (e) {error = e} - expect(error.message).to.be('Expected Network Info Object and got Type: string') - }) - }) - context('Ping Network', () => { - it('emits online status', async () => { - function checkResult(result){ - expect(result).to.be(true) - } - let network = new Lamden.Network(goodNetwork) - network.events.on('online', (status) => checkResult(status)) - await network.ping(); - }) + it("rejects missing hosts Array", () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + delete networkInfo.hosts; + new Lamden.Network(networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.be("HOSTS Required (Type: Array)"); + }); + it("rejects no protocol in host string", () => { + let error; + try { + let networkInfo = copyObject(goodNetwork); + networkInfo.hosts = ["missing.protocol.com"]; + new Lamden.Network(networkInfo); + } catch (e) { + error = e; + } + expect(error.message).to.be("Host String must include http:// or https://"); + }); + it("defaults missing type to custom", () => { + let networkInfo = copyObject(goodNetwork); + networkInfo.type = ""; + let network = new Lamden.Network(networkInfo); + expect(network.type).to.be("custom"); + }); + it("rejects arg not being an object", () => { + let error; + try { + new Lamden.Network("https://testnet-master-1.lamden.io:443"); + } catch (e) { + error = e; + } + expect(error.message).to.be("Expected Network Info Object and got Type: string"); + }); + }); + context("Ping Network", () => { + it("emits online status", async () => { + function checkResult(result) { + expect(result).to.be(true); + } + let network = new Lamden.Network(goodNetwork); + network.events.on("online", (status) => checkResult(status)); + await network.ping(); + }); - it('return value from method return', async () => { - function checkResult(result){ - expect(result).to.be(true) - } - let network = new Lamden.Network(goodNetwork) - let status = await network.ping() - checkResult(status) - }) - it('returns online status through callback', async () => { - function checkResult(result){ - expect(result).to.be(true) - } - let network = new Lamden.Network(goodNetwork) - await network.ping(((status) => checkResult(status))) - }) - }) -}) \ No newline at end of file + it("return value from method return", async () => { + function checkResult(result) { + expect(result).to.be(true); + } + let network = new Lamden.Network(goodNetwork); + let status = await network.ping(); + checkResult(status); + }); + it("returns online status through callback", async () => { + function checkResult(result) { + expect(result).to.be(true); + } + let network = new Lamden.Network(goodNetwork); + await network.ping((status) => checkResult(status)); + }); + }); +}); diff --git a/test/transactionBatcher-test.js b/test/transactionBatcher-test.js index 1b302af..af8532b 100644 --- a/test/transactionBatcher-test.js +++ b/test/transactionBatcher-test.js @@ -3,66 +3,65 @@ The nonces won't increment properly depending on network lag and I don't have a good solution to it. */ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); let networkInfo = { - hosts: ['https://testnet-master-1.lamden.io:443'] -} + hosts: ["https://testnet-master-1.lamden.io:443"], +}; -let uid = "randomUIDstring" +let uid = "randomUIDstring"; const senderWallet1 = { - vk: "960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb", - sk: "c8a3c5333aa3b058c4fa16d48db52355ab62ddc8daa9a183706a912e522440b6" -} + vk: "960c002a36c30c3aec8bc670e9b8b40eebcfd545f4e9237579fd7395a21ccebb", + sk: "c8a3c5333aa3b058c4fa16d48db52355ab62ddc8daa9a183706a912e522440b6", +}; const senderWallet2 = { - vk: "6a91a9a65eb80829a360efc0555cad8841af64c78375bbf394f6ecb89d5644ee", - sk: "4166ed44f465c51d562895295cdcde64a3444b14ea2a3e477c60cf0ecde65230" -} + vk: "6a91a9a65eb80829a360efc0555cad8841af64c78375bbf394f6ecb89d5644ee", + sk: "4166ed44f465c51d562895295cdcde64a3444b14ea2a3e477c60cf0ecde65230", +}; let recieverWallet = { - vk: 'f16c130ceb7ed9bcebde301488cfd507717d5d511674bc269c39ad41fc15d780' -} + vk: "f16c130ceb7ed9bcebde301488cfd507717d5d511674bc269c39ad41fc15d780", +}; function sleep(milliseconds) { - const date = Date.now(); - let currentDate = null; - do { - currentDate = Date.now(); - } while (currentDate - date < milliseconds); - } - - -const makeTxList = (senderVK, receiver, amount) => { - let txList = [] - for(i = 0; i <= (amount - 1); i++){ - txList.push({ - uid, - senderVk: senderVK, - contractName: 'currency', - methodName: 'transfer', - kwargs:{ - 'to': receiver, - 'amount': {"__fixed__":"0.0005"} - }, - stampLimit: 500 - }) - } - return txList + const date = Date.now(); + let currentDate = null; + do { + currentDate = Date.now(); + } while (currentDate - date < milliseconds); } -let keyList = {} -keyList[senderWallet1.vk] = senderWallet1.sk -keyList[senderWallet2.vk] = senderWallet2.sk - -describe('Test TransactionBuilder class', () => { - context('new TransactionBuilder', () => { - it('can create an instance', () => { - let txb = new Lamden.TransactionBatcher(networkInfo) - expect(txb.running).to.be(false) - }) - })/* +const makeTxList = (senderVK, receiver, amount) => { + let txList = []; + for (i = 0; i <= amount - 1; i++) { + txList.push({ + uid, + senderVk: senderVK, + contractName: "currency", + methodName: "transfer", + kwargs: { + to: receiver, + amount: { __fixed__: "0.0005" }, + }, + stampLimit: 500, + }); + } + return txList; +}; + +let keyList = {}; +keyList[senderWallet1.vk] = senderWallet1.sk; +keyList[senderWallet2.vk] = senderWallet2.sk; + +describe("Test TransactionBuilder class", () => { + context("new TransactionBuilder", () => { + it("can create an instance", () => { + let txb = new Lamden.TransactionBatcher(networkInfo); + expect(txb.running).to.be(false); + }); + }); /* context('TransactionBatcher.addTransaction()', () => { it('can add a list of transactions for 1 sender', () => { let txb = new Lamden.TransactionBatcher(networkInfo) @@ -207,4 +206,4 @@ describe('Test TransactionBuilder class', () => { }) })*/ -}) \ No newline at end of file +}); diff --git a/test/transactionBuilder-test.js b/test/transactionBuilder-test.js index f004686..3f02053 100644 --- a/test/transactionBuilder-test.js +++ b/test/transactionBuilder-test.js @@ -1,309 +1,364 @@ -const expect = require('expect.js'); -require('dotenv').config() -const Lamden = require('../dist/lamden'); +const expect = require("expect.js"); +require("dotenv").config(); +const Lamden = require("../dist/cjs/lamden"); -const { vk ,sk } = process.env +const { vk, sk } = process.env; let goodNetwork = { - type: 'testnet', - name: 'Lamden Public Testnet', - hosts: ['https://testnet-master-1.lamden.io:443'] -} + type: "testnet", + name: "Lamden Public Testnet", + hosts: ["https://testnet-master-1.lamden.io:443"], +}; let badNetwork = { - type: 'testnet', - name: 'Bad Network', - hosts: ['http://badnetwork.lamden.io:18080'] -} + type: "testnet", + name: "Bad Network", + hosts: ["http://badnetwork.lamden.io:18080"], +}; -let uid = "randomUIDstring" +let uid = "randomUIDstring"; -const senderWallet = { vk, sk } +const senderWallet = { vk, sk }; -let recieverWallet = Lamden.wallet.new_wallet() +let recieverWallet = Lamden.wallet.new_wallet(); -let senderVk = senderWallet.vk -let contractName = 'currency' -let methodName = 'transfer' -let stampLimit = 100 +let senderVk = senderWallet.vk; +let contractName = "currency"; +let methodName = "transfer"; +let stampLimit = 100; let nonce = 0; let processor = "0000000000000000000000000000000000000000000000000000000000000000"; let kwargs = { - to: recieverWallet.vk, - amount: 1 -} + to: recieverWallet.vk, + amount: 1, +}; let valuesTxInfo = { - senderVk: senderWallet.vk, - contractName: 'con_values_testing_2', - methodName: 'test_values', - stampLimit: 100, - kwargs: { - UID: 'lamdenjs-testing', - Str: 'test string', - Int: 1, - Float: 1.01, - Bool: false, - Dict: {'s':'test', 'i': 1, 'f': 1.1, 'b': true,'d':{'f':1.1,'l':[1,1.1]},'l':[1,1.1]}, - List: ['test', 1, 1.1, false, {'f':1.1,'l':[1,1.1]}, [1,1.1]], - ANY: {'f':1.1,'l':[1,1.1]}, - DateTime: {'datetime': "2020-07-28T19:16:35.059Z"}, - TimeDelta: {'timedelta':1000} - } -} - -let txInfo_noNonce = {uid, senderVk, contractName, methodName, kwargs, stampLimit } -let txInfo_withNonce = {uid, senderVk, contractName, methodName, kwargs, stampLimit, nonce, processor } - -describe('Test TransactionBuilder class', () => { - context('new TransactionBuilder', () => { - it('can create an instance without nonce or processor', () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - let newTxInfo = newTx.getAllInfo() - expect(newTx).to.exist; - //Validate TX Info propagated in the class - expect(newTxInfo.uid).to.be(txInfo_noNonce.uid) - expect(newTxInfo.txInfo.senderVk).to.be(txInfo_noNonce.senderVk) - expect(newTxInfo.txInfo.contractName).to.be(txInfo_noNonce.contractName) - expect(newTxInfo.txInfo.methodName).to.be(txInfo_noNonce.methodName) - expect(JSON.stringify(newTxInfo.txInfo.kwargs)).to.be(JSON.stringify(txInfo_noNonce.kwargs)) - //Validate internal properties - expect(newTxInfo.signed).to.be(false) - expect(newTxInfo.signature).to.be(undefined) - expect(JSON.stringify(newTxInfo.txSendResult)).to.be(JSON.stringify({errors: []})) - expect(JSON.stringify(newTxInfo.txBlockResult)).to.be(JSON.stringify({})) - expect(JSON.stringify(newTxInfo.nonceResult)).to.be(JSON.stringify({})) - }) - it('can create an instance by providing nonce and processor', () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce) - let newTxInfo = newTx.getAllInfo() - expect(newTx).to.exist; - expect(newTxInfo.txInfo.nonce).to.exist; - expect(newTxInfo.txInfo.processor).to.exist; - }) - - it('it throws error when missing arguments', () => { - function testValues(argName, networkInfo, senderVk, contractName, methodName, kwargs, stampLimit){ - let txInfo = {senderVk, contractName, methodName, kwargs, stampLimit} - try{ - return new Lamden.TransactionBuilder(networkInfo, txInfo) - }catch (e){ - expect(e.message.includes(argName)).to.be(true); - } - } - let newTx = undefined; - newTx = testValues('Network Info', undefined, senderWallet.vk, 'currency', 'transfer', kwargs, 50000) - newTx = testValues('Sender', goodNetwork, undefined, 'currency', 'transfer', kwargs, 50000) - newTx = testValues('Contract', goodNetwork, senderWallet.vk, undefined, 'transfer', kwargs, 50000) - newTx = testValues('Method', goodNetwork, senderWallet.vk, 'currency', undefined, kwargs, 50000) - newTx = testValues('Stamps', goodNetwork, senderWallet.vk, 'currency', 'transfer', kwargs, undefined) - expect(typeof newTx).to.be('undefined'); - }) - - it('it can create an instance with a Lamden Network Object as first arg', () => { - let network = new Lamden.Network(goodNetwork) - let error = '' - try { - var newTx = new Lamden.TransactionBuilder(network, txInfo_withNonce) - } catch (e){ - error = e - } - expect(newTx).to.exist; - expect(error === '').to.be(true); - }) - }) - - context('TransactionBuilder.sign()', () => { - it('can sign and verify a transaction', () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce) - newTx.sign(senderWallet.sk) - expect(newTx.transactionSigned).to.be(true) - expect(newTx.verifySignature()).to.be(true) - }) - it('can sign and verify a transaction using a keystore wallet', () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce) - - let stringBuffer = Buffer.from(newTx.sortedPayload.json) - let message = new Uint8Array(stringBuffer) - let keystore = new Lamden.Keystore({key: {sk:senderWallet.sk}}) - - newTx.sign(null, keystore.wallets[0]) - - expect(newTx.transactionSigned).to.be(true) - expect(newTx.verifySignature()).to.be(true) - expect(keystore.wallets[0].verify(message, newTx.signature)).to.be(true) - }) - it('throws and error if nonce not set ', () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - expect(newTx.nonce).to.not.exist - expect(newTx.processor).to.not.exist - try { - newTx.sign(senderWallet.sk) - } catch (e){ - expect(e.toString()).to.be('Error: No Nonce Set. Call getNonce()') - } - }) - }) - - context('TransactionBuilder.getNonce()', () => { - it('can retrieve nonce and processor from the masternode', async () => { - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - expect(newTx.nonce).to.not.exist - expect(newTx.processor).to.not.exist - - let response = await newTx.getNonce(); - - //Validate Nonce was retrieved - expect(response.nonce).to.exist - expect(response.processor).to.exist - expect(response.sender).to.exist - expect(newTx.nonce).to.be(response.nonce) - expect(newTx.processor).to.be(response.processor) - expect(newTx.sender).to.be(response.sender) - expect(goodNetwork.hosts.includes(newTx.nonceMasternode)).to.be(true) - - }) - it('throws error if vk is not correct type, missing or invalid', async () => { - let error = '' - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - newTx.sender = 'not-a-good-vk' - try{ - await newTx.getNonce() - } catch (e){ - error = e.message - } - expect(error).to.be(`${newTx.sender} is not a hex string.`) - }) - it('throws error if provided network is unresponsive', async () => { - let error = '' - let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_noNonce) - try{ - await newTx.getNonce() - } catch (e){ - error = e.message - } - expect(error).to.be(`Unable to get nonce for ${newTx.sender} on network ${newTx.url}`) - }) - }) - - context('TransactionBuilder.send()', () => { - let newTx1 = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - - it('Sends a transaction and receives a hash back', async function () { - await newTx1.getNonce(); - //Sign transaction - newTx1.sign(senderWallet.sk) - - //Validate transaction is signed - expect(newTx1.transactionSigned).to.be(true) - expect(newTx1.verifySignature()).to.be(true) - - //Send Tx - await newTx1.send(); - //console.log(newTx1.getAllInfo()) - - let txSendResult = newTx1.txSendResult; - expect(txSendResult.success).to.equal('Transaction successfully submitted to the network.') - expect(txSendResult.hash).to.exist - expect(txSendResult.timestamp).to.exist - }) - it('Creates ResultInfo object based on txSendResult', async function () { - let resultInfo = newTx1.resultInfo; - - expect(resultInfo.title).to.equal('Transaction Pending') - expect(resultInfo.subtitle).to.equal('Your transaction was submitted and is being processed') - expect(resultInfo.message).to.equal(`Tx Hash: ${newTx1.txSendResult.hash}`) - expect(resultInfo.type).to.equal('success') - }) - it('Sends transactions and can get hash result from masternode', async function () { - this.timeout(20000); - await newTx1.checkForTransactionResult() - let txBlockResult = newTx1.txBlockResult; - expect(txBlockResult.hash).to.equal(newTx1.txSendResult.hash) - expect(txBlockResult.result).to.equal('None') - expect(txBlockResult.stamps_used > 0).to.be(true) - expect(txBlockResult.state.length).to.equal(2) - expect(txBlockResult.status).to.equal(0) - expect(JSON.stringify(txBlockResult.transaction)).to.equal(JSON.stringify(newTx1.tx)) - expect(txBlockResult.timestamp).to.exist - }) - it('Creates ResultInfo object based on txBlockResult', async function () { - let resultInfo = newTx1.resultInfo; - expect(resultInfo.title).to.equal('Transaction Successful') - expect(resultInfo.subtitle).to.equal(`Your transaction used ${resultInfo.stampsUsed} stamps`) - expect(resultInfo.message).to.equal('') - expect(resultInfo.type).to.equal('success') - expect(resultInfo.errorInfo).to.equal(undefined) - expect(resultInfo.stampsUsed).to.equal(newTx1.txBlockResult.stamps_used) - expect(resultInfo.statusCode).to.equal(0) - expect(resultInfo.returnResult).to.equal('None') - - }) - it('gets nonce and signs transacation automatically if sk is provided', async function () { - this.timeout(10000); - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - //Send Tx - await newTx.send(senderWallet.sk); - - let txSendResult = newTx.txSendResult; - - expect(txSendResult.success).to.equal('Transaction successfully submitted to the network.') - expect(txSendResult.hash).to.exist - expect(txSendResult.timestamp).to.exist - }) - it('throws error if provided network is unresponsive', async function () { - let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_withNonce) - let response = await newTx.send(senderWallet.sk) - expect(response.errors[0]) - .to.be('FetchError: request to http://badnetwork.lamden.io:18080/ failed, reason: getaddrinfo ENOTFOUND badnetwork.lamden.io') - - }) - it('can return execution errors list', async function () { - this.timeout(10000); - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - newTx.stampLimit = 0 - //Send Tx - await newTx.send(senderWallet.sk); - await newTx.checkForTransactionResult() - - let resultInfo = newTx.resultInfo; - - expect(resultInfo.title).to.equal('Transaction Failed') - expect(resultInfo.subtitle).to.equal(`Your transaction returned status code 1 and used ${resultInfo.stampsUsed} stamps`) - expect(resultInfo.message).to.equal('This transaction returned 1 errors.') - expect(resultInfo.type).to.equal('error') - expect(resultInfo.errorInfo.length).to.equal(2) - expect(resultInfo.errorInfo[0]).to.equal('This transaction returned a non-zero status code') - expect(resultInfo.errorInfo[1].includes('The cost has exceeded the stamp supplied!')).to.be(true) - expect(resultInfo.stampsUsed).to.equal(newTx.txBlockResult.stamps_used) - expect(resultInfo.statusCode).to.equal(1) - expect(resultInfo.returnResult.includes('The cost has exceeded the stamp supplied!')).to.be(true) - }) - it('can return transaction validation errors list', async function () { - let sender = Lamden.wallet.new_wallet() - let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce) - newTx.sender = sender.vk; - - //Send Transaction - let response = await newTx.send(sender.sk); - expect(response.errors.length > 0).to.be(true) - expect(response.errors[0]).to.be('Transaction sender has too few stamps for this transaction.') - }) - it('can encode and send all annotation types', async function () { - this.timeout(15000); - valuesTxInfo.kwargs = Lamden.Encoder('object', valuesTxInfo.kwargs) - - let newTx = new Lamden.TransactionBuilder(goodNetwork, valuesTxInfo) - - //Send Transaction - let response = await newTx.send(senderWallet.sk); - - expect(response.success).to.be("Transaction successfully submitted to the network.") - - //Check Transaction - let check = await newTx.checkForTransactionResult() - expect(check.status).to.be(0) - }) - }) -}) \ No newline at end of file + senderVk: senderWallet.vk, + contractName: "con_values_testing_2", + methodName: "test_values", + stampLimit: 100, + kwargs: { + UID: "lamdenjs-testing", + Str: "test string", + Int: 1, + Float: 1.01, + Bool: false, + Dict: { s: "test", i: 1, f: 1.1, b: true, d: { f: 1.1, l: [1, 1.1] }, l: [1, 1.1] }, + List: ["test", 1, 1.1, false, { f: 1.1, l: [1, 1.1] }, [1, 1.1]], + ANY: { f: 1.1, l: [1, 1.1] }, + DateTime: { datetime: "2020-07-28T19:16:35.059Z" }, + TimeDelta: { timedelta: 1000 }, + }, +}; + +let txInfo_noNonce = { uid, senderVk, contractName, methodName, kwargs, stampLimit }; +let txInfo_withNonce = { + uid, + senderVk, + contractName, + methodName, + kwargs, + stampLimit, + nonce, + processor, +}; + +describe("Test TransactionBuilder class", () => { + context("new TransactionBuilder", () => { + it("can create an instance without nonce or processor", () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + let newTxInfo = newTx.getAllInfo(); + expect(newTx).to.exist; + //Validate TX Info propagated in the class + expect(newTxInfo.uid).to.be(txInfo_noNonce.uid); + expect(newTxInfo.txInfo.senderVk).to.be(txInfo_noNonce.senderVk); + expect(newTxInfo.txInfo.contractName).to.be(txInfo_noNonce.contractName); + expect(newTxInfo.txInfo.methodName).to.be(txInfo_noNonce.methodName); + expect(JSON.stringify(newTxInfo.txInfo.kwargs)).to.be(JSON.stringify(txInfo_noNonce.kwargs)); + //Validate internal properties + expect(newTxInfo.signed).to.be(false); + expect(newTxInfo.signature).to.be(undefined); + expect(JSON.stringify(newTxInfo.txSendResult)).to.be(JSON.stringify({ errors: [] })); + expect(JSON.stringify(newTxInfo.txBlockResult)).to.be(JSON.stringify({})); + expect(JSON.stringify(newTxInfo.nonceResult)).to.be(JSON.stringify({})); + }); + it("can create an instance by providing nonce and processor", () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + let newTxInfo = newTx.getAllInfo(); + expect(newTx).to.exist; + expect(newTxInfo.txInfo.nonce).to.exist; + expect(newTxInfo.txInfo.processor).to.exist; + }); + + it("it throws error when missing arguments", () => { + function testValues( + argName, + networkInfo, + senderVk, + contractName, + methodName, + kwargs, + stampLimit + ) { + let txInfo = { senderVk, contractName, methodName, kwargs, stampLimit }; + try { + return new Lamden.TransactionBuilder(networkInfo, txInfo); + } catch (e) { + expect(e.message.includes(argName)).to.be(true); + } + } + let newTx = undefined; + newTx = testValues( + "Network Info", + undefined, + senderWallet.vk, + "currency", + "transfer", + kwargs, + 50000 + ); + newTx = testValues("Sender", goodNetwork, undefined, "currency", "transfer", kwargs, 50000); + newTx = testValues( + "Contract", + goodNetwork, + senderWallet.vk, + undefined, + "transfer", + kwargs, + 50000 + ); + newTx = testValues( + "Method", + goodNetwork, + senderWallet.vk, + "currency", + undefined, + kwargs, + 50000 + ); + newTx = testValues( + "Stamps", + goodNetwork, + senderWallet.vk, + "currency", + "transfer", + kwargs, + undefined + ); + expect(typeof newTx).to.be("undefined"); + }); + + it("it can create an instance with a Lamden Network Object as first arg", () => { + let network = new Lamden.Network(goodNetwork); + let error = ""; + try { + var newTx = new Lamden.TransactionBuilder(network, txInfo_withNonce); + } catch (e) { + error = e; + } + expect(newTx).to.exist; + expect(error === "").to.be(true); + }); + }); + + context("TransactionBuilder.sign()", () => { + it("can sign and verify a transaction", () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + newTx.sign(senderWallet.sk); + expect(newTx.transactionSigned).to.be(true); + expect(newTx.verifySignature()).to.be(true); + }); + it("can sign and verify a transaction using a keystore wallet", () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_withNonce); + + let stringBuffer = Buffer.from(newTx.sortedPayload.json); + let message = new Uint8Array(stringBuffer); + let keystore = new Lamden.Keystore({ key: { sk: senderWallet.sk } }); + + newTx.sign(null, keystore.wallets[0]); + + expect(newTx.transactionSigned).to.be(true); + expect(newTx.verifySignature()).to.be(true); + expect(keystore.wallets[0].verify(message, newTx.signature)).to.be(true); + }); + it("throws and error if nonce not set ", () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + expect(newTx.nonce).to.not.exist; + expect(newTx.processor).to.not.exist; + try { + newTx.sign(senderWallet.sk); + } catch (e) { + expect(e.toString()).to.be("Error: No Nonce Set. Call getNonce()"); + } + }); + }); + + context("TransactionBuilder.getNonce()", () => { + it("can retrieve nonce and processor from the masternode", async () => { + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + expect(newTx.nonce).to.not.exist; + expect(newTx.processor).to.not.exist; + + let response = await newTx.getNonce(); + + //Validate Nonce was retrieved + expect(response.nonce).to.exist; + expect(response.processor).to.exist; + expect(response.sender).to.exist; + expect(newTx.nonce).to.be(response.nonce); + expect(newTx.processor).to.be(response.processor); + expect(newTx.sender).to.be(response.sender); + expect(goodNetwork.hosts.includes(newTx.nonceMasternode)).to.be(true); + }); + it("throws error if vk is not correct type, missing or invalid", async () => { + let error = ""; + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.sender = "not-a-good-vk"; + try { + await newTx.getNonce(); + } catch (e) { + error = e.message; + } + expect(error).to.be(`${newTx.sender} is not a hex string.`); + }); + it("throws error if provided network is unresponsive", async () => { + let error = ""; + let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_noNonce); + try { + await newTx.getNonce(); + } catch (e) { + error = e.message; + } + expect(error).to.be(`Unable to get nonce for ${newTx.sender} on network ${newTx.url}`); + }); + }); + + context("TransactionBuilder.send()", () => { + let newTx1 = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + + it("Sends a transaction and receives a hash back", async function () { + await newTx1.getNonce(); + //Sign transaction + newTx1.sign(senderWallet.sk); + + //Validate transaction is signed + expect(newTx1.transactionSigned).to.be(true); + expect(newTx1.verifySignature()).to.be(true); + + //Send Tx + await newTx1.send(); + //console.log(newTx1.getAllInfo()) + + let txSendResult = newTx1.txSendResult; + expect(txSendResult.success).to.equal("Transaction successfully submitted to the network."); + expect(txSendResult.hash).to.exist; + expect(txSendResult.timestamp).to.exist; + }); + it("Creates ResultInfo object based on txSendResult", async function () { + let resultInfo = newTx1.resultInfo; + + expect(resultInfo.title).to.equal("Transaction Pending"); + expect(resultInfo.subtitle).to.equal("Your transaction was submitted and is being processed"); + expect(resultInfo.message).to.equal(`Tx Hash: ${newTx1.txSendResult.hash}`); + expect(resultInfo.type).to.equal("success"); + }); + it("Sends transactions and can get hash result from masternode", async function () { + this.timeout(30000); + await newTx1.checkForTransactionResult(); + let txBlockResult = newTx1.txBlockResult; + expect(txBlockResult.hash).to.equal(newTx1.txSendResult.hash); + expect(txBlockResult.result).to.equal("None"); + expect(txBlockResult.stamps_used > 0).to.be(true); + expect(txBlockResult.state.length).to.equal(2); + expect(txBlockResult.status).to.equal(0); + expect(JSON.stringify(txBlockResult.transaction)).to.equal(JSON.stringify(newTx1.tx)); + expect(txBlockResult.timestamp).to.exist; + }); + it("Creates ResultInfo object based on txBlockResult", async function () { + let resultInfo = newTx1.resultInfo; + expect(resultInfo.title).to.equal("Transaction Successful"); + expect(resultInfo.subtitle).to.equal(`Your transaction used ${resultInfo.stampsUsed} stamps`); + expect(resultInfo.message).to.equal(""); + expect(resultInfo.type).to.equal("success"); + expect(resultInfo.errorInfo).to.equal(undefined); + expect(resultInfo.stampsUsed).to.equal(newTx1.txBlockResult.stamps_used); + expect(resultInfo.statusCode).to.equal(0); + expect(resultInfo.returnResult).to.equal("None"); + }); + it("gets nonce and signs transacation automatically if sk is provided", async function () { + this.timeout(10000); + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + //Send Tx + await newTx.send(senderWallet.sk); + + let txSendResult = newTx.txSendResult; + + expect(txSendResult.success).to.equal("Transaction successfully submitted to the network."); + expect(txSendResult.hash).to.exist; + expect(txSendResult.timestamp).to.exist; + }); + it("throws error if provided network is unresponsive", async function () { + let newTx = new Lamden.TransactionBuilder(badNetwork, txInfo_withNonce); + let response = await newTx.send(senderWallet.sk); + expect(response.errors[0]).to.be( + "FetchError: request to http://badnetwork.lamden.io:18080/ failed, reason: getaddrinfo ENOTFOUND badnetwork.lamden.io" + ); + }); + it("can return execution errors list", async function () { + this.timeout(10000); + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.stampLimit = 0; + //Send Tx + await newTx.send(senderWallet.sk); + await newTx.checkForTransactionResult(); + + let resultInfo = newTx.resultInfo; + + expect(resultInfo.title).to.equal("Transaction Failed"); + expect(resultInfo.subtitle).to.equal( + `Your transaction returned status code 1 and used ${resultInfo.stampsUsed} stamps` + ); + expect(resultInfo.message).to.equal("This transaction returned 1 errors."); + expect(resultInfo.type).to.equal("error"); + expect(resultInfo.errorInfo.length).to.equal(2); + expect(resultInfo.errorInfo[0]).to.equal("This transaction returned a non-zero status code"); + expect(resultInfo.errorInfo[1].includes("The cost has exceeded the stamp supplied!")).to.be( + true + ); + expect(resultInfo.stampsUsed).to.equal(newTx.txBlockResult.stamps_used); + expect(resultInfo.statusCode).to.equal(1); + expect(resultInfo.returnResult.includes("The cost has exceeded the stamp supplied!")).to.be( + true + ); + }); + it("can return transaction validation errors list", async function () { + let sender = Lamden.wallet.new_wallet(); + let newTx = new Lamden.TransactionBuilder(goodNetwork, txInfo_noNonce); + newTx.sender = sender.vk; + + //Send Transaction + let response = await newTx.send(sender.sk); + expect(response.errors.length > 0).to.be(true); + expect(response.errors[0]).to.be( + "Transaction sender has too few stamps for this transaction." + ); + }); + it("can encode and send all annotation types", async function () { + this.timeout(15000); + valuesTxInfo.kwargs = Lamden.Encoder("object", valuesTxInfo.kwargs); + + let newTx = new Lamden.TransactionBuilder(goodNetwork, valuesTxInfo); + + //Send Transaction + let response = await newTx.send(senderWallet.sk); + + expect(response.success).to.be("Transaction successfully submitted to the network."); + + //Check Transaction + let check = await newTx.checkForTransactionResult(); + expect(check.status).to.be(0); + }); + }); +}); diff --git a/test/wallet-test.js b/test/wallet-test.js index 4924768..bf43194 100644 --- a/test/wallet-test.js +++ b/test/wallet-test.js @@ -1,123 +1,110 @@ -const expect = require('expect.js'); -const Lamden = require('../dist/lamden'); -const validators = require('types-validate-assert') +const expect = require("expect.js"); +const Lamden = require("../dist/cjs/lamden"); +const validators = require("types-validate-assert"); const { validateTypes, assertTypes } = validators; const { wallet } = Lamden; -describe('Test Lamden Wallet methods', () => { +describe("Test Lamden Wallet methods", () => { + context("wallet.create_wallet_bip39: ", () => { + it("creates a bip39 / bip32 compatible lamden keypair", () => { + let newWallet = wallet.new_wallet_bip39(); - context('wallet.create_wallet_bip39: ', () => { - it('creates a bip39 / bip32 compatible lamden keypair', () => { - let newWallet = wallet.new_wallet_bip39(); - - expect( validateTypes.isStringHex(newWallet.vk) ).to.be( true ) - expect( newWallet.vk.length ).to.be( 64 ) - expect( validateTypes.isStringHex(newWallet.sk) ).to.be( true ) - expect( newWallet.sk.length ).to.be( 64 ) - expect( validateTypes.isStringWithValue(newWallet.mnemonic) ).to.be( true ) - expect( validateTypes.isNumber(newWallet.derivationIndex) ).to.be( true ) - expect( newWallet.derivationIndex ).to.be( 0 ) - }), - - it('creates a bip39 / bip32 compatible lamden keypair from mnemonic', () => { - const mnemonic = 'ripple junk access broom element fitness side example ramp flush model creek nest face rent jacket ahead come short find over family wise comfort' + expect(validateTypes.isStringHex(newWallet.vk)).to.be(true); + expect(newWallet.vk.length).to.be(64); + expect(validateTypes.isStringHex(newWallet.sk)).to.be(true); + expect(newWallet.sk.length).to.be(64); + expect(validateTypes.isStringWithValue(newWallet.mnemonic)).to.be(true); + expect(validateTypes.isNumber(newWallet.derivationIndex)).to.be(true); + expect(newWallet.derivationIndex).to.be(0); + }), + it('creates a bip39 / bip32 compatible lamden keypair from seed', () => { + const seed = 'd3ad26bd89d54d0c22bb32d34ea9f06c567ba060d8e1518974d807180b886c643bfb7f455bd3db2c767a17c089aab20db97cf0f0184d730b9d20be0c7b6cc6cc' const derivationIndex = 127 - let newWallet = wallet.new_wallet_bip39(mnemonic, derivationIndex); + let newWallet = wallet.new_wallet_bip39(seed, derivationIndex); expect( validateTypes.isStringHex(newWallet.vk) ).to.be( true ) expect( newWallet.vk ).to.be( 'd0d2de909bf7c2be3bafbcb3af0b1c50487b80ba48b5700bff35bb927921c607' ) expect( validateTypes.isStringHex(newWallet.sk) ).to.be( true ) expect( newWallet.sk ).to.be( '86c77748edc039c672cf761d2db1e52d6255b16cd4d626d4b66c67eb224287a8' ) - expect( newWallet.mnemonic ).to.be( mnemonic ) + expect( newWallet.mnemonic ).to.be( null ) + expect( newWallet.seed ).to.be( null ) expect( validateTypes.isNumber(newWallet.derivationIndex) ).to.be( true ) expect( newWallet.derivationIndex ).to.be( 127 ) }) }) - context('wallet.new_wallet(): ', () => { - it('creates a lamden keypair', () => { - let newWallet = wallet.new_wallet() + context("wallet.get_vk(): ", () => { + it("can create a vk from an sk", () => { + let newWallet = wallet.new_wallet(); - expect( validateTypes.isStringHex(newWallet.vk) ).to.be( true ) - expect( newWallet.vk.length ).to.be( 64 ) - expect( validateTypes.isStringHex(newWallet.sk) ).to.be( true ) - expect( newWallet.sk.length ).to.be( 64 ) - }) - }) + expect(wallet.get_vk(newWallet.sk)).to.be(newWallet.vk); + }); + }); + context("wallet.sign(): ", () => { + it("can sign a message", () => { + let newWallet = wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = wallet.sign(newWallet.sk, message); + expect(validateTypes.isStringHex(signedMessage)).to.be(true); + }); + }); - context('wallet.get_vk(): ', () => { - it('can create a vk from an sk', () => { - let newWallet = wallet.new_wallet() + context("wallet.verify(): ", () => { + it("can validate a correct signature", () => { + let newWallet = wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = wallet.sign(newWallet.sk, message); - expect( wallet.get_vk(newWallet.sk) ).to.be( newWallet.vk ) - }) - }) - context('wallet.sign(): ', () => { - it('can sign a message', () => { - let newWallet = wallet.new_wallet() - let message = new Uint8Array('this is a message') - let signedMessage = wallet.sign(newWallet.sk, message) + expect(validateTypes.isStringHex(signedMessage)).to.be(true); + expect(wallet.verify(newWallet.vk, message, signedMessage)).to.be(true); + }); + it("can validate an incorrect signature", () => { + let newWallet = wallet.new_wallet(); + let newWallet2 = wallet.new_wallet(); + let message = new Uint8Array("this is a message"); + let signedMessage = wallet.sign(newWallet.sk, message); - expect(validateTypes.isStringHex(signedMessage)).to.be(true) - }) - }) + expect(validateTypes.isStringHex(signedMessage)).to.be(true); + expect(wallet.verify(newWallet2.vk, message, signedMessage)).to.be(false); + }); + }); - context('wallet.verify(): ', () => { - it('can validate a correct signature', () => { - let newWallet = wallet.new_wallet() - let message = new Uint8Array('this is a message') - let signedMessage = wallet.sign(newWallet.sk, message) - - expect(validateTypes.isStringHex(signedMessage)).to.be(true) - expect( wallet.verify(newWallet.vk, message, signedMessage) ).to.be( true ) - }) - it('can validate an incorrect signature', () => { - let newWallet = wallet.new_wallet() - let newWallet2 = wallet.new_wallet() - let message = new Uint8Array('this is a message') - let signedMessage = wallet.sign(newWallet.sk, message) - - expect(validateTypes.isStringHex(signedMessage)).to.be(true) - expect( wallet.verify(newWallet2.vk, message, signedMessage) ).to.be( false ) - }) - }) - - context('wallet.create_wallet(): ', () => { - it('can create a new wallet object', () => { - let newWallet = wallet.create_wallet() - expect(newWallet).to.have.property('sign') - expect(newWallet).to.have.property('verify') - expect(newWallet).to.have.property('vk') - expect(newWallet).to.have.property('sk') - assertTypes.isStringHex(newWallet.vk) - assertTypes.isStringHex(newWallet.sk) - }) - it('can create a new wallet from a private key', () => { - let keypair = wallet.new_wallet() - let newWallet = wallet.create_wallet({sk: keypair.sk}) - expect(newWallet).to.have.property('sign') - expect(newWallet).to.have.property('verify') - expect(newWallet).to.have.property('vk') - expect(newWallet).to.have.property('sk') - assertTypes.isStringHex(newWallet.vk) - assertTypes.isStringHex(newWallet.sk) - }) - it('secret key is not accessible is set to private', () => { - let newWallet = wallet.create_wallet({keepPrivate: true}) - expect(() => assertTypes.isStringHex(newWallet.sk)).throwException(); - }) - it('wallet object can sign messages', () => { - let newWallet = wallet.create_wallet({keepPrivate: true}) - let message = new Uint8Array('this is a message') - let signedMessage = newWallet.sign(message) - expect( wallet.verify(newWallet.vk, message, signedMessage) ).to.be( true ) - }) - it('wallet object can verify a messages', () => { - let newWallet = wallet.create_wallet({keepPrivate: true}) - let message = new Uint8Array('this is a message') - let signedMessage = newWallet.sign(message) - expect( newWallet.verify(message, signedMessage) ).to.be( true ) - }) - }) -}) + context("wallet.create_wallet(): ", () => { + it("can create a new wallet object", () => { + let newWallet = wallet.create_wallet(); + expect(newWallet).to.have.property("sign"); + expect(newWallet).to.have.property("verify"); + expect(newWallet).to.have.property("vk"); + expect(newWallet).to.have.property("sk"); + assertTypes.isStringHex(newWallet.vk); + assertTypes.isStringHex(newWallet.sk); + }); + it("can create a new wallet from a private key", () => { + let keypair = wallet.new_wallet(); + let newWallet = wallet.create_wallet({ sk: keypair.sk }); + expect(newWallet).to.have.property("sign"); + expect(newWallet).to.have.property("verify"); + expect(newWallet).to.have.property("vk"); + expect(newWallet).to.have.property("sk"); + assertTypes.isStringHex(newWallet.vk); + assertTypes.isStringHex(newWallet.sk); + }); + it("secret key is not accessible is set to private", () => { + let newWallet = wallet.create_wallet({ keepPrivate: true }); + expect(() => assertTypes.isStringHex(newWallet.sk)).throwException(); + }); + it("wallet object can sign messages", () => { + let newWallet = wallet.create_wallet({ keepPrivate: true }); + let message = new Uint8Array("this is a message"); + let signedMessage = newWallet.sign(message); + expect(wallet.verify(newWallet.vk, message, signedMessage)).to.be(true); + }); + it("wallet object can verify a messages", () => { + let newWallet = wallet.create_wallet({ keepPrivate: true }); + let message = new Uint8Array("this is a message"); + let signedMessage = newWallet.sign(message); + expect(newWallet.verify(message, signedMessage)).to.be(true); + }); + }); +});