From 11cd216f94fa82fad25a608095449773e5165c0f Mon Sep 17 00:00:00 2001 From: Shai James Date: Sun, 19 Aug 2018 01:54:09 +0300 Subject: [PATCH] removing socketio in favor of websockets --- dist/scatter.cjs.js | 171 +- dist/scatter.esm.js | 171 +- dist/scatter.min.js | 80463 ++++++++++++------------------ dist/scatter.min.js.map | 2 +- index.html | 23 +- package-lock.json | 24 +- src/plugins/PluginRepository.js | 4 +- src/services/SocketService.js | 184 +- 8 files changed, 33122 insertions(+), 47920 deletions(-) diff --git a/dist/scatter.cjs.js b/dist/scatter.cjs.js index 9938cf94..8a409b87 100644 --- a/dist/scatter.cjs.js +++ b/dist/scatter.cjs.js @@ -5,11 +5,6 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var io = _interopDefault(require('socket.io-client')); var getRandomValues = _interopDefault(require('get-random-values')); var Eos = _interopDefault(require('eosjs')); -var ProviderEngine = _interopDefault(require('web3-provider-engine')); -var RpcSubprovider = _interopDefault(require('web3-provider-engine/subproviders/rpc')); -var WebsocketSubprovider = _interopDefault(require('web3-provider-engine/subproviders/websocket')); -var HookedWalletSubprovider = _interopDefault(require('web3-provider-engine/subproviders/hooked-wallet')); -var ethUtil = _interopDefault(require('ethereumjs-util')); require('isomorphic-fetch'); let storage = {}; @@ -55,7 +50,7 @@ class StorageService { const {ecc} = Eos.modules; -const host = 'http://127.0.0.1:50005'; +const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket'; let socket = null; let connected = false; @@ -67,7 +62,7 @@ let openRequests = []; let allowReconnects = true; let reconnectionTimeout = null; -const reconnectOnAbnormalDisconnection = async () => { +const reconnectOnAbnormalDisconnection = () => { if(!allowReconnects) return; clearTimeout(reconnectionTimeout); @@ -114,10 +109,10 @@ class SocketService { this.timeout = timeout; } - static async link(){ + static link(){ return Promise.race([ - new Promise((resolve, reject) => setTimeout(async () => { + new Promise((resolve, reject) => setTimeout(() => { if(connected) return; resolve(false); @@ -128,17 +123,18 @@ class SocketService { reconnectOnAbnormalDisconnection(); }, this.timeout)), - new Promise(async (resolve, reject) => { + new Promise((resolve, reject) => { socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false }); - socket.on('connected', async () => { + socket.on('connected', () => { clearTimeout(reconnectionTimeout); connected = true; - await pair(true); - resolve(true); + pair(true).then(() => { + resolve(true); + }); }); - socket.on('paired', async result => { + socket.on('paired', result => { paired = result; if(paired) { @@ -154,7 +150,7 @@ class SocketService { pairingPromise.resolve(result); }); - socket.on('rekey', async () => { + socket.on('rekey', () => { appkey = 'appkey:'+random(); socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); }); @@ -172,7 +168,7 @@ class SocketService { else openRequest.resolve(result.result); }); - socket.on('disconnect', async () => { + socket.on('disconnect', () => { console.log('Disconnected'); connected = false; socket = null; @@ -181,12 +177,12 @@ class SocketService { reconnectOnAbnormalDisconnection(); }); - socket.on('connect_error', async () => { + socket.on('connect_error', () => { allowReconnects = false; resolve(false); }); - socket.on('rejected', async reason => { + socket.on('rejected', reason => { console.error('reason', reason); reject(reason); }); @@ -198,37 +194,38 @@ class SocketService { return connected; } - static async disconnect(){ + static disconnect(){ socket.disconnect(); return true; } - static async sendApiRequest(request){ - return new Promise(async (resolve, reject) => { + static sendApiRequest(request){ + return new Promise((resolve, reject) => { if(request.type === 'identityFromPermissions' && !paired) return resolve(false); - await pair(); - if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'}); + pair().then(() => { + if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'}); - // Request ID used for resolving promises - request.id = random(); + // Request ID used for resolving promises + request.id = random(); - // Set Application Key - request.appkey = appkey; + // Set Application Key + request.appkey = appkey; - // Nonce used to authenticate this request - request.nonce = StorageService.getNonce() || 0; - // Next nonce used to authenticate the next request - const nextNonce = random(); - request.nextNonce = ecc.sha256(nextNonce); - StorageService.setNonce(nextNonce); + // Nonce used to authenticate this request + request.nonce = StorageService.getNonce() || 0; + // Next nonce used to authenticate the next request + const nextNonce = random(); + request.nextNonce = ecc.sha256(nextNonce); + StorageService.setNonce(nextNonce); - if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) - request.payload.origin = getOrigin(); + if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) + request.payload.origin = getOrigin(); - openRequests.push(Object.assign(request, {resolve, reject})); - socket.emit('api', {data:request, plugin}); + openRequests.push(Object.assign(request, {resolve, reject})); + socket.emit('api', {data:request, plugin}); + }); }); } @@ -390,87 +387,7 @@ class EOS extends Plugin { } } -let ethNetwork; - -class ETH extends Plugin { - - constructor(){ - super(Blockchains.ETH, BLOCKCHAIN_SUPPORT); - } - - signatureProvider(...args){ - - return (_network, _web3) => { - ethNetwork = Network.fromJson(_network); - if(!ethNetwork.isValid()) throw Error.noNetwork(); - - const rpcUrl = `${ethNetwork.protocol}://${ethNetwork.hostport()}`; - - const engine = new ProviderEngine(); - const web3 = new _web3(engine); - - const walletSubprovider = new HookedWalletSubprovider(new ScatterEthereumWallet()); - engine.addProvider(walletSubprovider); - - if(ethNetwork.protocol.indexOf('http') > -1) engine.addProvider(new RpcSubprovider({rpcUrl})); - else engine.addProvider(new WebsocketSubprovider({rpcUrl})); - - engine.start(); - - return web3; - } - } -} - - - -class ScatterEthereumWallet { - constructor(){ - this.getAccounts = this.getAccounts.bind(this); - this.signTransaction = this.signTransaction.bind(this); - } - - async getAccounts(callback) { - const result = await SocketService.sendApiRequest({ - type:'identityFromPermissions', - payload:{} - }); - const accounts = !result ? [] : result.accounts - .filter(account => account.blockchain === Blockchains.ETH) - .map(account => account.address); - - callback(null, accounts); - return accounts; - } - - async signTransaction(transaction){ - if(!ethNetwork) throw Error.noNetwork(); - - // Basic settings - if (transaction.gas !== undefined) transaction.gasLimit = transaction.gas; - transaction.value = transaction.value || '0x00'; - if(transaction.hasOwnProperty('data')) transaction.data = ethUtil.addHexPrefix(transaction.data); - - // Required Fields - const requiredFields = transaction.hasOwnProperty('requiredFields') ? transaction.requiredFields : {}; - - // Contract ABI - const abi = transaction.hasOwnProperty('abi') ? transaction.abi : null; - if(!abi && transaction.hasOwnProperty('data')) - throw Error.signatureError('no_abi', 'You must provide a JSON ABI along with your transaction so that users can read the contract'); - - const payload = Object.assign(transaction, { blockchain:Blockchains.ETH, network:ethNetwork, requiredFields }); - const {signatures, returnedFields} = await SocketService.sendApiRequest({ - type:'requestSignature', - payload - }); - - if(transaction.hasOwnProperty('fieldsCallback')) - transaction.fieldsCallback(returnedFields); - - return signatures[0]; - } -} +// import ETH from './defaults/eth'; /*** * Setting up for plugin based generators, @@ -486,7 +403,7 @@ class PluginRepositorySingleton { loadPlugins(){ this.plugins.push(new EOS()); - this.plugins.push(new ETH()); + // this.plugins.push(new ETH()); } signatureProviders(){ @@ -649,6 +566,22 @@ class Scatter { }); } + getPublicKey(blockchain){ + throwNoAuth(); + return SocketService.sendApiRequest({ + type:'getPublicKey', + payload:{ blockchain } + }); + } + + linkAccount(publicKey, account, network){ + throwNoAuth(); + return SocketService.sendApiRequest({ + type:'linkAccount', + payload:{ publicKey, account, network } + }); + } + suggestNetwork(network){ throwNoAuth(); return SocketService.sendApiRequest({ diff --git a/dist/scatter.esm.js b/dist/scatter.esm.js index f846f227..a2a1354d 100644 --- a/dist/scatter.esm.js +++ b/dist/scatter.esm.js @@ -1,11 +1,6 @@ import io from 'socket.io-client'; import getRandomValues from 'get-random-values'; import Eos from 'eosjs'; -import ProviderEngine from 'web3-provider-engine'; -import RpcSubprovider from 'web3-provider-engine/subproviders/rpc'; -import WebsocketSubprovider from 'web3-provider-engine/subproviders/websocket'; -import HookedWalletSubprovider from 'web3-provider-engine/subproviders/hooked-wallet'; -import ethUtil from 'ethereumjs-util'; import 'isomorphic-fetch'; let storage = {}; @@ -51,7 +46,7 @@ class StorageService { const {ecc} = Eos.modules; -const host = 'http://127.0.0.1:50005'; +const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket'; let socket = null; let connected = false; @@ -63,7 +58,7 @@ let openRequests = []; let allowReconnects = true; let reconnectionTimeout = null; -const reconnectOnAbnormalDisconnection = async () => { +const reconnectOnAbnormalDisconnection = () => { if(!allowReconnects) return; clearTimeout(reconnectionTimeout); @@ -110,10 +105,10 @@ class SocketService { this.timeout = timeout; } - static async link(){ + static link(){ return Promise.race([ - new Promise((resolve, reject) => setTimeout(async () => { + new Promise((resolve, reject) => setTimeout(() => { if(connected) return; resolve(false); @@ -124,17 +119,18 @@ class SocketService { reconnectOnAbnormalDisconnection(); }, this.timeout)), - new Promise(async (resolve, reject) => { + new Promise((resolve, reject) => { socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false }); - socket.on('connected', async () => { + socket.on('connected', () => { clearTimeout(reconnectionTimeout); connected = true; - await pair(true); - resolve(true); + pair(true).then(() => { + resolve(true); + }); }); - socket.on('paired', async result => { + socket.on('paired', result => { paired = result; if(paired) { @@ -150,7 +146,7 @@ class SocketService { pairingPromise.resolve(result); }); - socket.on('rekey', async () => { + socket.on('rekey', () => { appkey = 'appkey:'+random(); socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin}); }); @@ -168,7 +164,7 @@ class SocketService { else openRequest.resolve(result.result); }); - socket.on('disconnect', async () => { + socket.on('disconnect', () => { console.log('Disconnected'); connected = false; socket = null; @@ -177,12 +173,12 @@ class SocketService { reconnectOnAbnormalDisconnection(); }); - socket.on('connect_error', async () => { + socket.on('connect_error', () => { allowReconnects = false; resolve(false); }); - socket.on('rejected', async reason => { + socket.on('rejected', reason => { console.error('reason', reason); reject(reason); }); @@ -194,37 +190,38 @@ class SocketService { return connected; } - static async disconnect(){ + static disconnect(){ socket.disconnect(); return true; } - static async sendApiRequest(request){ - return new Promise(async (resolve, reject) => { + static sendApiRequest(request){ + return new Promise((resolve, reject) => { if(request.type === 'identityFromPermissions' && !paired) return resolve(false); - await pair(); - if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'}); + pair().then(() => { + if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'}); - // Request ID used for resolving promises - request.id = random(); + // Request ID used for resolving promises + request.id = random(); - // Set Application Key - request.appkey = appkey; + // Set Application Key + request.appkey = appkey; - // Nonce used to authenticate this request - request.nonce = StorageService.getNonce() || 0; - // Next nonce used to authenticate the next request - const nextNonce = random(); - request.nextNonce = ecc.sha256(nextNonce); - StorageService.setNonce(nextNonce); + // Nonce used to authenticate this request + request.nonce = StorageService.getNonce() || 0; + // Next nonce used to authenticate the next request + const nextNonce = random(); + request.nextNonce = ecc.sha256(nextNonce); + StorageService.setNonce(nextNonce); - if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) - request.payload.origin = getOrigin(); + if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) + request.payload.origin = getOrigin(); - openRequests.push(Object.assign(request, {resolve, reject})); - socket.emit('api', {data:request, plugin}); + openRequests.push(Object.assign(request, {resolve, reject})); + socket.emit('api', {data:request, plugin}); + }); }); } @@ -386,87 +383,7 @@ class EOS extends Plugin { } } -let ethNetwork; - -class ETH extends Plugin { - - constructor(){ - super(Blockchains.ETH, BLOCKCHAIN_SUPPORT); - } - - signatureProvider(...args){ - - return (_network, _web3) => { - ethNetwork = Network.fromJson(_network); - if(!ethNetwork.isValid()) throw Error.noNetwork(); - - const rpcUrl = `${ethNetwork.protocol}://${ethNetwork.hostport()}`; - - const engine = new ProviderEngine(); - const web3 = new _web3(engine); - - const walletSubprovider = new HookedWalletSubprovider(new ScatterEthereumWallet()); - engine.addProvider(walletSubprovider); - - if(ethNetwork.protocol.indexOf('http') > -1) engine.addProvider(new RpcSubprovider({rpcUrl})); - else engine.addProvider(new WebsocketSubprovider({rpcUrl})); - - engine.start(); - - return web3; - } - } -} - - - -class ScatterEthereumWallet { - constructor(){ - this.getAccounts = this.getAccounts.bind(this); - this.signTransaction = this.signTransaction.bind(this); - } - - async getAccounts(callback) { - const result = await SocketService.sendApiRequest({ - type:'identityFromPermissions', - payload:{} - }); - const accounts = !result ? [] : result.accounts - .filter(account => account.blockchain === Blockchains.ETH) - .map(account => account.address); - - callback(null, accounts); - return accounts; - } - - async signTransaction(transaction){ - if(!ethNetwork) throw Error.noNetwork(); - - // Basic settings - if (transaction.gas !== undefined) transaction.gasLimit = transaction.gas; - transaction.value = transaction.value || '0x00'; - if(transaction.hasOwnProperty('data')) transaction.data = ethUtil.addHexPrefix(transaction.data); - - // Required Fields - const requiredFields = transaction.hasOwnProperty('requiredFields') ? transaction.requiredFields : {}; - - // Contract ABI - const abi = transaction.hasOwnProperty('abi') ? transaction.abi : null; - if(!abi && transaction.hasOwnProperty('data')) - throw Error.signatureError('no_abi', 'You must provide a JSON ABI along with your transaction so that users can read the contract'); - - const payload = Object.assign(transaction, { blockchain:Blockchains.ETH, network:ethNetwork, requiredFields }); - const {signatures, returnedFields} = await SocketService.sendApiRequest({ - type:'requestSignature', - payload - }); - - if(transaction.hasOwnProperty('fieldsCallback')) - transaction.fieldsCallback(returnedFields); - - return signatures[0]; - } -} +// import ETH from './defaults/eth'; /*** * Setting up for plugin based generators, @@ -482,7 +399,7 @@ class PluginRepositorySingleton { loadPlugins(){ this.plugins.push(new EOS()); - this.plugins.push(new ETH()); + // this.plugins.push(new ETH()); } signatureProviders(){ @@ -645,6 +562,22 @@ class Scatter { }); } + getPublicKey(blockchain){ + throwNoAuth(); + return SocketService.sendApiRequest({ + type:'getPublicKey', + payload:{ blockchain } + }); + } + + linkAccount(publicKey, account, network){ + throwNoAuth(); + return SocketService.sendApiRequest({ + type:'linkAccount', + payload:{ publicKey, account, network } + }); + } + suggestNetwork(network){ throwNoAuth(); return SocketService.sendApiRequest({ diff --git a/dist/scatter.min.js b/dist/scatter.min.js index 755bed9d..d165c706 100644 --- a/dist/scatter.min.js +++ b/dist/scatter.min.js @@ -60,7 +60,7 @@ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 185); +/******/ return __webpack_require__(__webpack_require__.s = 141); /******/ }) /************************************************************************/ /******/ ([ @@ -175,9 +175,9 @@ if (typeof Object.create === 'function') { -var base64 = __webpack_require__(222) -var ieee754 = __webpack_require__(223) -var isArray = __webpack_require__(224) +var base64 = __webpack_require__(179) +var ieee754 = __webpack_require__(180) +var isArray = __webpack_require__(181) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer @@ -2057,7 +2057,7 @@ function isBuffer(b) { // 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. -var util = __webpack_require__(8); +var util = __webpack_require__(235); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { @@ -2506,8 +2506,8 @@ if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef /* 7 */ /***/ (function(module, exports, __webpack_require__) { -var store = __webpack_require__(75)('wks'); -var uid = __webpack_require__(54); +var store = __webpack_require__(56)('wks'); +var uid = __webpack_require__(41); var Symbol = __webpack_require__(6).Symbol; var USE_SYMBOL = typeof Symbol == 'function'; @@ -2523,49924 +2523,35956 @@ $exports.store = store; /* 8 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(global, process) {// 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. +var isObject = __webpack_require__(14); +module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; +}; -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; +/***/ }), +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { +/* WEBPACK VAR INJECTION */(function(process) {/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } +exports = module.exports = __webpack_require__(171); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); - if (process.noDeprecation === true) { - return fn; +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; } - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; } - return deprecated; -}; + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } - return debugs[set]; }; /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. + * Colorize log arguments if enabled. * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. + * @api public */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; +function formatArgs(args) { + var useColors = this.useColors; -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.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] -}; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; + if (!useColors) return; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } + args.splice(lastC, 0, c); } +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -function stylizeNoColor(str, styleType) { - return str; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + return r; +} - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } +exports.enable(load()); - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - var base = '', array = false, braces = ['{', '}']; +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17))) - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } +var BigInteger = __webpack_require__(126) - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } +//addons +__webpack_require__(238) - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } +module.exports = BigInteger - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); +var global = __webpack_require__(6); +var core = __webpack_require__(5); +var ctx = __webpack_require__(38); +var hide = __webpack_require__(12); +var has = __webpack_require__(16); +var PROTOTYPE = 'prototype'; + +var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var IS_WRAP = type & $export.W; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE]; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; + var key, own, out; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if (own && has(exports, key)) continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function (C) { + var F = function (a, b, c) { + if (this instanceof C) { + switch (arguments.length) { + case 0: return new C(); + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if (IS_PROTO) { + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); } } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; - ctx.seen.push(value); - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { - ctx.seen.pop(); +var dP = __webpack_require__(13); +var createDesc = __webpack_require__(40); +module.exports = __webpack_require__(15) ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); +} : function (object, key, value) { + object[key] = value; + return object; +}; - return reduceToSingleString(output, base, braces); -} +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} +var anObject = __webpack_require__(8); +var IE8_DOM_DEFINE = __webpack_require__(80); +var toPrimitive = __webpack_require__(52); +var dP = Object.defineProperty; +exports.f = __webpack_require__(15) ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; +}; -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - return name + ': ' + str; -} +/***/ }), +/* 14 */ +/***/ (function(module, exports) { +module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} +// Thank's IE8 for his funny defineProperty +module.exports = !__webpack_require__(21)(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; +}); -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; +/***/ }), +/* 16 */ +/***/ (function(module, exports) { -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function (it, key) { + return hasOwnProperty.call(it, key); +}; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; +/***/ }), +/* 17 */ +/***/ (function(module, exports) { -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +// shim for using process in browser +var process = module.exports = {}; -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; +// 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. -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; +var cachedSetTimeout; +var cachedClearTimeout; -function isUndefined(arg) { - return arg === void 0; +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); } -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); } -exports.isRegExp = isRegExp; +(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 isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; } -exports.isDate = isDate; +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); + } + } -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; } -exports.isPrimitive = isPrimitive; - -exports.isBuffer = __webpack_require__(276); +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; -function objectToString(o) { - return Object.prototype.toString.call(o); +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; -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); + 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); + } +}; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; } - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +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() {} -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = __webpack_require__(1); +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; -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; +process.listeners = function (name) { return [] } - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; +process.binding = function (name) { + throw new Error('process.binding is not supported'); }; -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(11))) /***/ }), -/* 9 */ +/* 18 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) { - 'use strict'; +var Buffer = __webpack_require__(0).Buffer +var Transform = __webpack_require__(117).Transform +var StringDecoder = __webpack_require__(73).StringDecoder +var inherits = __webpack_require__(1) - // Utils - function assert (val, msg) { - if (!val) throw new Error(msg || 'Assertion failed'); +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) - // Could use `inherits` module, but don't want to move from single file - // architecture yet. - function inherits (ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; +CipherBase.prototype.update = function (data, inputEnc, outputEnc) { + if (typeof data === 'string') { + data = Buffer.from(data, inputEnc) } - // BN + var outData = this._update(data) + if (this.hashMode) return this - function BN (number, base, endian) { - if (BN.isBN(number)) { - return number; - } + if (outputEnc) { + outData = this._toString(outData, outputEnc) + } - this.negative = 0; - this.words = null; - this.length = 0; + return outData +} - // Reduction context - this.red = null; +CipherBase.prototype.setAutoPadding = function () {} +CipherBase.prototype.getAuthTag = function () { + throw new Error('trying to get auth tag in unsupported state') +} - if (number !== null) { - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } +CipherBase.prototype.setAuthTag = function () { + throw new Error('trying to set auth tag in unsupported state') +} - this._init(number || 0, base || 10, endian || 'be'); +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) } - if (typeof module === 'object') { - module.exports = BN; - } else { - exports.BN = BN; - } - - BN.BN = BN; - BN.wordSize = 26; - - var Buffer; +} +CipherBase.prototype._flush = function (done) { + var err try { - Buffer = __webpack_require__(295).Buffer; + this.push(this.__final()) } catch (e) { + err = e } - BN.isBN = function isBN (num) { - if (num instanceof BN) { - return true; - } - - return num !== null && typeof num === 'object' && - num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); - }; - - BN.max = function max (left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; + done(err) +} +CipherBase.prototype._finalOrDigest = function (outputEnc) { + var outData = this.__final() || Buffer.alloc(0) + if (outputEnc) { + outData = this._toString(outData, outputEnc, true) + } + return outData +} - BN.min = function min (left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; +CipherBase.prototype._toString = function (value, enc, fin) { + if (!this._decoder) { + this._decoder = new StringDecoder(enc) + this._encoding = enc + } - BN.prototype._init = function init (number, base, endian) { - if (typeof number === 'number') { - return this._initNumber(number, base, endian); - } + if (this._encoding !== enc) throw new Error('can\'t switch encodings') - if (typeof number === 'object') { - return this._initArray(number, base, endian); - } + var out = this._decoder.write(value) + if (fin) { + out += this._decoder.end() + } - if (base === 'hex') { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); + return out +} - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') { - start++; - } +module.exports = CipherBase - if (base === 16) { - this._parseHex(number, start); - } else { - this._parseBase(number, base, start); - } - if (number[0] === '-') { - this.negative = 1; - } +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { - this.strip(); +"use strict"; +// 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. - if (endian !== 'le') return; +// 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. - this._initArray(this.toArray(), base, endian); - }; - BN.prototype._initNumber = function _initNumber (number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else if (number < 0x10000000000000) { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } else { - assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff, - 1 - ]; - this.length = 3; - } - if (endian !== 'le') return; +/**/ - // Reverse the bytes - this._initArray(this.toArray(), base, endian); - }; +var pna = __webpack_require__(49); +/**/ - BN.prototype._initArray = function _initArray (number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - if (number.length <= 0) { - this.words = [ 0 ]; - this.length = 1; - return this; - } +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } +module.exports = Duplex; - var j, w; - var off = 0; - if (endian === 'be') { - for (i = number.length - 1, j = 0; i >= 0; i -= 3) { - w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (i = 0, j = 0; i < number.length; i += 3) { - w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); - }; +/**/ +var util = __webpack_require__(34); +util.inherits = __webpack_require__(1); +/**/ - function parseHex (str, start, end) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; +var Readable = __webpack_require__(118); +var Writable = __webpack_require__(72); - r <<= 4; +util.inherits(Duplex, Readable); - // 'a' - 'f' - if (c >= 49 && c <= 54) { - r |= c - 49 + 0xa; +{ + // avoid scope creep, the keys array can then be collected + 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]; + } +} - // 'A' - 'F' - } else if (c >= 17 && c <= 22) { - r |= c - 17 + 0xa; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); - // '0' - '9' - } else { - r |= c & 0xf; - } - } - return r; - } + Readable.call(this, options); + Writable.call(this, options); - BN.prototype._parseHex = function _parseHex (number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - this.words[i] = 0; - } + if (options && options.readable === false) this.readable = false; - var j, w; - // Scan 24-bit chunks and add them to the number - var off = 0; - for (i = number.length - 6, j = 0; i >= start; i -= 6) { - w = parseHex(number, i, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - w = parseHex(number, start, i + 6); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); - }; + if (options && options.writable === false) this.writable = false; - function parseBase (str, start, end, mul) { - var r = 0; - var len = Math.min(str.length, end); - for (var i = start; i < len; i++) { - var c = str.charCodeAt(i) - 48; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - r *= mul; + this.once('end', onend); +} - // 'a' - if (c >= 49) { - r += c - 49 + 0xa; +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 () { + return this._writableState.highWaterMark; + } +}); - // 'A' - } else if (c >= 17) { - r += c - 17 + 0xa; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; - // '0' - '9' - } else { - r += c; - } + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; } - return r; + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (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; } +}); - BN.prototype._parseBase = function _parseBase (number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); - // Find length of limb in base - for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { - limbLen++; - } - limbLen--; - limbPow = (limbPow / base) | 0; + pna.nextTick(cb, err); +}; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { - var word = 0; - for (var i = start; i < end; i += limbLen) { - word = parseBase(number, i, i + limbLen, base); +"use strict"; - this.imuln(limbPow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); +var createHash = __webpack_require__(76); +var createHmac = __webpack_require__(245); - for (i = 0; i < mod; i++) { - pow *= base; - } +/** @namespace hash */ - this.imuln(pow); - if (this.words[0] + word < 0x4000000) { - this.words[0] += word; - } else { - this._iaddn(word); - } - } - }; +/** @arg {string|Buffer} data + @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' + @return {string|Buffer} - Buffer when resultEncoding is null, or string +*/ +function sha1(data, resultEncoding) { + return createHash('sha1').update(data).digest(resultEncoding); +} - BN.prototype.copy = function copy (dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) { - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; +/** @arg {string|Buffer} data + @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' + @return {string|Buffer} - Buffer when resultEncoding is null, or string +*/ +function sha256(data, resultEncoding) { + return createHash('sha256').update(data).digest(resultEncoding); +} - BN.prototype.clone = function clone () { - var r = new BN(null); - this.copy(r); - return r; - }; +/** @arg {string|Buffer} data + @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' + @return {string|Buffer} - Buffer when resultEncoding is null, or string +*/ +function sha512(data, resultEncoding) { + return createHash('sha512').update(data).digest(resultEncoding); +} - BN.prototype._expand = function _expand (size) { - while (this.length < size) { - this.words[this.length++] = 0; - } - return this; - }; +function HmacSHA256(buffer, secret) { + return createHmac('sha256', secret).update(buffer).digest(); +} - // Remove leading `0` from `this` - BN.prototype.strip = function strip () { - while (this.length > 1 && this.words[this.length - 1] === 0) { - this.length--; - } - return this._normSign(); - }; +function ripemd160(data) { + return createHash('rmd160').update(data).digest(); +} - BN.prototype._normSign = function _normSign () { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; +// function hash160(buffer) { +// return ripemd160(sha256(buffer)) +// } +// +// function hash256(buffer) { +// return sha256(sha256(buffer)) +// } - BN.prototype.inspect = function inspect () { - return (this.red ? ''; - }; +// +// function HmacSHA512(buffer, secret) { +// return crypto.createHmac('sha512', secret).update(buffer).digest() +// } - /* +module.exports = { + sha1: sha1, + sha256: sha256, + sha512: sha512, + HmacSHA256: HmacSHA256, + ripemd160: ripemd160 + // hash160: hash160, + // hash256: hash256, + // HmacSHA512: HmacSHA512 +}; - var zeros = []; - var groupSizes = []; - var groupBases = []; +/***/ }), +/* 21 */ +/***/ (function(module, exports) { - var s = ''; - var i = -1; - while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; - } - groupSizes[0] = 0; - groupSizes[1] = 0; - groupBases[0] = 0; - groupBases[1] = 0; - var base = 2 - 1; - while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; +module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; } +}; - */ - - var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' - ]; - var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 - ]; +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { - var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 - ]; +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = __webpack_require__(82); +var defined = __webpack_require__(53); +module.exports = function (it) { + return IObject(defined(it)); +}; - BN.prototype.toString = function toString (base, padding) { - base = base || 10; - padding = padding | 0 || 1; - var out; - if (base === 16 || base === 'hex') { - out = ''; - var off = 0; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } +/***/ }), +/* 23 */ +/***/ (function(module, exports) { - if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - out = ''; - var c = this.clone(); - c.negative = 0; - while (!c.isZero()) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); +module.exports = {}; - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = '0' + out; - } - while (out.length % padding !== 0) { - out = '0' + out; - } - if (this.negative !== 0) { - out = '-' + out; - } - return out; - } - assert(false, 'Base should be between 2 and 36'); - }; +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { - BN.prototype.toNumber = function toNumber () { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 0x4000000; - } else if (this.length === 3 && this.words[2] === 0x01) { - // NOTE: at this stage it is known that the top bit is set - ret += 0x10000000000000 + (this.words[1] * 0x4000000); - } else if (this.length > 2) { - assert(false, 'Number can only safely store up to 53 bits'); - } - return (this.negative !== 0) ? -ret : ret; - }; + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; - BN.prototype.toJSON = function toJSON () { - return this.toString(16); - }; - BN.prototype.toBuffer = function toBuffer (endian, length) { - assert(typeof Buffer !== 'undefined'); - return this.toArrayLike(Buffer, endian, length); - }; +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { - BN.prototype.toArray = function toArray (endian, length) { - return this.toArrayLike(Array, endian, length); - }; +/* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + */ - BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, 'byte array longer than desired length'); - assert(reqLength > 0, 'Requested array length <= 0'); +var keys = __webpack_require__(178); +var hasBinary = __webpack_require__(101); +var sliceBuffer = __webpack_require__(182); +var after = __webpack_require__(183); +var utf8 = __webpack_require__(184); - this.strip(); - var littleEndian = endian === 'le'; - var res = new ArrayType(reqLength); +var base64encoder; +if (global && global.ArrayBuffer) { + base64encoder = __webpack_require__(185); +} - var b, i; - var q = this.clone(); - if (!littleEndian) { - // Assume big-endian - for (i = 0; i < reqLength - byteLength; i++) { - res[i] = 0; - } +/** + * Check if we are running an android browser. That requires us to use + * ArrayBuffer with polling transports... + * + * http://ghinda.net/jpeg-blob-ajax-android/ + */ - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); - res[reqLength - i - 1] = b; - } - } else { - for (i = 0; !q.isZero(); i++) { - b = q.andln(0xff); - q.iushrn(8); +/** + * Check if we are running in PhantomJS. + * Uploading a Blob with PhantomJS does not work correctly, as reported here: + * https://github.com/ariya/phantomjs/issues/11395 + * @type boolean + */ +var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); - res[i] = b; - } +/** + * When true, avoids using Blobs to encode payloads. + * @type boolean + */ +var dontSendBlobs = isAndroid || isPhantomJS; - for (; i < reqLength; i++) { - res[i] = 0; - } - } +/** + * Current protocol version. + */ - return res; - }; +exports.protocol = 3; - if (Math.clz32) { - BN.prototype._countBits = function _countBits (w) { - return 32 - Math.clz32(w); - }; - } else { - BN.prototype._countBits = function _countBits (w) { - var t = w; - var r = 0; - if (t >= 0x1000) { - r += 13; - t >>>= 13; - } - if (t >= 0x40) { - r += 7; - t >>>= 7; - } - if (t >= 0x8) { - r += 4; - t >>>= 4; - } - if (t >= 0x02) { - r += 2; - t >>>= 2; - } - return r + t; - }; - } +/** + * Packet types. + */ - BN.prototype._zeroBits = function _zeroBits (w) { - // Short-cut - if (w === 0) return 26; +var packets = exports.packets = { + open: 0 // non-ws + , close: 1 // non-ws + , ping: 2 + , pong: 3 + , message: 4 + , upgrade: 5 + , noop: 6 +}; - var t = w; - var r = 0; - if ((t & 0x1fff) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 0x7f) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 0xf) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 0x3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 0x1) === 0) { - r++; - } - return r; - }; +var packetslist = keys(packets); - // Return number of used bits in a BN - BN.prototype.bitLength = function bitLength () { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; +/** + * Premade error packet. + */ - function toBitArray (num) { - var w = new Array(num.bitLength()); +var err = { type: 'error', data: 'parser error' }; - for (var bit = 0; bit < w.length; bit++) { - var off = (bit / 26) | 0; - var wbit = bit % 26; +/** + * Create a blob api even for blob builder when vendor prefixes exist + */ - w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; - } +var Blob = __webpack_require__(186); - return w; +/** + * Encodes a packet. + * + * [ ] + * + * Example: + * + * 5hello world + * 3 + * 4 + * + * Binary is encoded in an identical principle + * + * @api private + */ + +exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { + if (typeof supportsBinary === 'function') { + callback = supportsBinary; + supportsBinary = false; } - // Number of trailing zero bits - BN.prototype.zeroBits = function zeroBits () { - if (this.isZero()) return 0; + if (typeof utf8encode === 'function') { + callback = utf8encode; + utf8encode = null; + } - var r = 0; - for (var i = 0; i < this.length; i++) { - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; + var data = (packet.data === undefined) + ? undefined + : packet.data.buffer || packet.data; - BN.prototype.byteLength = function byteLength () { - return Math.ceil(this.bitLength() / 8); - }; + if (global.ArrayBuffer && data instanceof ArrayBuffer) { + return encodeArrayBuffer(packet, supportsBinary, callback); + } else if (Blob && data instanceof global.Blob) { + return encodeBlob(packet, supportsBinary, callback); + } - BN.prototype.toTwos = function toTwos (width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); - } - return this.clone(); - }; + // might be an object with { base64: true, data: dataAsBase64String } + if (data && data.base64) { + return encodeBase64Object(packet, callback); + } - BN.prototype.fromTwos = function fromTwos (width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); - } - return this.clone(); - }; + // Sending data as a utf-8 string + var encoded = packets[packet.type]; - BN.prototype.isNeg = function isNeg () { - return this.negative !== 0; - }; + // data fragment is optional + if (undefined !== packet.data) { + encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data); + } - // Return negative clone of `this` - BN.prototype.neg = function neg () { - return this.clone().ineg(); - }; + return callback('' + encoded); - BN.prototype.ineg = function ineg () { - if (!this.isZero()) { - this.negative ^= 1; - } +}; - return this; - }; +function encodeBase64Object(packet, callback) { + // packet data is an object { base64: true, data: dataAsBase64String } + var message = 'b' + exports.packets[packet.type] + packet.data.data; + return callback(message); +} - // Or `num` with `this` in-place - BN.prototype.iuor = function iuor (num) { - while (this.length < num.length) { - this.words[this.length++] = 0; - } +/** + * Encode packet helpers for binary types + */ - for (var i = 0; i < num.length; i++) { - this.words[i] = this.words[i] | num.words[i]; - } +function encodeArrayBuffer(packet, supportsBinary, callback) { + if (!supportsBinary) { + return exports.encodeBase64Packet(packet, callback); + } - return this.strip(); - }; + var data = packet.data; + var contentArray = new Uint8Array(data); + var resultBuffer = new Uint8Array(1 + data.byteLength); - BN.prototype.ior = function ior (num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; + resultBuffer[0] = packets[packet.type]; + for (var i = 0; i < contentArray.length; i++) { + resultBuffer[i+1] = contentArray[i]; + } - // Or `num` with `this` - BN.prototype.or = function or (num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; + return callback(resultBuffer.buffer); +} - BN.prototype.uor = function uor (num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); - }; +function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { + if (!supportsBinary) { + return exports.encodeBase64Packet(packet, callback); + } - // And `num` with `this` in-place - BN.prototype.iuand = function iuand (num) { - // b = min-length(num, this) - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } + var fr = new FileReader(); + fr.onload = function() { + packet.data = fr.result; + exports.encodePacket(packet, supportsBinary, true, callback); + }; + return fr.readAsArrayBuffer(packet.data); +} - for (var i = 0; i < b.length; i++) { - this.words[i] = this.words[i] & num.words[i]; - } +function encodeBlob(packet, supportsBinary, callback) { + if (!supportsBinary) { + return exports.encodeBase64Packet(packet, callback); + } - this.length = b.length; + if (dontSendBlobs) { + return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); + } - return this.strip(); - }; + var length = new Uint8Array(1); + length[0] = packets[packet.type]; + var blob = new Blob([length.buffer, packet.data]); - BN.prototype.iand = function iand (num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; + return callback(blob); +} - // And `num` with `this` - BN.prototype.and = function and (num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; +/** + * Encodes a packet with binary data in a base64 string + * + * @param {Object} packet, has `type` and `data` + * @return {String} base64 encoded message + */ - BN.prototype.uand = function uand (num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; +exports.encodeBase64Packet = function(packet, callback) { + var message = 'b' + exports.packets[packet.type]; + if (Blob && packet.data instanceof global.Blob) { + var fr = new FileReader(); + fr.onload = function() { + var b64 = fr.result.split(',')[1]; + callback(message + b64); + }; + return fr.readAsDataURL(packet.data); + } - // Xor `num` with `this` in-place - BN.prototype.iuxor = function iuxor (num) { - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + var b64data; + try { + b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); + } catch (e) { + // iPhone Safari doesn't let you apply with typed arrays + var typed = new Uint8Array(packet.data); + var basic = new Array(typed.length); + for (var i = 0; i < typed.length; i++) { + basic[i] = typed[i]; } + b64data = String.fromCharCode.apply(null, basic); + } + message += global.btoa(b64data); + return callback(message); +}; - for (var i = 0; i < b.length; i++) { - this.words[i] = a.words[i] ^ b.words[i]; +/** + * Decodes a packet. Changes format to Blob if requested. + * + * @return {Object} with `type` and `data` (if any) + * @api private + */ + +exports.decodePacket = function (data, binaryType, utf8decode) { + if (data === undefined) { + return err; + } + // String data + if (typeof data === 'string') { + if (data.charAt(0) === 'b') { + return exports.decodeBase64Packet(data.substr(1), binaryType); } - if (this !== a) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (utf8decode) { + data = tryDecode(data); + if (data === false) { + return err; } } + var type = data.charAt(0); - this.length = a.length; - - return this.strip(); - }; - - BN.prototype.ixor = function ixor (num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - - // Xor `num` with `this` - BN.prototype.xor = function xor (num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - - BN.prototype.uxor = function uxor (num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; + if (Number(type) != type || !packetslist[type]) { + return err; + } - // Not ``this`` with ``width`` bitwidth - BN.prototype.inotn = function inotn (width) { - assert(typeof width === 'number' && width >= 0); + if (data.length > 1) { + return { type: packetslist[type], data: data.substring(1) }; + } else { + return { type: packetslist[type] }; + } + } - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; + var asArray = new Uint8Array(data); + var type = asArray[0]; + var rest = sliceBuffer(data, 1); + if (Blob && binaryType === 'blob') { + rest = new Blob([rest]); + } + return { type: packetslist[type], data: rest }; +}; - // Extend the buffer with leading zeroes - this._expand(bytesNeeded); +function tryDecode(data) { + try { + data = utf8.decode(data, { strict: false }); + } catch (e) { + return false; + } + return data; +} - if (bitsLeft > 0) { - bytesNeeded--; - } +/** + * Decodes a packet encoded in a base64 string + * + * @param {String} base64 encoded message + * @return {Object} with `type` and `data` (if any) + */ - // Handle complete words - for (var i = 0; i < bytesNeeded; i++) { - this.words[i] = ~this.words[i] & 0x3ffffff; - } +exports.decodeBase64Packet = function(msg, binaryType) { + var type = packetslist[msg.charAt(0)]; + if (!base64encoder) { + return { type: type, data: { base64: true, data: msg.substr(1) } }; + } - // Handle the residue - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); - } + var data = base64encoder.decode(msg.substr(1)); - // And remove leading zeroes - return this.strip(); - }; + if (binaryType === 'blob' && Blob) { + data = new Blob([data]); + } - BN.prototype.notn = function notn (width) { - return this.clone().inotn(width); - }; + return { type: type, data: data }; +}; - // Set `bit` of `this` - BN.prototype.setn = function setn (bit, val) { - assert(typeof bit === 'number' && bit >= 0); +/** + * Encodes multiple messages (payload). + * + * :data + * + * Example: + * + * 11:hello world2:hi + * + * If any contents are binary, they will be encoded as base64 strings. Base64 + * encoded strings are marked with a b before the length specifier + * + * @param {Array} packets + * @api private + */ - var off = (bit / 26) | 0; - var wbit = bit % 26; +exports.encodePayload = function (packets, supportsBinary, callback) { + if (typeof supportsBinary === 'function') { + callback = supportsBinary; + supportsBinary = null; + } - this._expand(off + 1); + var isBinary = hasBinary(packets); - if (val) { - this.words[off] = this.words[off] | (1 << wbit); - } else { - this.words[off] = this.words[off] & ~(1 << wbit); + if (supportsBinary && isBinary) { + if (Blob && !dontSendBlobs) { + return exports.encodePayloadAsBlob(packets, callback); } - return this.strip(); - }; + return exports.encodePayloadAsArrayBuffer(packets, callback); + } - // Add `num` to `this` in-place - BN.prototype.iadd = function iadd (num) { - var r; + if (!packets.length) { + return callback('0:'); + } - // negative + positive - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); + function setLengthHeader(message) { + return message.length + ':' + message; + } - // positive + negative - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } + function encodeOne(packet, doneCallback) { + exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) { + doneCallback(null, setLengthHeader(message)); + }); + } - // a.length > b.length - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } + map(packets, encodeOne, function(err, results) { + return callback(results.join('')); + }); +}; - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } +/** + * Async array map using after + */ - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; - } - } +function map(ary, each, done) { + var result = new Array(ary.length); + var next = after(ary.length, done); - return this; + var eachWithIndex = function(i, el, cb) { + each(el, function(error, msg) { + result[i] = msg; + cb(error, result); + }); }; - // Add `num` to `this` - BN.prototype.add = function add (num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } + for (var i = 0; i < ary.length; i++) { + eachWithIndex(i, ary[i], next); + } +} - if (this.length > num.length) return this.clone().iadd(num); +/* + * Decodes data when a payload is maybe expected. Possible binary contents are + * decoded from their base64 representation + * + * @param {String} data, callback method + * @api public + */ - return num.clone().iadd(this); - }; +exports.decodePayload = function (data, binaryType, callback) { + if (typeof data !== 'string') { + return exports.decodePayloadAsBinary(data, binaryType, callback); + } - // Subtract `num` from `this` in-place - BN.prototype.isub = function isub (num) { - // this - (-num) = this + num - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); + if (typeof binaryType === 'function') { + callback = binaryType; + binaryType = null; + } - // -this - num = -(this + num) - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } + var packet; + if (data === '') { + // parser error - ignoring payload + return callback(err, 0, 1); + } - // At this point both numbers are positive - var cmp = this.cmp(num); + var length = '', n, msg; - // Optimization - zeroify - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } + for (var i = 0, l = data.length; i < l; i++) { + var chr = data.charAt(i); - // a > b - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; + if (chr !== ':') { + length += chr; + continue; } - var carry = 0; - for (var i = 0; i < b.length; i++) { - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + if (length === '' || (length != (n = Number(length)))) { + // parser error - ignoring payload + return callback(err, 0, 1); } - for (; carry !== 0 && i < a.length; i++) { - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 0x3ffffff; + + msg = data.substr(i + 1, n); + + if (length != msg.length) { + // parser error - ignoring payload + return callback(err, 0, 1); } - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) { - for (; i < a.length; i++) { - this.words[i] = a.words[i]; + if (msg.length) { + packet = exports.decodePacket(msg, binaryType, false); + + if (err.type === packet.type && err.data === packet.data) { + // parser error in individual packet - ignoring payload + return callback(err, 0, 1); } + + var ret = callback(packet, i + n, l); + if (false === ret) return; } - this.length = Math.max(this.length, i); + // advance cursor + i += n; + length = ''; + } - if (a !== this) { - this.negative = 1; - } + if (length !== '') { + // parser error - ignoring payload + return callback(err, 0, 1); + } - return this.strip(); - }; +}; - // Subtract `num` from `this` - BN.prototype.sub = function sub (num) { - return this.clone().isub(num); - }; +/** + * Encodes multiple messages (payload) as binary. + * + * <1 = binary, 0 = string>[...] + * + * Example: + * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers + * + * @param {Array} packets + * @return {ArrayBuffer} encoded payload + * @api private + */ - function smallMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - var len = (self.length + num.length) | 0; - out.length = len; - len = (len - 1) | 0; +exports.encodePayloadAsArrayBuffer = function(packets, callback) { + if (!packets.length) { + return callback(new ArrayBuffer(0)); + } - // Peel one iteration (compiler can't do it, because of code complexity) - var a = self.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; + function encodeOne(packet, doneCallback) { + exports.encodePacket(packet, true, true, function(data) { + return doneCallback(null, data); + }); + } - var lo = r & 0x3ffffff; - var carry = (r / 0x4000000) | 0; - out.words[0] = lo; + map(packets, encodeOne, function(err, encodedPackets) { + var totalLength = encodedPackets.reduce(function(acc, p) { + var len; + if (typeof p === 'string'){ + len = p.length; + } else { + len = p.byteLength; + } + return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 + }, 0); - for (var k = 1; k < len; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = (k - j) | 0; - a = self.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += (r / 0x4000000) | 0; - rword = r & 0x3ffffff; + var resultArray = new Uint8Array(totalLength); + + var bufferIndex = 0; + encodedPackets.forEach(function(p) { + var isString = typeof p === 'string'; + var ab = p; + if (isString) { + var view = new Uint8Array(p.length); + for (var i = 0; i < p.length; i++) { + view[i] = p.charCodeAt(i); + } + ab = view.buffer; } - out.words[k] = rword | 0; - carry = ncarry | 0; + + if (isString) { // not true binary + resultArray[bufferIndex++] = 0; + } else { // true binary + resultArray[bufferIndex++] = 1; + } + + var lenStr = ab.byteLength.toString(); + for (var i = 0; i < lenStr.length; i++) { + resultArray[bufferIndex++] = parseInt(lenStr[i]); + } + resultArray[bufferIndex++] = 255; + + var view = new Uint8Array(ab); + for (var i = 0; i < view.length; i++) { + resultArray[bufferIndex++] = view[i]; + } + }); + + return callback(resultArray.buffer); + }); +}; + +/** + * Encode as Blob + */ + +exports.encodePayloadAsBlob = function(packets, callback) { + function encodeOne(packet, doneCallback) { + exports.encodePacket(packet, true, true, function(encoded) { + var binaryIdentifier = new Uint8Array(1); + binaryIdentifier[0] = 1; + if (typeof encoded === 'string') { + var view = new Uint8Array(encoded.length); + for (var i = 0; i < encoded.length; i++) { + view[i] = encoded.charCodeAt(i); + } + encoded = view.buffer; + binaryIdentifier[0] = 0; + } + + var len = (encoded instanceof ArrayBuffer) + ? encoded.byteLength + : encoded.size; + + var lenStr = len.toString(); + var lengthAry = new Uint8Array(lenStr.length + 1); + for (var i = 0; i < lenStr.length; i++) { + lengthAry[i] = parseInt(lenStr[i]); + } + lengthAry[lenStr.length] = 255; + + if (Blob) { + var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); + doneCallback(null, blob); + } + }); + } + + map(packets, encodeOne, function(err, results) { + return callback(new Blob(results)); + }); +}; + +/* + * Decodes data when a payload is maybe expected. Strings are decoded by + * interpreting each byte as a key code for entries marked to start with 0. See + * description of encodePayloadAsBinary + * + * @param {ArrayBuffer} data, callback method + * @api public + */ + +exports.decodePayloadAsBinary = function (data, binaryType, callback) { + if (typeof binaryType === 'function') { + callback = binaryType; + binaryType = null; + } + + var bufferTail = data; + var buffers = []; + + while (bufferTail.byteLength > 0) { + var tailArray = new Uint8Array(bufferTail); + var isString = tailArray[0] === 0; + var msgLength = ''; + + for (var i = 1; ; i++) { + if (tailArray[i] === 255) break; + + // 310 = char length of Number.MAX_VALUE + if (msgLength.length > 310) { + return callback(err, 0, 1); + } + + msgLength += tailArray[i]; } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; + + bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); + msgLength = parseInt(msgLength); + + var msg = sliceBuffer(bufferTail, 0, msgLength); + if (isString) { + try { + msg = String.fromCharCode.apply(null, new Uint8Array(msg)); + } catch (e) { + // iPhone Safari doesn't let you apply to typed arrays + var typed = new Uint8Array(msg); + msg = ''; + for (var i = 0; i < typed.length; i++) { + msg += String.fromCharCode(typed[i]); + } + } } - return out.strip(); + buffers.push(msg); + bufferTail = sliceBuffer(bufferTail, msgLength); } - // TODO(indutny): it may be reasonable to omit it for users who don't need - // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit - // multiplication (like elliptic secp256k1). - var comb10MulTo = function comb10MulTo (self, num, out) { - var a = self.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 0x1fff; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 0x1fff; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 0x1fff; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 0x1fff; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 0x1fff; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 0x1fff; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 0x1fff; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 0x1fff; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 0x1fff; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 0x1fff; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 0x1fff; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 0x1fff; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 0x1fff; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 0x1fff; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 0x1fff; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 0x1fff; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 0x1fff; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 0x1fff; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 0x1fff; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 0x1fff; - var bh9 = b9 >>> 13; + var total = buffers.length; + buffers.forEach(function(buffer, i) { + callback(exports.decodePacket(buffer, binaryType, true), i, total); + }); +}; - out.negative = self.negative ^ num.negative; - out.length = 19; - /* k = 0 */ - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = (mid + Math.imul(ah0, bl0)) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; - w0 &= 0x3ffffff; - /* k = 1 */ - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = (mid + Math.imul(ah1, bl0)) | 0; - hi = Math.imul(ah1, bh0); - lo = (lo + Math.imul(al0, bl1)) | 0; - mid = (mid + Math.imul(al0, bh1)) | 0; - mid = (mid + Math.imul(ah0, bl1)) | 0; - hi = (hi + Math.imul(ah0, bh1)) | 0; - var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; - w1 &= 0x3ffffff; - /* k = 2 */ - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = (mid + Math.imul(ah2, bl0)) | 0; - hi = Math.imul(ah2, bh0); - lo = (lo + Math.imul(al1, bl1)) | 0; - mid = (mid + Math.imul(al1, bh1)) | 0; - mid = (mid + Math.imul(ah1, bl1)) | 0; - hi = (hi + Math.imul(ah1, bh1)) | 0; - lo = (lo + Math.imul(al0, bl2)) | 0; - mid = (mid + Math.imul(al0, bh2)) | 0; - mid = (mid + Math.imul(ah0, bl2)) | 0; - hi = (hi + Math.imul(ah0, bh2)) | 0; - var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; - w2 &= 0x3ffffff; - /* k = 3 */ - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = (mid + Math.imul(ah3, bl0)) | 0; - hi = Math.imul(ah3, bh0); - lo = (lo + Math.imul(al2, bl1)) | 0; - mid = (mid + Math.imul(al2, bh1)) | 0; - mid = (mid + Math.imul(ah2, bl1)) | 0; - hi = (hi + Math.imul(ah2, bh1)) | 0; - lo = (lo + Math.imul(al1, bl2)) | 0; - mid = (mid + Math.imul(al1, bh2)) | 0; - mid = (mid + Math.imul(ah1, bl2)) | 0; - hi = (hi + Math.imul(ah1, bh2)) | 0; - lo = (lo + Math.imul(al0, bl3)) | 0; - mid = (mid + Math.imul(al0, bh3)) | 0; - mid = (mid + Math.imul(ah0, bl3)) | 0; - hi = (hi + Math.imul(ah0, bh3)) | 0; - var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; - w3 &= 0x3ffffff; - /* k = 4 */ - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = (mid + Math.imul(ah4, bl0)) | 0; - hi = Math.imul(ah4, bh0); - lo = (lo + Math.imul(al3, bl1)) | 0; - mid = (mid + Math.imul(al3, bh1)) | 0; - mid = (mid + Math.imul(ah3, bl1)) | 0; - hi = (hi + Math.imul(ah3, bh1)) | 0; - lo = (lo + Math.imul(al2, bl2)) | 0; - mid = (mid + Math.imul(al2, bh2)) | 0; - mid = (mid + Math.imul(ah2, bl2)) | 0; - hi = (hi + Math.imul(ah2, bh2)) | 0; - lo = (lo + Math.imul(al1, bl3)) | 0; - mid = (mid + Math.imul(al1, bh3)) | 0; - mid = (mid + Math.imul(ah1, bl3)) | 0; - hi = (hi + Math.imul(ah1, bh3)) | 0; - lo = (lo + Math.imul(al0, bl4)) | 0; - mid = (mid + Math.imul(al0, bh4)) | 0; - mid = (mid + Math.imul(ah0, bl4)) | 0; - hi = (hi + Math.imul(ah0, bh4)) | 0; - var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; - w4 &= 0x3ffffff; - /* k = 5 */ - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = (mid + Math.imul(ah5, bl0)) | 0; - hi = Math.imul(ah5, bh0); - lo = (lo + Math.imul(al4, bl1)) | 0; - mid = (mid + Math.imul(al4, bh1)) | 0; - mid = (mid + Math.imul(ah4, bl1)) | 0; - hi = (hi + Math.imul(ah4, bh1)) | 0; - lo = (lo + Math.imul(al3, bl2)) | 0; - mid = (mid + Math.imul(al3, bh2)) | 0; - mid = (mid + Math.imul(ah3, bl2)) | 0; - hi = (hi + Math.imul(ah3, bh2)) | 0; - lo = (lo + Math.imul(al2, bl3)) | 0; - mid = (mid + Math.imul(al2, bh3)) | 0; - mid = (mid + Math.imul(ah2, bl3)) | 0; - hi = (hi + Math.imul(ah2, bh3)) | 0; - lo = (lo + Math.imul(al1, bl4)) | 0; - mid = (mid + Math.imul(al1, bh4)) | 0; - mid = (mid + Math.imul(ah1, bl4)) | 0; - hi = (hi + Math.imul(ah1, bh4)) | 0; - lo = (lo + Math.imul(al0, bl5)) | 0; - mid = (mid + Math.imul(al0, bh5)) | 0; - mid = (mid + Math.imul(ah0, bl5)) | 0; - hi = (hi + Math.imul(ah0, bh5)) | 0; - var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; - w5 &= 0x3ffffff; - /* k = 6 */ - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = (mid + Math.imul(ah6, bl0)) | 0; - hi = Math.imul(ah6, bh0); - lo = (lo + Math.imul(al5, bl1)) | 0; - mid = (mid + Math.imul(al5, bh1)) | 0; - mid = (mid + Math.imul(ah5, bl1)) | 0; - hi = (hi + Math.imul(ah5, bh1)) | 0; - lo = (lo + Math.imul(al4, bl2)) | 0; - mid = (mid + Math.imul(al4, bh2)) | 0; - mid = (mid + Math.imul(ah4, bl2)) | 0; - hi = (hi + Math.imul(ah4, bh2)) | 0; - lo = (lo + Math.imul(al3, bl3)) | 0; - mid = (mid + Math.imul(al3, bh3)) | 0; - mid = (mid + Math.imul(ah3, bl3)) | 0; - hi = (hi + Math.imul(ah3, bh3)) | 0; - lo = (lo + Math.imul(al2, bl4)) | 0; - mid = (mid + Math.imul(al2, bh4)) | 0; - mid = (mid + Math.imul(ah2, bl4)) | 0; - hi = (hi + Math.imul(ah2, bh4)) | 0; - lo = (lo + Math.imul(al1, bl5)) | 0; - mid = (mid + Math.imul(al1, bh5)) | 0; - mid = (mid + Math.imul(ah1, bl5)) | 0; - hi = (hi + Math.imul(ah1, bh5)) | 0; - lo = (lo + Math.imul(al0, bl6)) | 0; - mid = (mid + Math.imul(al0, bh6)) | 0; - mid = (mid + Math.imul(ah0, bl6)) | 0; - hi = (hi + Math.imul(ah0, bh6)) | 0; - var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; - w6 &= 0x3ffffff; - /* k = 7 */ - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = (mid + Math.imul(ah7, bl0)) | 0; - hi = Math.imul(ah7, bh0); - lo = (lo + Math.imul(al6, bl1)) | 0; - mid = (mid + Math.imul(al6, bh1)) | 0; - mid = (mid + Math.imul(ah6, bl1)) | 0; - hi = (hi + Math.imul(ah6, bh1)) | 0; - lo = (lo + Math.imul(al5, bl2)) | 0; - mid = (mid + Math.imul(al5, bh2)) | 0; - mid = (mid + Math.imul(ah5, bl2)) | 0; - hi = (hi + Math.imul(ah5, bh2)) | 0; - lo = (lo + Math.imul(al4, bl3)) | 0; - mid = (mid + Math.imul(al4, bh3)) | 0; - mid = (mid + Math.imul(ah4, bl3)) | 0; - hi = (hi + Math.imul(ah4, bh3)) | 0; - lo = (lo + Math.imul(al3, bl4)) | 0; - mid = (mid + Math.imul(al3, bh4)) | 0; - mid = (mid + Math.imul(ah3, bl4)) | 0; - hi = (hi + Math.imul(ah3, bh4)) | 0; - lo = (lo + Math.imul(al2, bl5)) | 0; - mid = (mid + Math.imul(al2, bh5)) | 0; - mid = (mid + Math.imul(ah2, bl5)) | 0; - hi = (hi + Math.imul(ah2, bh5)) | 0; - lo = (lo + Math.imul(al1, bl6)) | 0; - mid = (mid + Math.imul(al1, bh6)) | 0; - mid = (mid + Math.imul(ah1, bl6)) | 0; - hi = (hi + Math.imul(ah1, bh6)) | 0; - lo = (lo + Math.imul(al0, bl7)) | 0; - mid = (mid + Math.imul(al0, bh7)) | 0; - mid = (mid + Math.imul(ah0, bl7)) | 0; - hi = (hi + Math.imul(ah0, bh7)) | 0; - var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; - w7 &= 0x3ffffff; - /* k = 8 */ - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = (mid + Math.imul(ah8, bl0)) | 0; - hi = Math.imul(ah8, bh0); - lo = (lo + Math.imul(al7, bl1)) | 0; - mid = (mid + Math.imul(al7, bh1)) | 0; - mid = (mid + Math.imul(ah7, bl1)) | 0; - hi = (hi + Math.imul(ah7, bh1)) | 0; - lo = (lo + Math.imul(al6, bl2)) | 0; - mid = (mid + Math.imul(al6, bh2)) | 0; - mid = (mid + Math.imul(ah6, bl2)) | 0; - hi = (hi + Math.imul(ah6, bh2)) | 0; - lo = (lo + Math.imul(al5, bl3)) | 0; - mid = (mid + Math.imul(al5, bh3)) | 0; - mid = (mid + Math.imul(ah5, bl3)) | 0; - hi = (hi + Math.imul(ah5, bh3)) | 0; - lo = (lo + Math.imul(al4, bl4)) | 0; - mid = (mid + Math.imul(al4, bh4)) | 0; - mid = (mid + Math.imul(ah4, bl4)) | 0; - hi = (hi + Math.imul(ah4, bh4)) | 0; - lo = (lo + Math.imul(al3, bl5)) | 0; - mid = (mid + Math.imul(al3, bh5)) | 0; - mid = (mid + Math.imul(ah3, bl5)) | 0; - hi = (hi + Math.imul(ah3, bh5)) | 0; - lo = (lo + Math.imul(al2, bl6)) | 0; - mid = (mid + Math.imul(al2, bh6)) | 0; - mid = (mid + Math.imul(ah2, bl6)) | 0; - hi = (hi + Math.imul(ah2, bh6)) | 0; - lo = (lo + Math.imul(al1, bl7)) | 0; - mid = (mid + Math.imul(al1, bh7)) | 0; - mid = (mid + Math.imul(ah1, bl7)) | 0; - hi = (hi + Math.imul(ah1, bh7)) | 0; - lo = (lo + Math.imul(al0, bl8)) | 0; - mid = (mid + Math.imul(al0, bh8)) | 0; - mid = (mid + Math.imul(ah0, bl8)) | 0; - hi = (hi + Math.imul(ah0, bh8)) | 0; - var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; - w8 &= 0x3ffffff; - /* k = 9 */ - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = (mid + Math.imul(ah9, bl0)) | 0; - hi = Math.imul(ah9, bh0); - lo = (lo + Math.imul(al8, bl1)) | 0; - mid = (mid + Math.imul(al8, bh1)) | 0; - mid = (mid + Math.imul(ah8, bl1)) | 0; - hi = (hi + Math.imul(ah8, bh1)) | 0; - lo = (lo + Math.imul(al7, bl2)) | 0; - mid = (mid + Math.imul(al7, bh2)) | 0; - mid = (mid + Math.imul(ah7, bl2)) | 0; - hi = (hi + Math.imul(ah7, bh2)) | 0; - lo = (lo + Math.imul(al6, bl3)) | 0; - mid = (mid + Math.imul(al6, bh3)) | 0; - mid = (mid + Math.imul(ah6, bl3)) | 0; - hi = (hi + Math.imul(ah6, bh3)) | 0; - lo = (lo + Math.imul(al5, bl4)) | 0; - mid = (mid + Math.imul(al5, bh4)) | 0; - mid = (mid + Math.imul(ah5, bl4)) | 0; - hi = (hi + Math.imul(ah5, bh4)) | 0; - lo = (lo + Math.imul(al4, bl5)) | 0; - mid = (mid + Math.imul(al4, bh5)) | 0; - mid = (mid + Math.imul(ah4, bl5)) | 0; - hi = (hi + Math.imul(ah4, bh5)) | 0; - lo = (lo + Math.imul(al3, bl6)) | 0; - mid = (mid + Math.imul(al3, bh6)) | 0; - mid = (mid + Math.imul(ah3, bl6)) | 0; - hi = (hi + Math.imul(ah3, bh6)) | 0; - lo = (lo + Math.imul(al2, bl7)) | 0; - mid = (mid + Math.imul(al2, bh7)) | 0; - mid = (mid + Math.imul(ah2, bl7)) | 0; - hi = (hi + Math.imul(ah2, bh7)) | 0; - lo = (lo + Math.imul(al1, bl8)) | 0; - mid = (mid + Math.imul(al1, bh8)) | 0; - mid = (mid + Math.imul(ah1, bl8)) | 0; - hi = (hi + Math.imul(ah1, bh8)) | 0; - lo = (lo + Math.imul(al0, bl9)) | 0; - mid = (mid + Math.imul(al0, bh9)) | 0; - mid = (mid + Math.imul(ah0, bl9)) | 0; - hi = (hi + Math.imul(ah0, bh9)) | 0; - var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; - w9 &= 0x3ffffff; - /* k = 10 */ - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = (mid + Math.imul(ah9, bl1)) | 0; - hi = Math.imul(ah9, bh1); - lo = (lo + Math.imul(al8, bl2)) | 0; - mid = (mid + Math.imul(al8, bh2)) | 0; - mid = (mid + Math.imul(ah8, bl2)) | 0; - hi = (hi + Math.imul(ah8, bh2)) | 0; - lo = (lo + Math.imul(al7, bl3)) | 0; - mid = (mid + Math.imul(al7, bh3)) | 0; - mid = (mid + Math.imul(ah7, bl3)) | 0; - hi = (hi + Math.imul(ah7, bh3)) | 0; - lo = (lo + Math.imul(al6, bl4)) | 0; - mid = (mid + Math.imul(al6, bh4)) | 0; - mid = (mid + Math.imul(ah6, bl4)) | 0; - hi = (hi + Math.imul(ah6, bh4)) | 0; - lo = (lo + Math.imul(al5, bl5)) | 0; - mid = (mid + Math.imul(al5, bh5)) | 0; - mid = (mid + Math.imul(ah5, bl5)) | 0; - hi = (hi + Math.imul(ah5, bh5)) | 0; - lo = (lo + Math.imul(al4, bl6)) | 0; - mid = (mid + Math.imul(al4, bh6)) | 0; - mid = (mid + Math.imul(ah4, bl6)) | 0; - hi = (hi + Math.imul(ah4, bh6)) | 0; - lo = (lo + Math.imul(al3, bl7)) | 0; - mid = (mid + Math.imul(al3, bh7)) | 0; - mid = (mid + Math.imul(ah3, bl7)) | 0; - hi = (hi + Math.imul(ah3, bh7)) | 0; - lo = (lo + Math.imul(al2, bl8)) | 0; - mid = (mid + Math.imul(al2, bh8)) | 0; - mid = (mid + Math.imul(ah2, bl8)) | 0; - hi = (hi + Math.imul(ah2, bh8)) | 0; - lo = (lo + Math.imul(al1, bl9)) | 0; - mid = (mid + Math.imul(al1, bh9)) | 0; - mid = (mid + Math.imul(ah1, bl9)) | 0; - hi = (hi + Math.imul(ah1, bh9)) | 0; - var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; - w10 &= 0x3ffffff; - /* k = 11 */ - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = (mid + Math.imul(ah9, bl2)) | 0; - hi = Math.imul(ah9, bh2); - lo = (lo + Math.imul(al8, bl3)) | 0; - mid = (mid + Math.imul(al8, bh3)) | 0; - mid = (mid + Math.imul(ah8, bl3)) | 0; - hi = (hi + Math.imul(ah8, bh3)) | 0; - lo = (lo + Math.imul(al7, bl4)) | 0; - mid = (mid + Math.imul(al7, bh4)) | 0; - mid = (mid + Math.imul(ah7, bl4)) | 0; - hi = (hi + Math.imul(ah7, bh4)) | 0; - lo = (lo + Math.imul(al6, bl5)) | 0; - mid = (mid + Math.imul(al6, bh5)) | 0; - mid = (mid + Math.imul(ah6, bl5)) | 0; - hi = (hi + Math.imul(ah6, bh5)) | 0; - lo = (lo + Math.imul(al5, bl6)) | 0; - mid = (mid + Math.imul(al5, bh6)) | 0; - mid = (mid + Math.imul(ah5, bl6)) | 0; - hi = (hi + Math.imul(ah5, bh6)) | 0; - lo = (lo + Math.imul(al4, bl7)) | 0; - mid = (mid + Math.imul(al4, bh7)) | 0; - mid = (mid + Math.imul(ah4, bl7)) | 0; - hi = (hi + Math.imul(ah4, bh7)) | 0; - lo = (lo + Math.imul(al3, bl8)) | 0; - mid = (mid + Math.imul(al3, bh8)) | 0; - mid = (mid + Math.imul(ah3, bl8)) | 0; - hi = (hi + Math.imul(ah3, bh8)) | 0; - lo = (lo + Math.imul(al2, bl9)) | 0; - mid = (mid + Math.imul(al2, bh9)) | 0; - mid = (mid + Math.imul(ah2, bl9)) | 0; - hi = (hi + Math.imul(ah2, bh9)) | 0; - var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; - w11 &= 0x3ffffff; - /* k = 12 */ - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = (mid + Math.imul(ah9, bl3)) | 0; - hi = Math.imul(ah9, bh3); - lo = (lo + Math.imul(al8, bl4)) | 0; - mid = (mid + Math.imul(al8, bh4)) | 0; - mid = (mid + Math.imul(ah8, bl4)) | 0; - hi = (hi + Math.imul(ah8, bh4)) | 0; - lo = (lo + Math.imul(al7, bl5)) | 0; - mid = (mid + Math.imul(al7, bh5)) | 0; - mid = (mid + Math.imul(ah7, bl5)) | 0; - hi = (hi + Math.imul(ah7, bh5)) | 0; - lo = (lo + Math.imul(al6, bl6)) | 0; - mid = (mid + Math.imul(al6, bh6)) | 0; - mid = (mid + Math.imul(ah6, bl6)) | 0; - hi = (hi + Math.imul(ah6, bh6)) | 0; - lo = (lo + Math.imul(al5, bl7)) | 0; - mid = (mid + Math.imul(al5, bh7)) | 0; - mid = (mid + Math.imul(ah5, bl7)) | 0; - hi = (hi + Math.imul(ah5, bh7)) | 0; - lo = (lo + Math.imul(al4, bl8)) | 0; - mid = (mid + Math.imul(al4, bh8)) | 0; - mid = (mid + Math.imul(ah4, bl8)) | 0; - hi = (hi + Math.imul(ah4, bh8)) | 0; - lo = (lo + Math.imul(al3, bl9)) | 0; - mid = (mid + Math.imul(al3, bh9)) | 0; - mid = (mid + Math.imul(ah3, bl9)) | 0; - hi = (hi + Math.imul(ah3, bh9)) | 0; - var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; - w12 &= 0x3ffffff; - /* k = 13 */ - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = (mid + Math.imul(ah9, bl4)) | 0; - hi = Math.imul(ah9, bh4); - lo = (lo + Math.imul(al8, bl5)) | 0; - mid = (mid + Math.imul(al8, bh5)) | 0; - mid = (mid + Math.imul(ah8, bl5)) | 0; - hi = (hi + Math.imul(ah8, bh5)) | 0; - lo = (lo + Math.imul(al7, bl6)) | 0; - mid = (mid + Math.imul(al7, bh6)) | 0; - mid = (mid + Math.imul(ah7, bl6)) | 0; - hi = (hi + Math.imul(ah7, bh6)) | 0; - lo = (lo + Math.imul(al6, bl7)) | 0; - mid = (mid + Math.imul(al6, bh7)) | 0; - mid = (mid + Math.imul(ah6, bl7)) | 0; - hi = (hi + Math.imul(ah6, bh7)) | 0; - lo = (lo + Math.imul(al5, bl8)) | 0; - mid = (mid + Math.imul(al5, bh8)) | 0; - mid = (mid + Math.imul(ah5, bl8)) | 0; - hi = (hi + Math.imul(ah5, bh8)) | 0; - lo = (lo + Math.imul(al4, bl9)) | 0; - mid = (mid + Math.imul(al4, bh9)) | 0; - mid = (mid + Math.imul(ah4, bl9)) | 0; - hi = (hi + Math.imul(ah4, bh9)) | 0; - var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; - w13 &= 0x3ffffff; - /* k = 14 */ - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = (mid + Math.imul(ah9, bl5)) | 0; - hi = Math.imul(ah9, bh5); - lo = (lo + Math.imul(al8, bl6)) | 0; - mid = (mid + Math.imul(al8, bh6)) | 0; - mid = (mid + Math.imul(ah8, bl6)) | 0; - hi = (hi + Math.imul(ah8, bh6)) | 0; - lo = (lo + Math.imul(al7, bl7)) | 0; - mid = (mid + Math.imul(al7, bh7)) | 0; - mid = (mid + Math.imul(ah7, bl7)) | 0; - hi = (hi + Math.imul(ah7, bh7)) | 0; - lo = (lo + Math.imul(al6, bl8)) | 0; - mid = (mid + Math.imul(al6, bh8)) | 0; - mid = (mid + Math.imul(ah6, bl8)) | 0; - hi = (hi + Math.imul(ah6, bh8)) | 0; - lo = (lo + Math.imul(al5, bl9)) | 0; - mid = (mid + Math.imul(al5, bh9)) | 0; - mid = (mid + Math.imul(ah5, bl9)) | 0; - hi = (hi + Math.imul(ah5, bh9)) | 0; - var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; - w14 &= 0x3ffffff; - /* k = 15 */ - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = (mid + Math.imul(ah9, bl6)) | 0; - hi = Math.imul(ah9, bh6); - lo = (lo + Math.imul(al8, bl7)) | 0; - mid = (mid + Math.imul(al8, bh7)) | 0; - mid = (mid + Math.imul(ah8, bl7)) | 0; - hi = (hi + Math.imul(ah8, bh7)) | 0; - lo = (lo + Math.imul(al7, bl8)) | 0; - mid = (mid + Math.imul(al7, bh8)) | 0; - mid = (mid + Math.imul(ah7, bl8)) | 0; - hi = (hi + Math.imul(ah7, bh8)) | 0; - lo = (lo + Math.imul(al6, bl9)) | 0; - mid = (mid + Math.imul(al6, bh9)) | 0; - mid = (mid + Math.imul(ah6, bl9)) | 0; - hi = (hi + Math.imul(ah6, bh9)) | 0; - var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; - w15 &= 0x3ffffff; - /* k = 16 */ - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = (mid + Math.imul(ah9, bl7)) | 0; - hi = Math.imul(ah9, bh7); - lo = (lo + Math.imul(al8, bl8)) | 0; - mid = (mid + Math.imul(al8, bh8)) | 0; - mid = (mid + Math.imul(ah8, bl8)) | 0; - hi = (hi + Math.imul(ah8, bh8)) | 0; - lo = (lo + Math.imul(al7, bl9)) | 0; - mid = (mid + Math.imul(al7, bh9)) | 0; - mid = (mid + Math.imul(ah7, bl9)) | 0; - hi = (hi + Math.imul(ah7, bh9)) | 0; - var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; - w16 &= 0x3ffffff; - /* k = 17 */ - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = (mid + Math.imul(ah9, bl8)) | 0; - hi = Math.imul(ah9, bh8); - lo = (lo + Math.imul(al8, bl9)) | 0; - mid = (mid + Math.imul(al8, bh9)) | 0; - mid = (mid + Math.imul(ah8, bl9)) | 0; - hi = (hi + Math.imul(ah8, bh9)) | 0; - var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; - w17 &= 0x3ffffff; - /* k = 18 */ - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = (mid + Math.imul(ah9, bl9)) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; - c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; - w18 &= 0x3ffffff; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - - // Polyfill comb - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - - function bigMulTo (self, num, out) { - out.negative = num.negative ^ self.negative; - out.length = self.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = self.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); - } - - function jumboMulTo (self, num, out) { - var fftm = new FFTM(); - return fftm.mulp(self, num, out); - } - - BN.prototype.mulTo = function mulTo (num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - - return res; - }; - - // Cooley-Tukey algorithm for FFT - // slightly revisited to rely on looping instead of recursion - - function FFTM (x, y) { - this.x = x; - this.y = y; - } - - FFTM.prototype.makeRBT = function makeRBT (N) { - var t = new Array(N); - var l = BN.prototype._countBits(N) - 1; - for (var i = 0; i < N; i++) { - t[i] = this.revBin(i, l, N); - } - - return t; - }; - - // Returns binary-reversed representation of `x` - FFTM.prototype.revBin = function revBin (x, l, N) { - if (x === 0 || x === N - 1) return x; - - var rb = 0; - for (var i = 0; i < l; i++) { - rb |= (x & 1) << (l - i - 1); - x >>= 1; - } - - return rb; - }; - - // Performs "tweedling" phase, therefore 'emulating' - // behaviour of the recursive algorithm - FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { - for (var i = 0; i < N; i++) { - rtws[i] = rws[rbt[i]]; - itws[i] = iws[rbt[i]]; - } - }; - - FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { - this.permute(rbt, rws, iws, rtws, itws, N); - - for (var s = 1; s < N; s <<= 1) { - var l = s << 1; - - var rtwdf = Math.cos(2 * Math.PI / l); - var itwdf = Math.sin(2 * Math.PI / l); - - for (var p = 0; p < N; p += l) { - var rtwdf_ = rtwdf; - var itwdf_ = itwdf; - - for (var j = 0; j < s; j++) { - var re = rtws[p + j]; - var ie = itws[p + j]; - - var ro = rtws[p + j + s]; - var io = itws[p + j + s]; - - var rx = rtwdf_ * ro - itwdf_ * io; - - io = rtwdf_ * io + itwdf_ * ro; - ro = rx; - - rtws[p + j] = re + ro; - itws[p + j] = ie + io; - - rtws[p + j + s] = re - ro; - itws[p + j + s] = ie - io; - - /* jshint maxdepth : false */ - if (j !== l) { - rx = rtwdf * rtwdf_ - itwdf * itwdf_; - - itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; - rtwdf_ = rx; - } - } - } - } - }; - - FFTM.prototype.guessLen13b = function guessLen13b (n, m) { - var N = Math.max(m, n) | 1; - var odd = N & 1; - var i = 0; - for (N = N / 2 | 0; N; N = N >>> 1) { - i++; - } - - return 1 << i + 1 + odd; - }; - - FFTM.prototype.conjugate = function conjugate (rws, iws, N) { - if (N <= 1) return; - - for (var i = 0; i < N / 2; i++) { - var t = rws[i]; - - rws[i] = rws[N - i - 1]; - rws[N - i - 1] = t; - - t = iws[i]; - - iws[i] = -iws[N - i - 1]; - iws[N - i - 1] = -t; - } - }; - - FFTM.prototype.normalize13b = function normalize13b (ws, N) { - var carry = 0; - for (var i = 0; i < N / 2; i++) { - var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + - Math.round(ws[2 * i] / N) + - carry; - - ws[i] = w & 0x3ffffff; - - if (w < 0x4000000) { - carry = 0; - } else { - carry = w / 0x4000000 | 0; - } - } - - return ws; - }; - - FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { - var carry = 0; - for (var i = 0; i < len; i++) { - carry = carry + (ws[i] | 0); - - rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; - rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; - } - - // Pad with zeroes - for (i = 2 * len; i < N; ++i) { - rws[i] = 0; - } - - assert(carry === 0); - assert((carry & ~0x1fff) === 0); - }; - - FFTM.prototype.stub = function stub (N) { - var ph = new Array(N); - for (var i = 0; i < N; i++) { - ph[i] = 0; - } - - return ph; - }; - - FFTM.prototype.mulp = function mulp (x, y, out) { - var N = 2 * this.guessLen13b(x.length, y.length); - - var rbt = this.makeRBT(N); - - var _ = this.stub(N); - - var rws = new Array(N); - var rwst = new Array(N); - var iwst = new Array(N); - - var nrws = new Array(N); - var nrwst = new Array(N); - var niwst = new Array(N); - - var rmws = out.words; - rmws.length = N; - - this.convert13b(x.words, x.length, rws, N); - this.convert13b(y.words, y.length, nrws, N); - - this.transform(rws, _, rwst, iwst, N, rbt); - this.transform(nrws, _, nrwst, niwst, N, rbt); - - for (var i = 0; i < N; i++) { - var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; - iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; - rwst[i] = rx; - } - - this.conjugate(rwst, iwst, N); - this.transform(rwst, iwst, rmws, _, N, rbt); - this.conjugate(rmws, _, N); - this.normalize13b(rmws, N); - - out.negative = x.negative ^ y.negative; - out.length = x.length + y.length; - return out.strip(); - }; - - // Multiply `this` by `num` - BN.prototype.mul = function mul (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - - // Multiply employing FFT - BN.prototype.mulf = function mulf (num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - - // In-place Multiplication - BN.prototype.imul = function imul (num) { - return this.clone().mulTo(num, this); - }; - - BN.prototype.imuln = function imuln (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - // Carry - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = (this.words[i] | 0) * num; - var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); - carry >>= 26; - carry += (w / 0x4000000) | 0; - // NOTE: lo is 27bit maximum - carry += lo >>> 26; - this.words[i] = lo & 0x3ffffff; - } +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - - return this; - }; - - BN.prototype.muln = function muln (num) { - return this.clone().imuln(num); - }; - - // `this` * `this` - BN.prototype.sqr = function sqr () { - return this.mul(this); - }; - - // `this` * `this` in-place - BN.prototype.isqr = function isqr () { - return this.imul(this.clone()); - }; - - // Math.pow(`this`, `num`) - BN.prototype.pow = function pow (num) { - var w = toBitArray(num); - if (w.length === 0) return new BN(1); - - // Skip leading zeroes - var res = this; - for (var i = 0; i < w.length; i++, res = res.sqr()) { - if (w[i] !== 0) break; - } - - if (++i < w.length) { - for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { - if (w[i] === 0) continue; - - res = res.mul(q); - } - } - - return res; - }; - - // Shift-left in-place - BN.prototype.iushln = function iushln (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - var i; - - if (r !== 0) { - var carry = 0; - - for (i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = ((this.words[i] | 0) - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (i = this.length - 1; i >= 0; i--) { - this.words[i + s] = this.words[i]; - } - - for (i = 0; i < s; i++) { - this.words[i] = 0; - } - - this.length += s; - } - - return this.strip(); - }; - - BN.prototype.ishln = function ishln (bits) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushln(bits); - }; - - // Shift-right in-place - // NOTE: `hint` is a lowest bit before trailing zeroes - // NOTE: if `extended` is present - it will be filled with destroyed bits - BN.prototype.iushrn = function iushrn (bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - var h; - if (hint) { - h = (hint - (hint % 26)) / 26; - } else { - h = 0; - } - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - h -= s; - h = Math.max(0, h); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) { - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (i = 0; i < this.length; i++) { - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { - var word = this.words[i] | 0; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - return this.strip(); - }; - - BN.prototype.ishrn = function ishrn (bits, hint, extended) { - // TODO(indutny): implement me - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - - // Shift-left - BN.prototype.shln = function shln (bits) { - return this.clone().ishln(bits); - }; - - BN.prototype.ushln = function ushln (bits) { - return this.clone().iushln(bits); - }; - - // Shift-right - BN.prototype.shrn = function shrn (bits) { - return this.clone().ishrn(bits); - }; - - BN.prototype.ushrn = function ushrn (bits) { - return this.clone().iushrn(bits); - }; - - // Test if n bit is set - BN.prototype.testn = function testn (bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) return false; - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); - }; - - // Return only lowers bits of number (in-place) - BN.prototype.imaskn = function imaskn (bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(this.negative === 0, 'imaskn works only with positive numbers'); - - if (this.length <= s) { - return this; - } - - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); - }; - - // Return only lowers bits of number - BN.prototype.maskn = function maskn (bits) { - return this.clone().imaskn(bits); - }; - - // Add plain number `num` to `this` - BN.prototype.iaddn = function iaddn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.isubn(-num); - - // Possible sign change - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) < num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - - // Add without checks - return this._iaddn(num); - }; - - BN.prototype._iaddn = function _iaddn (num) { - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - - return this; - }; - - // Subtract plain number `num` from `this` - BN.prototype.isubn = function isubn (num) { - assert(typeof num === 'number'); - assert(num < 0x4000000); - if (num < 0) return this.iaddn(-num); - - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - - this.words[0] -= num; - - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - } - - return this.strip(); - }; - - BN.prototype.addn = function addn (num) { - return this.clone().iaddn(num); - }; - - BN.prototype.subn = function subn (num) { - return this.clone().isubn(num); - }; - - BN.prototype.iabs = function iabs () { - this.negative = 0; - - return this; - }; - - BN.prototype.abs = function abs () { - return this.clone().iabs(); - }; - - BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { - var len = num.length + shift; - var i; - - this._expand(len); - - var w; - var carry = 0; - for (i = 0; i < num.length; i++) { - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 0x3ffffff; - carry = (w >> 26) - ((right / 0x4000000) | 0); - this.words[i + shift] = w & 0x3ffffff; - } - for (; i < this.length - shift; i++) { - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 0x3ffffff; - } - - if (carry === 0) return this.strip(); - - // Subtraction overflow - assert(carry === -1); - carry = 0; - for (i = 0; i < this.length; i++) { - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 0x3ffffff; - } - this.negative = 1; - - return this.strip(); - }; - - BN.prototype._wordDiv = function _wordDiv (num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - // Normalize - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - - // Initialize quotient - var m = a.length - b.length; - var q; - - if (mode !== 'mod') { - q = new BN(null); - q.length = m + 1; - q.words = new Array(q.length); - for (var i = 0; i < q.length; i++) { - q.words[i] = 0; - } - } - - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - - for (var j = m - 1; j >= 0; j--) { - var qj = (a.words[b.length + j] | 0) * 0x4000000 + - (a.words[b.length + j - 1] | 0); - - // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max - // (0x7ffffff) - qj = Math.min((qj / bhi) | 0, 0x3ffffff); - - a._ishlnsubmul(b, qj, j); - while (a.negative !== 0) { - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; - } - } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q.strip(); - } - a.strip(); - - // Denormalize - if (mode !== 'div' && shift !== 0) { - a.iushrn(shift); - } - - return { - div: q || null, - mod: a - }; - }; - - // NOTE: 1) `mode` can be set to `mod` to request mod only, - // to `div` to request div only, or be absent to - // request both div & mod - // 2) `positive` is true if unsigned mod is requested - BN.prototype.divmod = function divmod (num, mode, positive) { - assert(!num.isZero()); - - if (this.isZero()) { - return { - div: new BN(0), - mod: new BN(0) - }; - } - - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } - } - - return { - div: div, - mod: mod - }; - } - - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - - if (mode !== 'mod') { - div = res.div.neg(); - } - - return { - div: div, - mod: res.mod - }; - } - - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - - if (mode !== 'div') { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } - } - - return { - div: res.div, - mod: mod - }; - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN(0), - mod: this - }; - } - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') { - return { - div: this.divn(num.words[0]), - mod: null - }; - } - - if (mode === 'mod') { - return { - div: null, - mod: new BN(this.modn(num.words[0])) - }; - } - - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); - }; - - // Find `this` / `num` - BN.prototype.div = function div (num) { - return this.divmod(num, 'div', false).div; - }; - - // Find `this` % `num` - BN.prototype.mod = function mod (num) { - return this.divmod(num, 'mod', false).mod; - }; - - BN.prototype.umod = function umod (num) { - return this.divmod(num, 'mod', true).mod; - }; - - // Find Round(`this` / `num`) - BN.prototype.divRound = function divRound (num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.isZero()) return dm.div; - - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - - // Round up - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - - BN.prototype.modn = function modn (num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) { - acc = (p * acc + (this.words[i] | 0)) % num; - } - - return acc; - }; - - // In-place division by number - BN.prototype.idivn = function idivn (num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = (this.words[i] | 0) + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); - }; - - BN.prototype.divn = function divn (num) { - return this.clone().idivn(num); - }; - - BN.prototype.egcd = function egcd (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var x = this; - var y = p.clone(); - - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - - // A * x + B * y = x - var A = new BN(1); - var B = new BN(0); - - // C * x + D * y = y - var C = new BN(0); - var D = new BN(1); - - var g = 0; - - while (x.isEven() && y.isEven()) { - x.iushrn(1); - y.iushrn(1); - ++g; - } - - var yp = y.clone(); - var xp = x.clone(); - - while (!x.isZero()) { - for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while (i-- > 0) { - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - - A.iushrn(1); - B.iushrn(1); - } - } - - for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while (j-- > 0) { - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - - C.iushrn(1); - D.iushrn(1); - } - } - - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } - } - - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - - // This is reduced incarnation of the binary EEA - // above, designated to invert members of the - // _prime_ fields F(p) at a maximal speed - BN.prototype._invmp = function _invmp (p) { - assert(p.negative === 0); - assert(!p.isZero()); - - var a = this; - var b = p.clone(); - - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - - var x1 = new BN(1); - var x2 = new BN(0); - - var delta = b.clone(); - - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while (i-- > 0) { - if (x1.isOdd()) { - x1.iadd(delta); - } - - x1.iushrn(1); - } - } - - for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while (j-- > 0) { - if (x2.isOdd()) { - x2.iadd(delta); - } - - x2.iushrn(1); - } - } - - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - - if (res.cmpn(0) < 0) { - res.iadd(p); - } - - return res; - }; - - BN.prototype.gcd = function gcd (num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.iushrn(1); - b.iushrn(1); - } - - do { - while (a.isEven()) { - a.iushrn(1); - } - while (b.isEven()) { - b.iushrn(1); - } - - var r = a.cmp(b); - if (r < 0) { - // Swap `a` and `b` to make `a` always bigger than `b` - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - - a.isub(b); - } while (true); - - return b.iushln(shift); - }; - - // Invert number in the field F(num) - BN.prototype.invm = function invm (num) { - return this.egcd(num).a.umod(num); - }; - - BN.prototype.isEven = function isEven () { - return (this.words[0] & 1) === 0; - }; - - BN.prototype.isOdd = function isOdd () { - return (this.words[0] & 1) === 1; - }; - - // And first word and num - BN.prototype.andln = function andln (num) { - return this.words[0] & num; - }; - - // Increment at the bit position in-line - BN.prototype.bincn = function bincn (bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - - BN.prototype.isZero = function isZero () { - return this.length === 1 && this.words[0] === 0; - }; - - BN.prototype.cmpn = function cmpn (num) { - var negative = num < 0; - - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - - assert(num <= 0x3ffffff, 'Number is too big'); - - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Compare two numbers and return: - // 1 - if `this` > `num` - // 0 - if `this` == `num` - // -1 - if `this` < `num` - BN.prototype.cmp = function cmp (num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - - // Unsigned comparison - BN.prototype.ucmp = function ucmp (num) { - // At this point both numbers have the same sign - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i] | 0; - var b = num.words[i] | 0; - - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - - BN.prototype.gtn = function gtn (num) { - return this.cmpn(num) === 1; - }; - - BN.prototype.gt = function gt (num) { - return this.cmp(num) === 1; - }; - - BN.prototype.gten = function gten (num) { - return this.cmpn(num) >= 0; - }; - - BN.prototype.gte = function gte (num) { - return this.cmp(num) >= 0; - }; - - BN.prototype.ltn = function ltn (num) { - return this.cmpn(num) === -1; - }; - - BN.prototype.lt = function lt (num) { - return this.cmp(num) === -1; - }; - - BN.prototype.lten = function lten (num) { - return this.cmpn(num) <= 0; - }; - - BN.prototype.lte = function lte (num) { - return this.cmp(num) <= 0; - }; - - BN.prototype.eqn = function eqn (num) { - return this.cmpn(num) === 0; - }; - - BN.prototype.eq = function eq (num) { - return this.cmp(num) === 0; - }; - - // - // A reduce context, could be using montgomery or something better, depending - // on the `m` itself. - // - BN.red = function red (num) { - return new Red(num); - }; - - BN.prototype.toRed = function toRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(this.negative === 0, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); - }; - - BN.prototype.fromRed = function fromRed () { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); - }; - - BN.prototype._forceRed = function _forceRed (ctx) { - this.red = ctx; - return this; - }; - - BN.prototype.forceRed = function forceRed (ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); - }; - - BN.prototype.redAdd = function redAdd (num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); - }; - - BN.prototype.redIAdd = function redIAdd (num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); - }; - - BN.prototype.redSub = function redSub (num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); - }; - - BN.prototype.redISub = function redISub (num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); - }; - - BN.prototype.redShl = function redShl (num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); - }; - - BN.prototype.redMul = function redMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - - BN.prototype.redIMul = function redIMul (num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - - BN.prototype.redSqr = function redSqr () { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); - }; - - BN.prototype.redISqr = function redISqr () { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); - }; - - // Square root over p - BN.prototype.redSqrt = function redSqrt () { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); - }; - - BN.prototype.redInvm = function redInvm () { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); - }; - - // Return negative clone of `this` % `red modulo` - BN.prototype.redNeg = function redNeg () { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); - }; - - BN.prototype.redPow = function redPow (num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); - }; - - // Prime numbers with efficient reduction - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - - // Pseudo-Mersenne prime - function MPrime (name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).iushln(this.n).isub(this.p); - - this.tmp = this._tmp(); - } - - MPrime.prototype._tmp = function _tmp () { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - - MPrime.prototype.ireduce = function ireduce (num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; - }; - - MPrime.prototype.split = function split (input, out) { - input.iushrn(this.n, 0, out); - }; - - MPrime.prototype.imulK = function imulK (num) { - return num.imul(this.k); - }; - - function K256 () { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); - } - inherits(K256, MPrime); - - K256.prototype.split = function split (input, output) { - // 256 = 9 * 26 + 22 - var mask = 0x3fffff; - - var outLen = Math.min(input.length, 9); - for (var i = 0; i < outLen; i++) { - output.words[i] = input.words[i]; - } - output.length = outLen; - - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - - // Shift by 9 limbs - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - - for (i = 10; i < input.length; i++) { - var next = input.words[i] | 0; - input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - - K256.prototype.imulK = function imulK (num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i] | 0; - lo += w * 0x3d1; - num.words[i] = lo & 0x3ffffff; - lo = w * 0x40 + ((lo / 0x4000000) | 0); - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - - function P224 () { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); - } - inherits(P224, MPrime); - - function P192 () { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); - } - inherits(P192, MPrime); - - function P25519 () { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); - } - inherits(P25519, MPrime); - - P25519.prototype.imulK = function imulK (num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = (num.words[i] | 0) * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - - // Exported mostly for testing purposes, use plain name instead - BN._prime = function prime (name) { - // Cached version of prime - if (primes[name]) return primes[name]; - - var prime; - if (name === 'k256') { - prime = new K256(); - } else if (name === 'p224') { - prime = new P224(); - } else if (name === 'p192') { - prime = new P192(); - } else if (name === 'p25519') { - prime = new P25519(); - } else { - throw new Error('Unknown prime ' + name); - } - primes[name] = prime; - - return prime; - }; - - // - // Base reduction engine - // - function Red (m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), 'modulus must be greater than 1'); - this.m = m; - this.prime = null; - } - } - - Red.prototype._verify1 = function _verify1 (a) { - assert(a.negative === 0, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); - }; - - Red.prototype._verify2 = function _verify2 (a, b) { - assert((a.negative | b.negative) === 0, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); - }; - - Red.prototype.imod = function imod (a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - return a.umod(this.m)._forceRed(this); - }; - - Red.prototype.neg = function neg (a) { - if (a.isZero()) { - return a.clone(); - } - - return this.m.sub(a)._forceRed(this); - }; - - Red.prototype.add = function add (a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.iadd = function iadd (a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - - Red.prototype.sub = function sub (a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - - Red.prototype.isub = function isub (a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - - Red.prototype.shl = function shl (a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - - Red.prototype.imul = function imul (a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - - Red.prototype.mul = function mul (a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - - Red.prototype.isqr = function isqr (a) { - return this.imul(a, a.clone()); - }; - - Red.prototype.sqr = function sqr (a) { - return this.mul(a, a); - }; - - Red.prototype.sqrt = function sqrt (a) { - if (a.isZero()) return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).iushrn(2); - return this.pow(a, pow); - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (!q.isZero() && q.andln(1) === 0) { - s++; - q.iushrn(1); - } - assert(!q.isZero()); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - - while (this.pow(z, lpow).cmp(nOne) !== 0) { - z.redIAdd(nOne); - } - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) { - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN(1).iushln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; - }; - - Red.prototype.invm = function invm (a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - - Red.prototype.pow = function pow (a, num) { - if (num.isZero()) return new BN(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN(1).toRed(this); - wnd[1] = a; - for (var i = 2; i < wnd.length; i++) { - wnd[i] = this.mul(wnd[i - 1], a); - } - - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - - for (i = num.length - 1; i >= 0; i--) { - var word = num.words[i]; - for (var j = start - 1; j >= 0; j--) { - var bit = (word >> j) & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - - return res; - }; - - Red.prototype.convertTo = function convertTo (num) { - var r = num.umod(this.m); - - return r === num ? r.clone() : r; - }; - - Red.prototype.convertFrom = function convertFrom (num) { - var res = num.clone(); - res.red = null; - return res; - }; - - // - // Montgomery method engine - // - - BN.mont = function mont (num) { - return new Mont(num); - }; - - function Mont (m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - (this.shift % 26); - } - - this.r = new BN(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - - Mont.prototype.convertTo = function convertTo (num) { - return this.imod(num.ushln(this.shift)); - }; - - Mont.prototype.convertFrom = function convertFrom (num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - - Mont.prototype.imul = function imul (a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.mul = function mul (a, b) { - if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - - return res._forceRed(this); - }; - - Mont.prototype.invm = function invm (a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; -})(typeof module === 'undefined' || module, this); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(59)(module))) - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var elliptic = exports; - -elliptic.version = __webpack_require__(345).version; -elliptic.utils = __webpack_require__(346); -elliptic.rand = __webpack_require__(347); -elliptic.curve = __webpack_require__(66); -elliptic.curves = __webpack_require__(353); - -// Protocols -elliptic.ec = __webpack_require__(361); -elliptic.eddsa = __webpack_require__(365); - - -/***/ }), -/* 11 */ -/***/ (function(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; }; - - -/***/ }), -/* 12 */ -/***/ (function(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. - -function EventEmitter() { - this._events = this._events || {}; - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -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. -EventEmitter.defaultMaxListeners = 10; - -// 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(n) { - if (!isNumber(n) || n < 0 || isNaN(n)) - throw TypeError('n must be a positive number'); - this._maxListeners = n; - return this; -}; - -EventEmitter.prototype.emit = function(type) { - var er, handler, len, args, i, listeners; - - if (!this._events) - this._events = {}; - - // If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || - (isObject(this._events.error) && !this._events.error.length)) { - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - } - } - - handler = this._events[type]; - - if (isUndefined(handler)) - return false; - - if (isFunction(handler)) { - switch (arguments.length) { - // fast cases - case 1: - handler.call(this); - break; - case 2: - handler.call(this, arguments[1]); - break; - case 3: - handler.call(this, arguments[1], arguments[2]); - break; - // slower - default: - args = Array.prototype.slice.call(arguments, 1); - handler.apply(this, args); - } - } else if (isObject(handler)) { - args = Array.prototype.slice.call(arguments, 1); - listeners = handler.slice(); - len = listeners.length; - for (i = 0; i < len; i++) - listeners[i].apply(this, args); - } - - return true; -}; - -EventEmitter.prototype.addListener = function(type, listener) { - var m; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events) - this._events = {}; - - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) - this.emit('newListener', type, - isFunction(listener.listener) ? - listener.listener : listener); - - if (!this._events[type]) - // Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; - else if (isObject(this._events[type])) - // If we've already got an array, just append. - this._events[type].push(listener); - else - // Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener]; - - // Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { - m = this._maxListeners; - } else { - m = EventEmitter.defaultMaxListeners; - } - - if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; - console.error('(node) warning: possible EventEmitter memory ' + - 'leak detected. %d listeners added. ' + - 'Use emitter.setMaxListeners() to increase limit.', - this._events[type].length); - if (typeof console.trace === 'function') { - // not supported in IE 10 - console.trace(); - } - } - } - - return this; -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.once = function(type, listener) { - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - var fired = false; - - function g() { - this.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(this, arguments); - } - } - - g.listener = listener; - this.on(type, g); - - return this; -}; - -// emits a 'removeListener' event iff the listener was removed -EventEmitter.prototype.removeListener = function(type, listener) { - var list, position, length, i; - - if (!isFunction(listener)) - throw TypeError('listener must be a function'); - - if (!this._events || !this._events[type]) - return this; - - list = this._events[type]; - length = list.length; - position = -1; - - if (list === listener || - (isFunction(list.listener) && list.listener === listener)) { - delete this._events[type]; - if (this._events.removeListener) - this.emit('removeListener', type, listener); - - } else if (isObject(list)) { - for (i = length; i-- > 0;) { - if (list[i] === listener || - (list[i].listener && list[i].listener === listener)) { - position = i; - break; - } - } - - if (position < 0) - return this; - - if (list.length === 1) { - list.length = 0; - delete this._events[type]; - } else { - list.splice(position, 1); - } - - if (this._events.removeListener) - this.emit('removeListener', type, listener); - } - - return this; -}; - -EventEmitter.prototype.removeAllListeners = function(type) { - var key, listeners; - - if (!this._events) - return this; - - // not listening for removeListener, no need to emit - if (!this._events.removeListener) { - if (arguments.length === 0) - this._events = {}; - else if (this._events[type]) - delete this._events[type]; - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - for (key in this._events) { - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = {}; - return this; - } - - listeners = this._events[type]; - - if (isFunction(listeners)) { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - while (listeners.length) - this.removeListener(type, listeners[listeners.length - 1]); - } - delete this._events[type]; - - return this; -}; - -EventEmitter.prototype.listeners = function(type) { - var ret; - if (!this._events || !this._events[type]) - ret = []; - else if (isFunction(this._events[type])) - ret = [this._events[type]]; - else - ret = this._events[type].slice(); - return ret; -}; - -EventEmitter.prototype.listenerCount = function(type) { - if (this._events) { - var evlistener = this._events[type]; - - if (isFunction(evlistener)) - return 1; - else if (evlistener) - return evlistener.length; - } - return 0; -}; - -EventEmitter.listenerCount = function(emitter, type) { - return emitter.listenerCount(type); -}; - -function isFunction(arg) { - return typeof arg === 'function'; -} - -function isNumber(arg) { - return typeof arg === 'number'; -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -function isUndefined(arg) { - return arg === void 0; -} - - -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var assert = __webpack_require__(26); -var inherits = __webpack_require__(1); - -exports.inherits = inherits; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -exports.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -exports.toHex = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -exports.htonl = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -exports.toHex32 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -exports.zero2 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -exports.zero8 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -exports.join32 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -exports.split32 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -exports.rotr32 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -exports.rotl32 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -exports.sum32 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -exports.sum32_3 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -exports.sum32_4 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -exports.sum32_5 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -exports.sum64 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -exports.sum64_hi = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -exports.sum64_lo = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -exports.sum64_4_hi = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -exports.sum64_4_lo = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -exports.sum64_5_hi = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -exports.sum64_5_lo = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -exports.rotr64_hi = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.rotr64_lo = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -exports.shr64_hi = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.shr64_lo = shr64_lo; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -var isObject = __webpack_require__(20); -module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; -}; - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(process) {/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = __webpack_require__(214); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', - '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', - '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', - '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', - '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', - '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', - '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', - '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', - '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', - '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', - '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - -var BigInteger = __webpack_require__(150) - -//addons -__webpack_require__(278) - -module.exports = BigInteger - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var ctx = __webpack_require__(51); -var hide = __webpack_require__(18); -var has = __webpack_require__(22); -var PROTOTYPE = 'prototype'; - -var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var IS_WRAP = type & $export.W; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE]; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]; - var key, own, out; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if (own && has(exports, key)) continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function (C) { - var F = function (a, b, c) { - if (this instanceof C) { - switch (arguments.length) { - case 0: return new C(); - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if (IS_PROTO) { - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out); - } - } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -$export.U = 64; // safe -$export.R = 128; // real proto method for `library` -module.exports = $export; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -var dP = __webpack_require__(19); -var createDesc = __webpack_require__(53); -module.exports = __webpack_require__(21) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); -} : function (object, key, value) { - object[key] = value; - return object; -}; - - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -var anObject = __webpack_require__(14); -var IE8_DOM_DEFINE = __webpack_require__(106); -var toPrimitive = __webpack_require__(71); -var dP = Object.defineProperty; - -exports.f = __webpack_require__(21) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; -}; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports) { - -module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; -}; - - -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { - -// Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(28)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; -}); - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function (it, key) { - return hasOwnProperty.call(it, key); -}; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(63).Transform -var StringDecoder = __webpack_require__(91).StringDecoder -var inherits = __webpack_require__(1) - -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 - - -/***/ }), -/* 24 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// 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. - - - -/**/ - -var pna = __webpack_require__(64); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = __webpack_require__(43); -util.inherits = __webpack_require__(1); -/**/ - -var Readable = __webpack_require__(141); -var Writable = __webpack_require__(90); - -util.inherits(Duplex, Readable); - -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); -} - -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 () { - return this._writableState.highWaterMark; - } -}); - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (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; - } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - pna.nextTick(cb, err); -}; - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var createHash = __webpack_require__(45); -var createHmac = __webpack_require__(285); - -/** @namespace hash */ - -/** @arg {string|Buffer} data - @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' - @return {string|Buffer} - Buffer when resultEncoding is null, or string -*/ -function sha1(data, resultEncoding) { - return createHash('sha1').update(data).digest(resultEncoding); -} - -/** @arg {string|Buffer} data - @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' - @return {string|Buffer} - Buffer when resultEncoding is null, or string -*/ -function sha256(data, resultEncoding) { - return createHash('sha256').update(data).digest(resultEncoding); -} - -/** @arg {string|Buffer} data - @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64' - @return {string|Buffer} - Buffer when resultEncoding is null, or string -*/ -function sha512(data, resultEncoding) { - return createHash('sha512').update(data).digest(resultEncoding); -} - -function HmacSHA256(buffer, secret) { - return createHmac('sha256', secret).update(buffer).digest(); -} - -function ripemd160(data) { - return createHash('rmd160').update(data).digest(); -} - -// function hash160(buffer) { -// return ripemd160(sha256(buffer)) -// } -// -// function hash256(buffer) { -// return sha256(sha256(buffer)) -// } - -// -// function HmacSHA512(buffer, secret) { -// return crypto.createHmac('sha512', secret).update(buffer).digest() -// } - -module.exports = { - sha1: sha1, - sha256: sha256, - sha512: sha512, - HmacSHA256: HmacSHA256, - ripemd160: ripemd160 - // hash160: hash160, - // hash256: hash256, - // HmacSHA512: HmacSHA512 -}; - -/***/ }), -/* 26 */ -/***/ (function(module, exports) { - -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isAsync = undefined; - -var _asyncify = __webpack_require__(399); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; -} - -exports.default = wrapAsync; -exports.isAsync = isAsync; - -/***/ }), -/* 28 */ -/***/ (function(module, exports) { - -module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } -}; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = __webpack_require__(108); -var defined = __webpack_require__(72); -module.exports = function (it) { - return IObject(defined(it)); -}; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports) { - -module.exports = {}; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - */ - -var keys = __webpack_require__(221); -var hasBinary = __webpack_require__(125); -var sliceBuffer = __webpack_require__(225); -var after = __webpack_require__(226); -var utf8 = __webpack_require__(227); - -var base64encoder; -if (global && global.ArrayBuffer) { - base64encoder = __webpack_require__(228); -} - -/** - * Check if we are running an android browser. That requires us to use - * ArrayBuffer with polling transports... - * - * http://ghinda.net/jpeg-blob-ajax-android/ - */ - -var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); - -/** - * Check if we are running in PhantomJS. - * Uploading a Blob with PhantomJS does not work correctly, as reported here: - * https://github.com/ariya/phantomjs/issues/11395 - * @type boolean - */ -var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent); - -/** - * When true, avoids using Blobs to encode payloads. - * @type boolean - */ -var dontSendBlobs = isAndroid || isPhantomJS; - -/** - * Current protocol version. - */ - -exports.protocol = 3; - -/** - * Packet types. - */ - -var packets = exports.packets = { - open: 0 // non-ws - , close: 1 // non-ws - , ping: 2 - , pong: 3 - , message: 4 - , upgrade: 5 - , noop: 6 -}; - -var packetslist = keys(packets); - -/** - * Premade error packet. - */ - -var err = { type: 'error', data: 'parser error' }; - -/** - * Create a blob api even for blob builder when vendor prefixes exist - */ - -var Blob = __webpack_require__(229); - -/** - * Encodes a packet. - * - * [ ] - * - * Example: - * - * 5hello world - * 3 - * 4 - * - * Binary is encoded in an identical principle - * - * @api private - */ - -exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) { - if (typeof supportsBinary === 'function') { - callback = supportsBinary; - supportsBinary = false; - } - - if (typeof utf8encode === 'function') { - callback = utf8encode; - utf8encode = null; - } - - var data = (packet.data === undefined) - ? undefined - : packet.data.buffer || packet.data; - - if (global.ArrayBuffer && data instanceof ArrayBuffer) { - return encodeArrayBuffer(packet, supportsBinary, callback); - } else if (Blob && data instanceof global.Blob) { - return encodeBlob(packet, supportsBinary, callback); - } - - // might be an object with { base64: true, data: dataAsBase64String } - if (data && data.base64) { - return encodeBase64Object(packet, callback); - } - - // Sending data as a utf-8 string - var encoded = packets[packet.type]; - - // data fragment is optional - if (undefined !== packet.data) { - encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data); - } - - return callback('' + encoded); - -}; - -function encodeBase64Object(packet, callback) { - // packet data is an object { base64: true, data: dataAsBase64String } - var message = 'b' + exports.packets[packet.type] + packet.data.data; - return callback(message); -} - -/** - * Encode packet helpers for binary types - */ - -function encodeArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - var data = packet.data; - var contentArray = new Uint8Array(data); - var resultBuffer = new Uint8Array(1 + data.byteLength); - - resultBuffer[0] = packets[packet.type]; - for (var i = 0; i < contentArray.length; i++) { - resultBuffer[i+1] = contentArray[i]; - } - - return callback(resultBuffer.buffer); -} - -function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - var fr = new FileReader(); - fr.onload = function() { - packet.data = fr.result; - exports.encodePacket(packet, supportsBinary, true, callback); - }; - return fr.readAsArrayBuffer(packet.data); -} - -function encodeBlob(packet, supportsBinary, callback) { - if (!supportsBinary) { - return exports.encodeBase64Packet(packet, callback); - } - - if (dontSendBlobs) { - return encodeBlobAsArrayBuffer(packet, supportsBinary, callback); - } - - var length = new Uint8Array(1); - length[0] = packets[packet.type]; - var blob = new Blob([length.buffer, packet.data]); - - return callback(blob); -} - -/** - * Encodes a packet with binary data in a base64 string - * - * @param {Object} packet, has `type` and `data` - * @return {String} base64 encoded message - */ - -exports.encodeBase64Packet = function(packet, callback) { - var message = 'b' + exports.packets[packet.type]; - if (Blob && packet.data instanceof global.Blob) { - var fr = new FileReader(); - fr.onload = function() { - var b64 = fr.result.split(',')[1]; - callback(message + b64); - }; - return fr.readAsDataURL(packet.data); - } - - var b64data; - try { - b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data)); - } catch (e) { - // iPhone Safari doesn't let you apply with typed arrays - var typed = new Uint8Array(packet.data); - var basic = new Array(typed.length); - for (var i = 0; i < typed.length; i++) { - basic[i] = typed[i]; - } - b64data = String.fromCharCode.apply(null, basic); - } - message += global.btoa(b64data); - return callback(message); -}; - -/** - * Decodes a packet. Changes format to Blob if requested. - * - * @return {Object} with `type` and `data` (if any) - * @api private - */ - -exports.decodePacket = function (data, binaryType, utf8decode) { - if (data === undefined) { - return err; - } - // String data - if (typeof data === 'string') { - if (data.charAt(0) === 'b') { - return exports.decodeBase64Packet(data.substr(1), binaryType); - } - - if (utf8decode) { - data = tryDecode(data); - if (data === false) { - return err; - } - } - var type = data.charAt(0); - - if (Number(type) != type || !packetslist[type]) { - return err; - } - - if (data.length > 1) { - return { type: packetslist[type], data: data.substring(1) }; - } else { - return { type: packetslist[type] }; - } - } - - var asArray = new Uint8Array(data); - var type = asArray[0]; - var rest = sliceBuffer(data, 1); - if (Blob && binaryType === 'blob') { - rest = new Blob([rest]); - } - return { type: packetslist[type], data: rest }; -}; - -function tryDecode(data) { - try { - data = utf8.decode(data, { strict: false }); - } catch (e) { - return false; - } - return data; -} - -/** - * Decodes a packet encoded in a base64 string - * - * @param {String} base64 encoded message - * @return {Object} with `type` and `data` (if any) - */ - -exports.decodeBase64Packet = function(msg, binaryType) { - var type = packetslist[msg.charAt(0)]; - if (!base64encoder) { - return { type: type, data: { base64: true, data: msg.substr(1) } }; - } - - var data = base64encoder.decode(msg.substr(1)); - - if (binaryType === 'blob' && Blob) { - data = new Blob([data]); - } - - return { type: type, data: data }; -}; - -/** - * Encodes multiple messages (payload). - * - * :data - * - * Example: - * - * 11:hello world2:hi - * - * If any contents are binary, they will be encoded as base64 strings. Base64 - * encoded strings are marked with a b before the length specifier - * - * @param {Array} packets - * @api private - */ - -exports.encodePayload = function (packets, supportsBinary, callback) { - if (typeof supportsBinary === 'function') { - callback = supportsBinary; - supportsBinary = null; - } - - var isBinary = hasBinary(packets); - - if (supportsBinary && isBinary) { - if (Blob && !dontSendBlobs) { - return exports.encodePayloadAsBlob(packets, callback); - } - - return exports.encodePayloadAsArrayBuffer(packets, callback); - } - - if (!packets.length) { - return callback('0:'); - } - - function setLengthHeader(message) { - return message.length + ':' + message; - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) { - doneCallback(null, setLengthHeader(message)); - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(results.join('')); - }); -}; - -/** - * Async array map using after - */ - -function map(ary, each, done) { - var result = new Array(ary.length); - var next = after(ary.length, done); - - var eachWithIndex = function(i, el, cb) { - each(el, function(error, msg) { - result[i] = msg; - cb(error, result); - }); - }; - - for (var i = 0; i < ary.length; i++) { - eachWithIndex(i, ary[i], next); - } -} - -/* - * Decodes data when a payload is maybe expected. Possible binary contents are - * decoded from their base64 representation - * - * @param {String} data, callback method - * @api public - */ - -exports.decodePayload = function (data, binaryType, callback) { - if (typeof data !== 'string') { - return exports.decodePayloadAsBinary(data, binaryType, callback); - } - - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var packet; - if (data === '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - var length = '', n, msg; - - for (var i = 0, l = data.length; i < l; i++) { - var chr = data.charAt(i); - - if (chr !== ':') { - length += chr; - continue; - } - - if (length === '' || (length != (n = Number(length)))) { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - msg = data.substr(i + 1, n); - - if (length != msg.length) { - // parser error - ignoring payload - return callback(err, 0, 1); - } - - if (msg.length) { - packet = exports.decodePacket(msg, binaryType, false); - - if (err.type === packet.type && err.data === packet.data) { - // parser error in individual packet - ignoring payload - return callback(err, 0, 1); - } - - var ret = callback(packet, i + n, l); - if (false === ret) return; - } - - // advance cursor - i += n; - length = ''; - } - - if (length !== '') { - // parser error - ignoring payload - return callback(err, 0, 1); - } - -}; - -/** - * Encodes multiple messages (payload) as binary. - * - * <1 = binary, 0 = string>[...] - * - * Example: - * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers - * - * @param {Array} packets - * @return {ArrayBuffer} encoded payload - * @api private - */ - -exports.encodePayloadAsArrayBuffer = function(packets, callback) { - if (!packets.length) { - return callback(new ArrayBuffer(0)); - } - - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(data) { - return doneCallback(null, data); - }); - } - - map(packets, encodeOne, function(err, encodedPackets) { - var totalLength = encodedPackets.reduce(function(acc, p) { - var len; - if (typeof p === 'string'){ - len = p.length; - } else { - len = p.byteLength; - } - return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2 - }, 0); - - var resultArray = new Uint8Array(totalLength); - - var bufferIndex = 0; - encodedPackets.forEach(function(p) { - var isString = typeof p === 'string'; - var ab = p; - if (isString) { - var view = new Uint8Array(p.length); - for (var i = 0; i < p.length; i++) { - view[i] = p.charCodeAt(i); - } - ab = view.buffer; - } - - if (isString) { // not true binary - resultArray[bufferIndex++] = 0; - } else { // true binary - resultArray[bufferIndex++] = 1; - } - - var lenStr = ab.byteLength.toString(); - for (var i = 0; i < lenStr.length; i++) { - resultArray[bufferIndex++] = parseInt(lenStr[i]); - } - resultArray[bufferIndex++] = 255; - - var view = new Uint8Array(ab); - for (var i = 0; i < view.length; i++) { - resultArray[bufferIndex++] = view[i]; - } - }); - - return callback(resultArray.buffer); - }); -}; - -/** - * Encode as Blob - */ - -exports.encodePayloadAsBlob = function(packets, callback) { - function encodeOne(packet, doneCallback) { - exports.encodePacket(packet, true, true, function(encoded) { - var binaryIdentifier = new Uint8Array(1); - binaryIdentifier[0] = 1; - if (typeof encoded === 'string') { - var view = new Uint8Array(encoded.length); - for (var i = 0; i < encoded.length; i++) { - view[i] = encoded.charCodeAt(i); - } - encoded = view.buffer; - binaryIdentifier[0] = 0; - } - - var len = (encoded instanceof ArrayBuffer) - ? encoded.byteLength - : encoded.size; - - var lenStr = len.toString(); - var lengthAry = new Uint8Array(lenStr.length + 1); - for (var i = 0; i < lenStr.length; i++) { - lengthAry[i] = parseInt(lenStr[i]); - } - lengthAry[lenStr.length] = 255; - - if (Blob) { - var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]); - doneCallback(null, blob); - } - }); - } - - map(packets, encodeOne, function(err, results) { - return callback(new Blob(results)); - }); -}; - -/* - * Decodes data when a payload is maybe expected. Strings are decoded by - * interpreting each byte as a key code for entries marked to start with 0. See - * description of encodePayloadAsBinary - * - * @param {ArrayBuffer} data, callback method - * @api public - */ - -exports.decodePayloadAsBinary = function (data, binaryType, callback) { - if (typeof binaryType === 'function') { - callback = binaryType; - binaryType = null; - } - - var bufferTail = data; - var buffers = []; - - while (bufferTail.byteLength > 0) { - var tailArray = new Uint8Array(bufferTail); - var isString = tailArray[0] === 0; - var msgLength = ''; - - for (var i = 1; ; i++) { - if (tailArray[i] === 255) break; - - // 310 = char length of Number.MAX_VALUE - if (msgLength.length > 310) { - return callback(err, 0, 1); - } - - msgLength += tailArray[i]; - } - - bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length); - msgLength = parseInt(msgLength); - - var msg = sliceBuffer(bufferTail, 0, msgLength); - if (isString) { - try { - msg = String.fromCharCode.apply(null, new Uint8Array(msg)); - } catch (e) { - // iPhone Safari doesn't let you apply to typed arrays - var typed = new Uint8Array(msg); - msg = ''; - for (var i = 0; i < typed.length; i++) { - msg += String.fromCharCode(typed[i]); - } - } - } - - buffers.push(msg); - bufferTail = sliceBuffer(bufferTail, msgLength); - } - - var total = buffers.length; - buffers.forEach(function(buffer, i) { - callback(exports.decodePacket(buffer, binaryType, true), i, total); - }); -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* - Copyright 2013-2014 Daniel Wirtz - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -/** - * @license bytebuffer.js (c) 2015 Daniel Wirtz - * Backing buffer: ArrayBuffer, Accessor: Uint8Array - * Released under the Apache License, Version 2.0 - * see: https://github.com/dcodeIO/bytebuffer.js for details - */ -(function(global, factory) { - - /* AMD */ if (true) - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(254)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"]) - module['exports'] = (function() { - var Long; try { Long = require("long"); } catch (e) {} - return factory(Long); - })(); - /* Global */ else - (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]); - -})(this, function(Long) { - "use strict"; - - /** - * Constructs a new ByteBuffer. - * @class The swiss army knife for binary data in JavaScript. - * @exports ByteBuffer - * @constructor - * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}. - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @expose - */ - var ByteBuffer = function(capacity, littleEndian, noAssert) { - if (typeof capacity === 'undefined') - capacity = ByteBuffer.DEFAULT_CAPACITY; - if (typeof littleEndian === 'undefined') - littleEndian = ByteBuffer.DEFAULT_ENDIAN; - if (typeof noAssert === 'undefined') - noAssert = ByteBuffer.DEFAULT_NOASSERT; - if (!noAssert) { - capacity = capacity | 0; - if (capacity < 0) - throw RangeError("Illegal capacity"); - littleEndian = !!littleEndian; - noAssert = !!noAssert; - } - - /** - * Backing ArrayBuffer. - * @type {!ArrayBuffer} - * @expose - */ - this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity); - - /** - * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`. - * @type {?Uint8Array} - * @expose - */ - this.view = capacity === 0 ? null : new Uint8Array(this.buffer); - - /** - * Absolute read/write offset. - * @type {number} - * @expose - * @see ByteBuffer#flip - * @see ByteBuffer#clear - */ - this.offset = 0; - - /** - * Marked offset. - * @type {number} - * @expose - * @see ByteBuffer#mark - * @see ByteBuffer#reset - */ - this.markedOffset = -1; - - /** - * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation. - * @type {number} - * @expose - * @see ByteBuffer#flip - * @see ByteBuffer#clear - */ - this.limit = capacity; - - /** - * Whether to use little endian byte order, defaults to `false` for big endian. - * @type {boolean} - * @expose - */ - this.littleEndian = littleEndian; - - /** - * Whether to skip assertions of offsets and values, defaults to `false`. - * @type {boolean} - * @expose - */ - this.noAssert = noAssert; - }; - - /** - * ByteBuffer version. - * @type {string} - * @const - * @expose - */ - ByteBuffer.VERSION = "5.0.1"; - - /** - * Little endian constant that can be used instead of its boolean value. Evaluates to `true`. - * @type {boolean} - * @const - * @expose - */ - ByteBuffer.LITTLE_ENDIAN = true; - - /** - * Big endian constant that can be used instead of its boolean value. Evaluates to `false`. - * @type {boolean} - * @const - * @expose - */ - ByteBuffer.BIG_ENDIAN = false; - - /** - * Default initial capacity of `16`. - * @type {number} - * @expose - */ - ByteBuffer.DEFAULT_CAPACITY = 16; - - /** - * Default endianess of `false` for big endian. - * @type {boolean} - * @expose - */ - ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN; - - /** - * Default no assertions flag of `false`. - * @type {boolean} - * @expose - */ - ByteBuffer.DEFAULT_NOASSERT = false; - - /** - * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded - * and int64 support is not available. - * @type {?Long} - * @const - * @see https://github.com/dcodeIO/long.js - * @expose - */ - ByteBuffer.Long = Long || null; - - /** - * @alias ByteBuffer.prototype - * @inner - */ - var ByteBufferPrototype = ByteBuffer.prototype; - - /** - * An indicator used to reliably determine if an object is a ByteBuffer or not. - * @type {boolean} - * @const - * @expose - * @private - */ - ByteBufferPrototype.__isByteBuffer__; - - Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", { - value: true, - enumerable: false, - configurable: false - }); - - // helpers - - /** - * @type {!ArrayBuffer} - * @inner - */ - var EMPTY_BUFFER = new ArrayBuffer(0); - - /** - * String.fromCharCode reference for compile-time renaming. - * @type {function(...number):string} - * @inner - */ - var stringFromCharCode = String.fromCharCode; - - /** - * Creates a source function for a string. - * @param {string} s String to read from - * @returns {function():number|null} Source function returning the next char code respectively `null` if there are - * no more characters left. - * @throws {TypeError} If the argument is invalid - * @inner - */ - function stringSource(s) { - var i=0; return function() { - return i < s.length ? s.charCodeAt(i++) : null; - }; - } - - /** - * Creates a destination function for a string. - * @returns {function(number=):undefined|string} Destination function successively called with the next char code. - * Returns the final string when called without arguments. - * @inner - */ - function stringDestination() { - var cs = [], ps = []; return function() { - if (arguments.length === 0) - return ps.join('')+stringFromCharCode.apply(String, cs); - if (cs.length + arguments.length > 1024) - ps.push(stringFromCharCode.apply(String, cs)), - cs.length = 0; - Array.prototype.push.apply(cs, arguments); - }; - } - - /** - * Gets the accessor type. - * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes) - * @expose - */ - ByteBuffer.accessor = function() { - return Uint8Array; - }; - /** - * Allocates a new ByteBuffer backed by a buffer of the specified capacity. - * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}. - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} - * @expose - */ - ByteBuffer.allocate = function(capacity, littleEndian, noAssert) { - return new ByteBuffer(capacity, littleEndian, noAssert); - }; - - /** - * Concatenates multiple ByteBuffers into one. - * @param {!Array.} buffers Buffers to concatenate - * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary", - * defaults to "utf8") - * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults - * to {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} Concatenated ByteBuffer - * @expose - */ - ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) { - if (typeof encoding === 'boolean' || typeof encoding !== 'string') { - noAssert = littleEndian; - littleEndian = encoding; - encoding = undefined; - } - var capacity = 0; - for (var i=0, k=buffers.length, length; i 0) capacity += length; - } - if (capacity === 0) - return new ByteBuffer(0, littleEndian, noAssert); - var bb = new ByteBuffer(capacity, littleEndian, noAssert), - bi; - i=0; while (i} buffer Anything that can be wrapped - * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to - * "utf8") - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer` - * @expose - */ - ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) { - if (typeof encoding !== 'string') { - noAssert = littleEndian; - littleEndian = encoding; - encoding = undefined; - } - if (typeof buffer === 'string') { - if (typeof encoding === 'undefined') - encoding = "utf8"; - switch (encoding) { - case "base64": - return ByteBuffer.fromBase64(buffer, littleEndian); - case "hex": - return ByteBuffer.fromHex(buffer, littleEndian); - case "binary": - return ByteBuffer.fromBinary(buffer, littleEndian); - case "utf8": - return ByteBuffer.fromUTF8(buffer, littleEndian); - case "debug": - return ByteBuffer.fromDebug(buffer, littleEndian); - default: - throw Error("Unsupported encoding: "+encoding); - } - } - if (buffer === null || typeof buffer !== 'object') - throw TypeError("Illegal buffer"); - var bb; - if (ByteBuffer.isByteBuffer(buffer)) { - bb = ByteBufferPrototype.clone.call(buffer); - bb.markedOffset = -1; - return bb; - } - if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array - bb = new ByteBuffer(0, littleEndian, noAssert); - if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER - bb.buffer = buffer.buffer; - bb.offset = buffer.byteOffset; - bb.limit = buffer.byteOffset + buffer.byteLength; - bb.view = new Uint8Array(buffer.buffer); - } - } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer - bb = new ByteBuffer(0, littleEndian, noAssert); - if (buffer.byteLength > 0) { - bb.buffer = buffer; - bb.offset = 0; - bb.limit = buffer.byteLength; - bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null; - } - } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets - bb = new ByteBuffer(buffer.length, littleEndian, noAssert); - bb.limit = buffer.length; - for (var i=0; i} value Array of booleans to write - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. - * @returns {!ByteBuffer} - * @expose - */ - ByteBufferPrototype.writeBitSet = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (!(value instanceof Array)) - throw TypeError("Illegal BitSet: Not an array"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - - var start = offset, - bits = value.length, - bytes = (bits >> 3), - bit = 0, - k; - - offset += this.writeVarint32(bits,offset); - - while(bytes--) { - k = (!!value[bit++] & 1) | - ((!!value[bit++] & 1) << 1) | - ((!!value[bit++] & 1) << 2) | - ((!!value[bit++] & 1) << 3) | - ((!!value[bit++] & 1) << 4) | - ((!!value[bit++] & 1) << 5) | - ((!!value[bit++] & 1) << 6) | - ((!!value[bit++] & 1) << 7); - this.writeByte(k,offset++); - } - - if(bit < bits) { - var m = 0; k = 0; - while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++)); - this.writeByte(k,offset++); - } - - if (relative) { - this.offset = offset; - return this; - } - return offset - start; - } - - /** - * Reads a BitSet as an array of booleans. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. - * @returns {Array - * @expose - */ - ByteBufferPrototype.readBitSet = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - - var ret = this.readVarint32(offset), - bits = ret.value, - bytes = (bits >> 3), - bit = 0, - value = [], - k; - - offset += ret.length; - - while(bytes--) { - k = this.readByte(offset++); - value[bit++] = !!(k & 0x01); - value[bit++] = !!(k & 0x02); - value[bit++] = !!(k & 0x04); - value[bit++] = !!(k & 0x08); - value[bit++] = !!(k & 0x10); - value[bit++] = !!(k & 0x20); - value[bit++] = !!(k & 0x40); - value[bit++] = !!(k & 0x80); - } - - if(bit < bits) { - var m = 0; - k = this.readByte(offset++); - while(bit < bits) value[bit++] = !!((k >> (m++)) & 1); - } - - if (relative) { - this.offset = offset; - } - return value; - } - /** - * Reads the specified number of bytes. - * @param {number} length Number of bytes to read - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted. - * @returns {!ByteBuffer} - * @expose - */ - ByteBufferPrototype.readBytes = function(length, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + length > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength); - } - var slice = this.slice(offset, offset + length); - if (relative) this.offset += length; - return slice; - }; - - /** - * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}. - * @function - * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets - * will be modified according to the performed read operation. - * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeBytes = ByteBufferPrototype.append; - - // types/ints/int8 - - /** - * Writes an 8bit signed integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeInt8 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value |= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 1; - var capacity0 = this.buffer.byteLength; - if (offset > capacity0) - this.resize((capacity0 *= 2) > offset ? capacity0 : offset); - offset -= 1; - this.view[offset] = value; - if (relative) this.offset += 1; - return this; - }; - - /** - * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8; - - /** - * Reads an 8bit signed integer. - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readInt8 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - var value = this.view[offset]; - if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed - if (relative) this.offset += 1; - return value; - }; - - /** - * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}. - * @function - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8; - - /** - * Writes an 8bit unsigned integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeUint8 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value >>>= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 1; - var capacity1 = this.buffer.byteLength; - if (offset > capacity1) - this.resize((capacity1 *= 2) > offset ? capacity1 : offset); - offset -= 1; - this.view[offset] = value; - if (relative) this.offset += 1; - return this; - }; - - /** - * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8; - - /** - * Reads an 8bit unsigned integer. - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readUint8 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - var value = this.view[offset]; - if (relative) this.offset += 1; - return value; - }; - - /** - * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}. - * @function - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8; - - // types/ints/int16 - - /** - * Writes a 16bit signed integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @throws {TypeError} If `offset` or `value` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.writeInt16 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value |= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 2; - var capacity2 = this.buffer.byteLength; - if (offset > capacity2) - this.resize((capacity2 *= 2) > offset ? capacity2 : offset); - offset -= 2; - if (this.littleEndian) { - this.view[offset+1] = (value & 0xFF00) >>> 8; - this.view[offset ] = value & 0x00FF; - } else { - this.view[offset] = (value & 0xFF00) >>> 8; - this.view[offset+1] = value & 0x00FF; - } - if (relative) this.offset += 2; - return this; - }; - - /** - * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @throws {TypeError} If `offset` or `value` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16; - - /** - * Reads a 16bit signed integer. - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @returns {number} Value read - * @throws {TypeError} If `offset` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.readInt16 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 2 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength); - } - var value = 0; - if (this.littleEndian) { - value = this.view[offset ]; - value |= this.view[offset+1] << 8; - } else { - value = this.view[offset ] << 8; - value |= this.view[offset+1]; - } - if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed - if (relative) this.offset += 2; - return value; - }; - - /** - * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}. - * @function - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @returns {number} Value read - * @throws {TypeError} If `offset` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16; - - /** - * Writes a 16bit unsigned integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @throws {TypeError} If `offset` or `value` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.writeUint16 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value >>>= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 2; - var capacity3 = this.buffer.byteLength; - if (offset > capacity3) - this.resize((capacity3 *= 2) > offset ? capacity3 : offset); - offset -= 2; - if (this.littleEndian) { - this.view[offset+1] = (value & 0xFF00) >>> 8; - this.view[offset ] = value & 0x00FF; - } else { - this.view[offset] = (value & 0xFF00) >>> 8; - this.view[offset+1] = value & 0x00FF; - } - if (relative) this.offset += 2; - return this; - }; - - /** - * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @throws {TypeError} If `offset` or `value` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16; - - /** - * Reads a 16bit unsigned integer. - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @returns {number} Value read - * @throws {TypeError} If `offset` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.readUint16 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 2 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength); - } - var value = 0; - if (this.littleEndian) { - value = this.view[offset ]; - value |= this.view[offset+1] << 8; - } else { - value = this.view[offset ] << 8; - value |= this.view[offset+1]; - } - if (relative) this.offset += 2; - return value; - }; - - /** - * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}. - * @function - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted. - * @returns {number} Value read - * @throws {TypeError} If `offset` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @expose - */ - ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16; - - // types/ints/int32 - - /** - * Writes a 32bit signed integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @expose - */ - ByteBufferPrototype.writeInt32 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value |= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 4; - var capacity4 = this.buffer.byteLength; - if (offset > capacity4) - this.resize((capacity4 *= 2) > offset ? capacity4 : offset); - offset -= 4; - if (this.littleEndian) { - this.view[offset+3] = (value >>> 24) & 0xFF; - this.view[offset+2] = (value >>> 16) & 0xFF; - this.view[offset+1] = (value >>> 8) & 0xFF; - this.view[offset ] = value & 0xFF; - } else { - this.view[offset ] = (value >>> 24) & 0xFF; - this.view[offset+1] = (value >>> 16) & 0xFF; - this.view[offset+2] = (value >>> 8) & 0xFF; - this.view[offset+3] = value & 0xFF; - } - if (relative) this.offset += 4; - return this; - }; - - /** - * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @expose - */ - ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32; - - /** - * Reads a 32bit signed integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readInt32 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 4 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); - } - var value = 0; - if (this.littleEndian) { - value = this.view[offset+2] << 16; - value |= this.view[offset+1] << 8; - value |= this.view[offset ]; - value += this.view[offset+3] << 24 >>> 0; - } else { - value = this.view[offset+1] << 16; - value |= this.view[offset+2] << 8; - value |= this.view[offset+3]; - value += this.view[offset ] << 24 >>> 0; - } - value |= 0; // Cast to signed - if (relative) this.offset += 4; - return value; - }; - - /** - * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}. - * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32; - - /** - * Writes a 32bit unsigned integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @expose - */ - ByteBufferPrototype.writeUint32 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value >>>= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 4; - var capacity5 = this.buffer.byteLength; - if (offset > capacity5) - this.resize((capacity5 *= 2) > offset ? capacity5 : offset); - offset -= 4; - if (this.littleEndian) { - this.view[offset+3] = (value >>> 24) & 0xFF; - this.view[offset+2] = (value >>> 16) & 0xFF; - this.view[offset+1] = (value >>> 8) & 0xFF; - this.view[offset ] = value & 0xFF; - } else { - this.view[offset ] = (value >>> 24) & 0xFF; - this.view[offset+1] = (value >>> 16) & 0xFF; - this.view[offset+2] = (value >>> 8) & 0xFF; - this.view[offset+3] = value & 0xFF; - } - if (relative) this.offset += 4; - return this; - }; - - /** - * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @expose - */ - ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32; - - /** - * Reads a 32bit unsigned integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readUint32 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 4 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); - } - var value = 0; - if (this.littleEndian) { - value = this.view[offset+2] << 16; - value |= this.view[offset+1] << 8; - value |= this.view[offset ]; - value += this.view[offset+3] << 24 >>> 0; - } else { - value = this.view[offset+1] << 16; - value |= this.view[offset+2] << 8; - value |= this.view[offset+3]; - value += this.view[offset ] << 24 >>> 0; - } - if (relative) this.offset += 4; - return value; - }; - - /** - * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}. - * @function - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} Value read - * @expose - */ - ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32; - - // types/ints/int64 - - if (Long) { - - /** - * Writes a 64bit signed integer. - * @param {number|!Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeInt64 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - else if (!(value && value instanceof Long)) - throw TypeError("Illegal value: "+value+" (not an integer or Long)"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - offset += 8; - var capacity6 = this.buffer.byteLength; - if (offset > capacity6) - this.resize((capacity6 *= 2) > offset ? capacity6 : offset); - offset -= 8; - var lo = value.low, - hi = value.high; - if (this.littleEndian) { - this.view[offset+3] = (lo >>> 24) & 0xFF; - this.view[offset+2] = (lo >>> 16) & 0xFF; - this.view[offset+1] = (lo >>> 8) & 0xFF; - this.view[offset ] = lo & 0xFF; - offset += 4; - this.view[offset+3] = (hi >>> 24) & 0xFF; - this.view[offset+2] = (hi >>> 16) & 0xFF; - this.view[offset+1] = (hi >>> 8) & 0xFF; - this.view[offset ] = hi & 0xFF; - } else { - this.view[offset ] = (hi >>> 24) & 0xFF; - this.view[offset+1] = (hi >>> 16) & 0xFF; - this.view[offset+2] = (hi >>> 8) & 0xFF; - this.view[offset+3] = hi & 0xFF; - offset += 4; - this.view[offset ] = (lo >>> 24) & 0xFF; - this.view[offset+1] = (lo >>> 16) & 0xFF; - this.view[offset+2] = (lo >>> 8) & 0xFF; - this.view[offset+3] = lo & 0xFF; - } - if (relative) this.offset += 8; - return this; - }; - - /** - * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}. - * @param {number|!Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64; - - /** - * Reads a 64bit signed integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!Long} - * @expose - */ - ByteBufferPrototype.readInt64 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 8 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); - } - var lo = 0, - hi = 0; - if (this.littleEndian) { - lo = this.view[offset+2] << 16; - lo |= this.view[offset+1] << 8; - lo |= this.view[offset ]; - lo += this.view[offset+3] << 24 >>> 0; - offset += 4; - hi = this.view[offset+2] << 16; - hi |= this.view[offset+1] << 8; - hi |= this.view[offset ]; - hi += this.view[offset+3] << 24 >>> 0; - } else { - hi = this.view[offset+1] << 16; - hi |= this.view[offset+2] << 8; - hi |= this.view[offset+3]; - hi += this.view[offset ] << 24 >>> 0; - offset += 4; - lo = this.view[offset+1] << 16; - lo |= this.view[offset+2] << 8; - lo |= this.view[offset+3]; - lo += this.view[offset ] << 24 >>> 0; - } - var value = new Long(lo, hi, false); - if (relative) this.offset += 8; - return value; - }; - - /** - * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!Long} - * @expose - */ - ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64; - - /** - * Writes a 64bit unsigned integer. - * @param {number|!Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeUint64 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - else if (!(value && value instanceof Long)) - throw TypeError("Illegal value: "+value+" (not an integer or Long)"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - offset += 8; - var capacity7 = this.buffer.byteLength; - if (offset > capacity7) - this.resize((capacity7 *= 2) > offset ? capacity7 : offset); - offset -= 8; - var lo = value.low, - hi = value.high; - if (this.littleEndian) { - this.view[offset+3] = (lo >>> 24) & 0xFF; - this.view[offset+2] = (lo >>> 16) & 0xFF; - this.view[offset+1] = (lo >>> 8) & 0xFF; - this.view[offset ] = lo & 0xFF; - offset += 4; - this.view[offset+3] = (hi >>> 24) & 0xFF; - this.view[offset+2] = (hi >>> 16) & 0xFF; - this.view[offset+1] = (hi >>> 8) & 0xFF; - this.view[offset ] = hi & 0xFF; - } else { - this.view[offset ] = (hi >>> 24) & 0xFF; - this.view[offset+1] = (hi >>> 16) & 0xFF; - this.view[offset+2] = (hi >>> 8) & 0xFF; - this.view[offset+3] = hi & 0xFF; - offset += 4; - this.view[offset ] = (lo >>> 24) & 0xFF; - this.view[offset+1] = (lo >>> 16) & 0xFF; - this.view[offset+2] = (lo >>> 8) & 0xFF; - this.view[offset+3] = lo & 0xFF; - } - if (relative) this.offset += 8; - return this; - }; - - /** - * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}. - * @function - * @param {number|!Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64; - - /** - * Reads a 64bit unsigned integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!Long} - * @expose - */ - ByteBufferPrototype.readUint64 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 8 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); - } - var lo = 0, - hi = 0; - if (this.littleEndian) { - lo = this.view[offset+2] << 16; - lo |= this.view[offset+1] << 8; - lo |= this.view[offset ]; - lo += this.view[offset+3] << 24 >>> 0; - offset += 4; - hi = this.view[offset+2] << 16; - hi |= this.view[offset+1] << 8; - hi |= this.view[offset ]; - hi += this.view[offset+3] << 24 >>> 0; - } else { - hi = this.view[offset+1] << 16; - hi |= this.view[offset+2] << 8; - hi |= this.view[offset+3]; - hi += this.view[offset ] << 24 >>> 0; - offset += 4; - lo = this.view[offset+1] << 16; - lo |= this.view[offset+2] << 8; - lo |= this.view[offset+3]; - lo += this.view[offset ] << 24 >>> 0; - } - var value = new Long(lo, hi, true); - if (relative) this.offset += 8; - return value; - }; - - /** - * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}. - * @function - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!Long} - * @expose - */ - ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64; - - } // Long - - - // types/floats/float32 - - /* - ieee754 - https://github.com/feross/ieee754 - - The MIT License (MIT) - - Copyright (c) Feross Aboukhadijeh - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - */ - - /** - * Reads an IEEE754 float from a byte array. - * @param {!Array} buffer - * @param {number} offset - * @param {boolean} isLE - * @param {number} mLen - * @param {number} nBytes - * @returns {number} - * @inner - */ - function ieee754_read(buffer, offset, isLE, mLen, nBytes) { - var e, m, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = isLE ? (nBytes - 1) : 0, - d = isLE ? -1 : 1, - 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); - } - - /** - * Writes an IEEE754 float to a byte array. - * @param {!Array} buffer - * @param {number} value - * @param {number} offset - * @param {boolean} isLE - * @param {number} mLen - * @param {number} nBytes - * @inner - */ - function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c, - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = isLE ? 0 : (nBytes - 1), - d = isLE ? 1 : -1, - 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; - } - - /** - * Writes a 32bit float. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeFloat32 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number') - throw TypeError("Illegal value: "+value+" (not a number)"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 4; - var capacity8 = this.buffer.byteLength; - if (offset > capacity8) - this.resize((capacity8 *= 2) > offset ? capacity8 : offset); - offset -= 4; - ieee754_write(this.view, value, offset, this.littleEndian, 23, 4); - if (relative) this.offset += 4; - return this; - }; - - /** - * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32; - - /** - * Reads a 32bit float. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} - * @expose - */ - ByteBufferPrototype.readFloat32 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 4 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); - } - var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4); - if (relative) this.offset += 4; - return value; - }; - - /** - * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}. - * @function - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted. - * @returns {number} - * @expose - */ - ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32; - - // types/floats/float64 - - /** - * Writes a 64bit float. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeFloat64 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number') - throw TypeError("Illegal value: "+value+" (not a number)"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - offset += 8; - var capacity9 = this.buffer.byteLength; - if (offset > capacity9) - this.resize((capacity9 *= 2) > offset ? capacity9 : offset); - offset -= 8; - ieee754_write(this.view, value, offset, this.littleEndian, 52, 8); - if (relative) this.offset += 8; - return this; - }; - - /** - * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}. - * @function - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64; - - /** - * Reads a 64bit float. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {number} - * @expose - */ - ByteBufferPrototype.readFloat64 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 8 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength); - } - var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8); - if (relative) this.offset += 8; - return value; - }; - - /** - * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}. - * @function - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted. - * @returns {number} - * @expose - */ - ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64; - - - // types/varints/varint32 - - /** - * Maximum number of bytes required to store a 32bit base 128 variable-length integer. - * @type {number} - * @const - * @expose - */ - ByteBuffer.MAX_VARINT32_BYTES = 5; - - /** - * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer. - * @param {number} value Value to encode - * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES} - * @expose - */ - ByteBuffer.calculateVarint32 = function(value) { - // ref: src/google/protobuf/io/coded_stream.cc - value = value >>> 0; - if (value < 1 << 7 ) return 1; - else if (value < 1 << 14) return 2; - else if (value < 1 << 21) return 3; - else if (value < 1 << 28) return 4; - else return 5; - }; - - /** - * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding. - * @param {number} n Signed 32bit integer - * @returns {number} Unsigned zigzag encoded 32bit integer - * @expose - */ - ByteBuffer.zigZagEncode32 = function(n) { - return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h - }; - - /** - * Decodes a zigzag encoded signed 32bit integer. - * @param {number} n Unsigned zigzag encoded 32bit integer - * @returns {number} Signed 32bit integer - * @expose - */ - ByteBuffer.zigZagDecode32 = function(n) { - return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h - }; - - /** - * Writes a 32bit base 128 variable-length integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written - * @expose - */ - ByteBufferPrototype.writeVarint32 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value |= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - var size = ByteBuffer.calculateVarint32(value), - b; - offset += size; - var capacity10 = this.buffer.byteLength; - if (offset > capacity10) - this.resize((capacity10 *= 2) > offset ? capacity10 : offset); - offset -= size; - value >>>= 0; - while (value >= 0x80) { - b = (value & 0x7f) | 0x80; - this.view[offset++] = b; - value >>>= 7; - } - this.view[offset++] = value; - if (relative) { - this.offset = offset; - return this; - } - return size; - }; - - /** - * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer. - * @param {number} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written - * @expose - */ - ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) { - return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset); - }; - - /** - * Reads a 32bit base 128 variable-length integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read - * and the actual number of bytes read. - * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available - * to fully decode the varint. - * @expose - */ - ByteBufferPrototype.readVarint32 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - var c = 0, - value = 0 >>> 0, - b; - do { - if (!this.noAssert && offset > this.limit) { - var err = Error("Truncated"); - err['truncated'] = true; - throw err; - } - b = this.view[offset++]; - if (c < 5) - value |= (b & 0x7f) << (7*c); - ++c; - } while ((b & 0x80) !== 0); - value |= 0; - if (relative) { - this.offset = offset; - return value; - } - return { - "value": value, - "length": c - }; - }; - - /** - * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read - * and the actual number of bytes read. - * @throws {Error} If it's not a valid varint - * @expose - */ - ByteBufferPrototype.readVarint32ZigZag = function(offset) { - var val = this.readVarint32(offset); - if (typeof val === 'object') - val["value"] = ByteBuffer.zigZagDecode32(val["value"]); - else - val = ByteBuffer.zigZagDecode32(val); - return val; - }; - - // types/varints/varint64 - - if (Long) { - - /** - * Maximum number of bytes required to store a 64bit base 128 variable-length integer. - * @type {number} - * @const - * @expose - */ - ByteBuffer.MAX_VARINT64_BYTES = 10; - - /** - * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer. - * @param {number|!Long} value Value to encode - * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES} - * @expose - */ - ByteBuffer.calculateVarint64 = function(value) { - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - // ref: src/google/protobuf/io/coded_stream.cc - var part0 = value.toInt() >>> 0, - part1 = value.shiftRightUnsigned(28).toInt() >>> 0, - part2 = value.shiftRightUnsigned(56).toInt() >>> 0; - if (part2 == 0) { - if (part1 == 0) { - if (part0 < 1 << 14) - return part0 < 1 << 7 ? 1 : 2; - else - return part0 < 1 << 21 ? 3 : 4; - } else { - if (part1 < 1 << 14) - return part1 < 1 << 7 ? 5 : 6; - else - return part1 < 1 << 21 ? 7 : 8; - } - } else - return part2 < 1 << 7 ? 9 : 10; - }; - - /** - * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding. - * @param {number|!Long} value Signed long - * @returns {!Long} Unsigned zigzag encoded long - * @expose - */ - ByteBuffer.zigZagEncode64 = function(value) { - if (typeof value === 'number') - value = Long.fromNumber(value, false); - else if (typeof value === 'string') - value = Long.fromString(value, false); - else if (value.unsigned !== false) value = value.toSigned(); - // ref: src/google/protobuf/wire_format_lite.h - return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned(); - }; - - /** - * Decodes a zigzag encoded signed 64bit integer. - * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number - * @returns {!Long} Signed long - * @expose - */ - ByteBuffer.zigZagDecode64 = function(value) { - if (typeof value === 'number') - value = Long.fromNumber(value, false); - else if (typeof value === 'string') - value = Long.fromString(value, false); - else if (value.unsigned !== false) value = value.toSigned(); - // ref: src/google/protobuf/wire_format_lite.h - return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned(); - }; - - /** - * Writes a 64bit base 128 variable-length integer. - * @param {number|Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written. - * @expose - */ - ByteBufferPrototype.writeVarint64 = function(value, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof value === 'number') - value = Long.fromNumber(value); - else if (typeof value === 'string') - value = Long.fromString(value); - else if (!(value && value instanceof Long)) - throw TypeError("Illegal value: "+value+" (not an integer or Long)"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - if (typeof value === 'number') - value = Long.fromNumber(value, false); - else if (typeof value === 'string') - value = Long.fromString(value, false); - else if (value.unsigned !== false) value = value.toSigned(); - var size = ByteBuffer.calculateVarint64(value), - part0 = value.toInt() >>> 0, - part1 = value.shiftRightUnsigned(28).toInt() >>> 0, - part2 = value.shiftRightUnsigned(56).toInt() >>> 0; - offset += size; - var capacity11 = this.buffer.byteLength; - if (offset > capacity11) - this.resize((capacity11 *= 2) > offset ? capacity11 : offset); - offset -= size; - switch (size) { - case 10: this.view[offset+9] = (part2 >>> 7) & 0x01; - case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F; - case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F; - case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F; - case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F; - case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F; - case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F; - case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F; - case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F; - case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F; - } - if (relative) { - this.offset += size; - return this; - } else { - return size; - } - }; - - /** - * Writes a zig-zag encoded 64bit base 128 variable-length integer. - * @param {number|Long} value Value to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written. - * @expose - */ - ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) { - return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset); - }; - - /** - * Reads a 64bit base 128 variable-length integer. Requires Long.js. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and - * the actual number of bytes read. - * @throws {Error} If it's not a valid varint - * @expose - */ - ByteBufferPrototype.readVarint64 = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - // ref: src/google/protobuf/io/coded_stream.cc - var start = offset, - part0 = 0, - part1 = 0, - part2 = 0, - b = 0; - b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) { - b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) { - throw Error("Buffer overrun"); }}}}}}}}}} - var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false); - if (relative) { - this.offset = offset; - return value; - } else { - return { - 'value': value, - 'length': offset-start - }; - } - }; - - /** - * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and - * the actual number of bytes read. - * @throws {Error} If it's not a valid varint - * @expose - */ - ByteBufferPrototype.readVarint64ZigZag = function(offset) { - var val = this.readVarint64(offset); - if (val && val['value'] instanceof Long) - val["value"] = ByteBuffer.zigZagDecode64(val["value"]); - else - val = ByteBuffer.zigZagDecode64(val); - return val; - }; - - } // Long - - - // types/strings/cstring - - /** - * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL - * characters itself. - * @param {string} str String to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * contained in `str` + 1 if omitted. - * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written - * @expose - */ - ByteBufferPrototype.writeCString = function(str, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - var i, - k = str.length; - if (!this.noAssert) { - if (typeof str !== 'string') - throw TypeError("Illegal str: Not a string"); - for (i=0; i>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - // UTF8 strings do not contain zero bytes in between except for the zero character, so: - k = utfx.calculateUTF16asUTF8(stringSource(str))[1]; - offset += k+1; - var capacity12 = this.buffer.byteLength; - if (offset > capacity12) - this.resize((capacity12 *= 2) > offset ? capacity12 : offset); - offset -= k+1; - utfx.encodeUTF16toUTF8(stringSource(str), function(b) { - this.view[offset++] = b; - }.bind(this)); - this.view[offset++] = 0; - if (relative) { - this.offset = offset; - return this; - } - return k; - }; - - /** - * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters - * itself. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string - * read and the actual number of bytes read. - * @expose - */ - ByteBufferPrototype.readCString = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - var start = offset, - temp; - // UTF8 strings do not contain zero bytes in between except for the zero character itself, so: - var sd, b = -1; - utfx.decodeUTF8toUTF16(function() { - if (b === 0) return null; - if (offset >= this.limit) - throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit); - b = this.view[offset++]; - return b === 0 ? null : b; - }.bind(this), sd = stringDestination(), true); - if (relative) { - this.offset = offset; - return sd(); - } else { - return { - "string": sd(), - "length": offset - start - }; - } - }; - - // types/strings/istring - - /** - * Writes a length as uint32 prefixed UTF8 encoded string. - * @param {string} str String to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written - * @expose - * @see ByteBuffer#writeVarint32 - */ - ByteBufferPrototype.writeIString = function(str, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof str !== 'string') - throw TypeError("Illegal str: Not a string"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - var start = offset, - k; - k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1]; - offset += 4+k; - var capacity13 = this.buffer.byteLength; - if (offset > capacity13) - this.resize((capacity13 *= 2) > offset ? capacity13 : offset); - offset -= 4+k; - if (this.littleEndian) { - this.view[offset+3] = (k >>> 24) & 0xFF; - this.view[offset+2] = (k >>> 16) & 0xFF; - this.view[offset+1] = (k >>> 8) & 0xFF; - this.view[offset ] = k & 0xFF; - } else { - this.view[offset ] = (k >>> 24) & 0xFF; - this.view[offset+1] = (k >>> 16) & 0xFF; - this.view[offset+2] = (k >>> 8) & 0xFF; - this.view[offset+3] = k & 0xFF; - } - offset += 4; - utfx.encodeUTF16toUTF8(stringSource(str), function(b) { - this.view[offset++] = b; - }.bind(this)); - if (offset !== start + 4 + k) - throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k)); - if (relative) { - this.offset = offset; - return this; - } - return offset - start; - }; - - /** - * Reads a length as uint32 prefixed UTF8 encoded string. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string - * read and the actual number of bytes read. - * @expose - * @see ByteBuffer#readVarint32 - */ - ByteBufferPrototype.readIString = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 4 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength); - } - var start = offset; - var len = this.readUint32(offset); - var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4); - offset += str['length']; - if (relative) { - this.offset = offset; - return str['string']; - } else { - return { - 'string': str['string'], - 'length': offset - start - }; - } - }; - - // types/strings/utf8string - - /** - * Metrics representing number of UTF8 characters. Evaluates to `c`. - * @type {string} - * @const - * @expose - */ - ByteBuffer.METRICS_CHARS = 'c'; - - /** - * Metrics representing number of bytes. Evaluates to `b`. - * @type {string} - * @const - * @expose - */ - ByteBuffer.METRICS_BYTES = 'b'; - - /** - * Writes an UTF8 encoded string. - * @param {string} str String to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted. - * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written. - * @expose - */ - ByteBufferPrototype.writeUTF8String = function(str, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - var k; - var start = offset; - k = utfx.calculateUTF16asUTF8(stringSource(str))[1]; - offset += k; - var capacity14 = this.buffer.byteLength; - if (offset > capacity14) - this.resize((capacity14 *= 2) > offset ? capacity14 : offset); - offset -= k; - utfx.encodeUTF16toUTF8(stringSource(str), function(b) { - this.view[offset++] = b; - }.bind(this)); - if (relative) { - this.offset = offset; - return this; - } - return offset - start; - }; - - /** - * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}. - * @function - * @param {string} str String to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted. - * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written. - * @expose - */ - ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String; - - /** - * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's - * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF. - * @param {string} str String to calculate - * @returns {number} Number of UTF8 characters - * @expose - */ - ByteBuffer.calculateUTF8Chars = function(str) { - return utfx.calculateUTF16asUTF8(stringSource(str))[0]; - }; - - /** - * Calculates the number of UTF8 bytes of a string. - * @param {string} str String to calculate - * @returns {number} Number of UTF8 bytes - * @expose - */ - ByteBuffer.calculateUTF8Bytes = function(str) { - return utfx.calculateUTF16asUTF8(stringSource(str))[1]; - }; - - /** - * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}. - * @function - * @param {string} str String to calculate - * @returns {number} Number of UTF8 bytes - * @expose - */ - ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes; - - /** - * Reads an UTF8 encoded string. - * @param {number} length Number of characters or bytes to read. - * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to - * {@link ByteBuffer.METRICS_CHARS}. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string - * read and the actual number of bytes read. - * @expose - */ - ByteBufferPrototype.readUTF8String = function(length, metrics, offset) { - if (typeof metrics === 'number') { - offset = metrics; - metrics = undefined; - } - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS; - if (!this.noAssert) { - if (typeof length !== 'number' || length % 1 !== 0) - throw TypeError("Illegal length: "+length+" (not an integer)"); - length |= 0; - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - var i = 0, - start = offset, - sd; - if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser - sd = stringDestination(); - utfx.decodeUTF8(function() { - return i < length && offset < this.limit ? this.view[offset++] : null; - }.bind(this), function(cp) { - ++i; utfx.UTF8toUTF16(cp, sd); - }); - if (i !== length) - throw RangeError("Illegal range: Truncated data, "+i+" == "+length); - if (relative) { - this.offset = offset; - return sd(); - } else { - return { - "string": sd(), - "length": offset - start - }; - } - } else if (metrics === ByteBuffer.METRICS_BYTES) { - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + length > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength); - } - var k = offset + length; - utfx.decodeUTF8toUTF16(function() { - return offset < k ? this.view[offset++] : null; - }.bind(this), sd = stringDestination(), this.noAssert); - if (offset !== k) - throw RangeError("Illegal range: Truncated data, "+offset+" == "+k); - if (relative) { - this.offset = offset; - return sd(); - } else { - return { - 'string': sd(), - 'length': offset - start - }; - } - } else - throw TypeError("Unsupported metrics: "+metrics); - }; - - /** - * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}. - * @function - * @param {number} length Number of characters or bytes to read - * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to - * {@link ByteBuffer.METRICS_CHARS}. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string - * read and the actual number of bytes read. - * @expose - */ - ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String; - - // types/strings/vstring - - /** - * Writes a length as varint32 prefixed UTF8 encoded string. - * @param {string} str String to write - * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written - * @expose - * @see ByteBuffer#writeVarint32 - */ - ByteBufferPrototype.writeVString = function(str, offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof str !== 'string') - throw TypeError("Illegal str: Not a string"); - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - var start = offset, - k, l; - k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1]; - l = ByteBuffer.calculateVarint32(k); - offset += l+k; - var capacity15 = this.buffer.byteLength; - if (offset > capacity15) - this.resize((capacity15 *= 2) > offset ? capacity15 : offset); - offset -= l+k; - offset += this.writeVarint32(k, offset); - utfx.encodeUTF16toUTF8(stringSource(str), function(b) { - this.view[offset++] = b; - }.bind(this)); - if (offset !== start+k+l) - throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l)); - if (relative) { - this.offset = offset; - return this; - } - return offset - start; - }; - - /** - * Reads a length as varint32 prefixed UTF8 encoded string. - * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string - * read and the actual number of bytes read. - * @expose - * @see ByteBuffer#readVarint32 - */ - ByteBufferPrototype.readVString = function(offset) { - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 1 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength); - } - var start = offset; - var len = this.readVarint32(offset); - var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']); - offset += str['length']; - if (relative) { - this.offset = offset; - return str['string']; - } else { - return { - 'string': str['string'], - 'length': offset - start - }; - } - }; - - - /** - * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended - * data's length. - * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets - * will be modified according to the performed read operation. - * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") - * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. - * @returns {!ByteBuffer} this - * @expose - * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|` - * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|` - */ - ByteBufferPrototype.append = function(source, encoding, offset) { - if (typeof encoding === 'number' || typeof encoding !== 'string') { - offset = encoding; - encoding = undefined; - } - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - if (!(source instanceof ByteBuffer)) - source = ByteBuffer.wrap(source, encoding); - var length = source.limit - source.offset; - if (length <= 0) return this; // Nothing to append - offset += length; - var capacity16 = this.buffer.byteLength; - if (offset > capacity16) - this.resize((capacity16 *= 2) > offset ? capacity16 : offset); - offset -= length; - this.view.set(source.view.subarray(source.offset, source.limit), offset); - source.offset += length; - if (relative) this.offset += length; - return this; - }; - - /** - * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the - specified offset up to the length of this ByteBuffer's data. - * @param {!ByteBuffer} target Target ByteBuffer - * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * read if omitted. - * @returns {!ByteBuffer} this - * @expose - * @see ByteBuffer#append - */ - ByteBufferPrototype.appendTo = function(target, offset) { - target.append(this, offset); - return this; - }; - - /** - * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to - * disable them if your code already makes sure that everything is valid. - * @param {boolean} assert `true` to enable assertions, otherwise `false` - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.assert = function(assert) { - this.noAssert = !assert; - return this; - }; - - /** - * Gets the capacity of this ByteBuffer's backing buffer. - * @returns {number} Capacity of the backing buffer - * @expose - */ - ByteBufferPrototype.capacity = function() { - return this.buffer.byteLength; - }; - /** - * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the - * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.clear = function() { - this.offset = 0; - this.limit = this.buffer.byteLength; - this.markedOffset = -1; - return this; - }; - - /** - * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset}, - * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}. - * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false` - * @returns {!ByteBuffer} Cloned instance - * @expose - */ - ByteBufferPrototype.clone = function(copy) { - var bb = new ByteBuffer(0, this.littleEndian, this.noAssert); - if (copy) { - bb.buffer = new ArrayBuffer(this.buffer.byteLength); - bb.view = new Uint8Array(bb.buffer); - } else { - bb.buffer = this.buffer; - bb.view = this.view; - } - bb.offset = this.offset; - bb.markedOffset = this.markedOffset; - bb.limit = this.limit; - return bb; - }; - - /** - * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes - * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and - * adapt {@link ByteBuffer#markedOffset} to the same relative position if set. - * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset} - * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.compact = function(begin, end) { - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - if (begin === 0 && end === this.buffer.byteLength) - return this; // Already compacted - var len = end - begin; - if (len === 0) { - this.buffer = EMPTY_BUFFER; - this.view = null; - if (this.markedOffset >= 0) this.markedOffset -= begin; - this.offset = 0; - this.limit = 0; - return this; - } - var buffer = new ArrayBuffer(len); - var view = new Uint8Array(buffer); - view.set(this.view.subarray(begin, end)); - this.buffer = buffer; - this.view = view; - if (this.markedOffset >= 0) this.markedOffset -= begin; - this.offset = 0; - this.limit = len; - return this; - }; - - /** - * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and - * {@link ByteBuffer#limit}. - * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}. - * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. - * @returns {!ByteBuffer} Copy - * @expose - */ - ByteBufferPrototype.copy = function(begin, end) { - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - if (begin === end) - return new ByteBuffer(0, this.littleEndian, this.noAssert); - var capacity = end - begin, - bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert); - bb.offset = 0; - bb.limit = capacity; - if (bb.markedOffset >= 0) bb.markedOffset -= begin; - this.copyTo(bb, 0, begin, end); - return bb; - }; - - /** - * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and - * {@link ByteBuffer#limit}. - * @param {!ByteBuffer} target Target ByteBuffer - * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset} - * by the number of bytes copied if omitted. - * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the - * number of bytes copied if omitted. - * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit} - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) { - var relative, - targetRelative; - if (!this.noAssert) { - if (!ByteBuffer.isByteBuffer(target)) - throw TypeError("Illegal target: Not a ByteBuffer"); - } - targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0; - sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0; - sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0; - - if (targetOffset < 0 || targetOffset > target.buffer.byteLength) - throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength); - if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength) - throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength); - - var len = sourceLimit - sourceOffset; - if (len === 0) - return target; // Nothing to copy - - target.ensureCapacity(targetOffset + len); - - target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset); - - if (relative) this.offset += len; - if (targetRelative) target.offset += len; - - return this; - }; - - /** - * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the - * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity, - * the required capacity will be used instead. - * @param {number} capacity Required capacity - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.ensureCapacity = function(capacity) { - var current = this.buffer.byteLength; - if (current < capacity) - return this.resize((current *= 2) > capacity ? current : capacity); - return this; - }; - - /** - * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between - * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. - * @param {number|string} value Byte value to fill with. If given as a string, the first character is used. - * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes - * written if omitted. defaults to {@link ByteBuffer#offset}. - * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. - * @returns {!ByteBuffer} this - * @expose - * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes - */ - ByteBufferPrototype.fill = function(value, begin, end) { - var relative = typeof begin === 'undefined'; - if (relative) begin = this.offset; - if (typeof value === 'string' && value.length > 0) - value = value.charCodeAt(0); - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof value !== 'number' || value % 1 !== 0) - throw TypeError("Illegal value: "+value+" (not an integer)"); - value |= 0; - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - if (begin >= end) - return this; // Nothing to fill - while (begin < end) this.view[begin++] = value; - if (relative) this.offset = begin; - return this; - }; - - /** - * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and - * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.flip = function() { - this.limit = this.offset; - this.offset = 0; - return this; - }; - /** - * Marks an offset on this ByteBuffer to be used later. - * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}. - * @returns {!ByteBuffer} this - * @throws {TypeError} If `offset` is not a valid number - * @throws {RangeError} If `offset` is out of bounds - * @see ByteBuffer#reset - * @expose - */ - ByteBufferPrototype.mark = function(offset) { - offset = typeof offset === 'undefined' ? this.offset : offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - this.markedOffset = offset; - return this; - }; - /** - * Sets the byte order. - * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.order = function(littleEndian) { - if (!this.noAssert) { - if (typeof littleEndian !== 'boolean') - throw TypeError("Illegal littleEndian: Not a boolean"); - } - this.littleEndian = !!littleEndian; - return this; - }; - - /** - * Switches (to) little endian byte order. - * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.LE = function(littleEndian) { - this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true; - return this; - }; - - /** - * Switches (to) big endian byte order. - * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.BE = function(bigEndian) { - this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false; - return this; - }; - /** - * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the - * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer - * will be resized and its contents moved accordingly. - * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be - * modified according to the performed read operation. - * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8") - * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes - * prepended if omitted. - * @returns {!ByteBuffer} this - * @expose - * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|` - * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|` - */ - ByteBufferPrototype.prepend = function(source, encoding, offset) { - if (typeof encoding === 'number' || typeof encoding !== 'string') { - offset = encoding; - encoding = undefined; - } - var relative = typeof offset === 'undefined'; - if (relative) offset = this.offset; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: "+offset+" (not an integer)"); - offset >>>= 0; - if (offset < 0 || offset + 0 > this.buffer.byteLength) - throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength); - } - if (!(source instanceof ByteBuffer)) - source = ByteBuffer.wrap(source, encoding); - var len = source.limit - source.offset; - if (len <= 0) return this; // Nothing to prepend - var diff = len - offset; - if (diff > 0) { // Not enough space before offset, so resize + move - var buffer = new ArrayBuffer(this.buffer.byteLength + diff); - var view = new Uint8Array(buffer); - view.set(this.view.subarray(offset, this.buffer.byteLength), len); - this.buffer = buffer; - this.view = view; - this.offset += diff; - if (this.markedOffset >= 0) this.markedOffset += diff; - this.limit += diff; - offset += diff; - } else { - var arrayView = new Uint8Array(this.buffer); - } - this.view.set(source.view.subarray(source.offset, source.limit), offset - len); - - source.offset = source.limit; - if (relative) - this.offset -= len; - return this; - }; - - /** - * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the - * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer - * will be resized and its contents moved accordingly. - * @param {!ByteBuffer} target Target ByteBuffer - * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes - * prepended if omitted. - * @returns {!ByteBuffer} this - * @expose - * @see ByteBuffer#prepend - */ - ByteBufferPrototype.prependTo = function(target, offset) { - target.prepend(this, offset); - return this; - }; - /** - * Prints debug information about this ByteBuffer's contents. - * @param {function(string)=} out Output function to call, defaults to console.log - * @expose - */ - ByteBufferPrototype.printDebug = function(out) { - if (typeof out !== 'function') out = console.log.bind(console); - out( - this.toString()+"\n"+ - "-------------------------------------------------------------------\n"+ - this.toDebug(/* columns */ true) - ); - }; - - /** - * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and - * {@link ByteBuffer#limit}, so this returns `limit - offset`. - * @returns {number} Remaining readable bytes. May be negative if `offset > limit`. - * @expose - */ - ByteBufferPrototype.remaining = function() { - return this.limit - this.offset; - }; - /** - * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark} - * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been - * marked, sets `offset = 0`. - * @returns {!ByteBuffer} this - * @see ByteBuffer#mark - * @expose - */ - ByteBufferPrototype.reset = function() { - if (this.markedOffset >= 0) { - this.offset = this.markedOffset; - this.markedOffset = -1; - } else { - this.offset = 0; - } - return this; - }; - /** - * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that - * large or larger. - * @param {number} capacity Capacity required - * @returns {!ByteBuffer} this - * @throws {TypeError} If `capacity` is not a number - * @throws {RangeError} If `capacity < 0` - * @expose - */ - ByteBufferPrototype.resize = function(capacity) { - if (!this.noAssert) { - if (typeof capacity !== 'number' || capacity % 1 !== 0) - throw TypeError("Illegal capacity: "+capacity+" (not an integer)"); - capacity |= 0; - if (capacity < 0) - throw RangeError("Illegal capacity: 0 <= "+capacity); - } - if (this.buffer.byteLength < capacity) { - var buffer = new ArrayBuffer(capacity); - var view = new Uint8Array(buffer); - view.set(this.view); - this.buffer = buffer; - this.view = view; - } - return this; - }; - /** - * Reverses this ByteBuffer's contents. - * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset} - * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.reverse = function(begin, end) { - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - if (begin === end) - return this; // Nothing to reverse - Array.prototype.reverse.call(this.view.subarray(begin, end)); - return this; - }; - /** - * Skips the next `length` bytes. This will just advance - * @param {number} length Number of bytes to skip. May also be negative to move the offset back. - * @returns {!ByteBuffer} this - * @expose - */ - ByteBufferPrototype.skip = function(length) { - if (!this.noAssert) { - if (typeof length !== 'number' || length % 1 !== 0) - throw TypeError("Illegal length: "+length+" (not an integer)"); - length |= 0; - } - var offset = this.offset + length; - if (!this.noAssert) { - if (offset < 0 || offset > this.buffer.byteLength) - throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength); - } - this.offset = offset; - return this; - }; - - /** - * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`. - * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}. - * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}. - * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer} - * @expose - */ - ByteBufferPrototype.slice = function(begin, end) { - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - var bb = this.clone(); - bb.offset = begin; - bb.limit = end; - return bb; - }; - /** - * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between - * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. - * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if - * possible. Defaults to `false` - * @returns {!ArrayBuffer} Contents as an ArrayBuffer - * @expose - */ - ByteBufferPrototype.toBuffer = function(forceCopy) { - var offset = this.offset, - limit = this.limit; - if (!this.noAssert) { - if (typeof offset !== 'number' || offset % 1 !== 0) - throw TypeError("Illegal offset: Not an integer"); - offset >>>= 0; - if (typeof limit !== 'number' || limit % 1 !== 0) - throw TypeError("Illegal limit: Not an integer"); - limit >>>= 0; - if (offset < 0 || offset > limit || limit > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength); - } - // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is - // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So: - if (!forceCopy && offset === 0 && limit === this.buffer.byteLength) - return this.buffer; - if (offset === limit) - return EMPTY_BUFFER; - var buffer = new ArrayBuffer(limit - offset); - new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0); - return buffer; - }; - - /** - * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between - * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}. - * @function - * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory. - * Defaults to `false` - * @returns {!ArrayBuffer} Contents as an ArrayBuffer - * @expose - */ - ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer; - - /** - * Converts the ByteBuffer's contents to a string. - * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows - * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with - * highlighted offsets. - * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset} - * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit} - * @returns {string} String representation - * @throws {Error} If `encoding` is invalid - * @expose - */ - ByteBufferPrototype.toString = function(encoding, begin, end) { - if (typeof encoding === 'undefined') - return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")"; - if (typeof encoding === 'number') - encoding = "utf8", - begin = encoding, - end = begin; - switch (encoding) { - case "utf8": - return this.toUTF8(begin, end); - case "base64": - return this.toBase64(begin, end); - case "hex": - return this.toHex(begin, end); - case "binary": - return this.toBinary(begin, end); - case "debug": - return this.toDebug(); - case "columns": - return this.toColumns(); - default: - throw Error("Unsupported encoding: "+encoding); - } - }; - - // lxiv-embeddable - - /** - * lxiv-embeddable (c) 2014 Daniel Wirtz - * Released under the Apache License, Version 2.0 - * see: https://github.com/dcodeIO/lxiv for details - */ - var lxiv = function() { - "use strict"; - - /** - * lxiv namespace. - * @type {!Object.} - * @exports lxiv - */ - var lxiv = {}; - - /** - * Character codes for output. - * @type {!Array.} - * @inner - */ - var aout = [ - 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, - 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, - 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, - 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47 - ]; - - /** - * Character codes for input. - * @type {!Array.} - * @inner - */ - var ain = []; - for (var i=0, k=aout.length; i>2)&0x3f]); - t = (b&0x3)<<4; - if ((b = src()) !== null) { - t |= (b>>4)&0xf; - dst(aout[(t|((b>>4)&0xf))&0x3f]); - t = (b&0xf)<<2; - if ((b = src()) !== null) - dst(aout[(t|((b>>6)&0x3))&0x3f]), - dst(aout[b&0x3f]); - else - dst(aout[t&0x3f]), - dst(61); - } else - dst(aout[t&0x3f]), - dst(61), - dst(61); - } - }; - - /** - * Decodes base64 char codes to bytes. - * @param {!function():number|null} src Characters source as a function returning the next char code respectively - * `null` if there are no more characters left. - * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. - * @throws {Error} If a character code is invalid - */ - lxiv.decode = function(src, dst) { - var c, t1, t2; - function fail(c) { - throw Error("Illegal character code: "+c); - } - while ((c = src()) !== null) { - t1 = ain[c]; - if (typeof t1 === 'undefined') fail(c); - if ((c = src()) !== null) { - t2 = ain[c]; - if (typeof t2 === 'undefined') fail(c); - dst((t1<<2)>>>0|(t2&0x30)>>4); - if ((c = src()) !== null) { - t1 = ain[c]; - if (typeof t1 === 'undefined') - if (c === 61) break; else fail(c); - dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2); - if ((c = src()) !== null) { - t2 = ain[c]; - if (typeof t2 === 'undefined') - if (c === 61) break; else fail(c); - dst(((t1&0x3)<<6)>>>0|t2); - } - } - } - } - }; - - /** - * Tests if a string is valid base64. - * @param {string} str String to test - * @returns {boolean} `true` if valid, otherwise `false` - */ - lxiv.test = function(str) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str); - }; - - return lxiv; - }(); - - // encodings/base64 - - /** - * Encodes this ByteBuffer's contents to a base64 encoded string. - * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}. - * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}. - * @returns {string} Base64 encoded string - * @throws {RangeError} If `begin` or `end` is out of bounds - * @expose - */ - ByteBufferPrototype.toBase64 = function(begin, end) { - if (typeof begin === 'undefined') - begin = this.offset; - if (typeof end === 'undefined') - end = this.limit; - begin = begin | 0; end = end | 0; - if (begin < 0 || end > this.capacity || begin > end) - throw RangeError("begin, end"); - var sd; lxiv.encode(function() { - return begin < end ? this.view[begin++] : null; - }.bind(this), sd = stringDestination()); - return sd(); - }; - - /** - * Decodes a base64 encoded string to a ByteBuffer. - * @param {string} str String to decode - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @returns {!ByteBuffer} ByteBuffer - * @expose - */ - ByteBuffer.fromBase64 = function(str, littleEndian) { - if (typeof str !== 'string') - throw TypeError("str"); - var bb = new ByteBuffer(str.length/4*3, littleEndian), - i = 0; - lxiv.decode(stringSource(str), function(b) { - bb.view[i++] = b; - }); - bb.limit = i; - return bb; - }; - - /** - * Encodes a binary string to base64 like `window.btoa` does. - * @param {string} str Binary string - * @returns {string} Base64 encoded string - * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa - * @expose - */ - ByteBuffer.btoa = function(str) { - return ByteBuffer.fromBinary(str).toBase64(); - }; - - /** - * Decodes a base64 encoded string to binary like `window.atob` does. - * @param {string} b64 Base64 encoded string - * @returns {string} Binary string - * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob - * @expose - */ - ByteBuffer.atob = function(b64) { - return ByteBuffer.fromBase64(b64).toBinary(); - }; - - // encodings/binary - - /** - * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes. - * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}. - * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}. - * @returns {string} Binary encoded string - * @throws {RangeError} If `offset > limit` - * @expose - */ - ByteBufferPrototype.toBinary = function(begin, end) { - if (typeof begin === 'undefined') - begin = this.offset; - if (typeof end === 'undefined') - end = this.limit; - begin |= 0; end |= 0; - if (begin < 0 || end > this.capacity() || begin > end) - throw RangeError("begin, end"); - if (begin === end) - return ""; - var chars = [], - parts = []; - while (begin < end) { - chars.push(this.view[begin++]); - if (chars.length >= 1024) - parts.push(String.fromCharCode.apply(String, chars)), - chars = []; - } - return parts.join('') + String.fromCharCode.apply(String, chars); - }; - - /** - * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer. - * @param {string} str String to decode - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @returns {!ByteBuffer} ByteBuffer - * @expose - */ - ByteBuffer.fromBinary = function(str, littleEndian) { - if (typeof str !== 'string') - throw TypeError("str"); - var i = 0, - k = str.length, - charCode, - bb = new ByteBuffer(k, littleEndian); - while (i 0xff) - throw RangeError("illegal char code: "+charCode); - bb.view[i++] = charCode; - } - bb.limit = k; - return bb; - }; - - // encodings/debug - - /** - * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are: - * * `<` : offset, - * * `'` : markedOffset, - * * `>` : limit, - * * `|` : offset and limit, - * * `[` : offset and markedOffset, - * * `]` : markedOffset and limit, - * * `!` : offset, markedOffset and limit - * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false` - * @returns {string|!Array.} Debug string or array of lines if `asArray = true` - * @expose - * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3` - * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4` - * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1` - * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1` - */ - ByteBufferPrototype.toDebug = function(columns) { - var i = -1, - k = this.buffer.byteLength, - b, - hex = "", - asc = "", - out = ""; - while (i 32 && b < 127 ? String.fromCharCode(b) : '.'; - } - ++i; - if (columns) { - if (i > 0 && i % 16 === 0 && i !== k) { - while (hex.length < 3*16+3) hex += " "; - out += hex+asc+"\n"; - hex = asc = ""; - } - } - if (i === this.offset && i === this.limit) - hex += i === this.markedOffset ? "!" : "|"; - else if (i === this.offset) - hex += i === this.markedOffset ? "[" : "<"; - else if (i === this.limit) - hex += i === this.markedOffset ? "]" : ">"; - else - hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : ""); - } - if (columns && hex !== " ") { - while (hex.length < 3*16+3) - hex += " "; - out += hex + asc + "\n"; - } - return columns ? out : hex; - }; - - /** - * Decodes a hex encoded string with marked offsets to a ByteBuffer. - * @param {string} str Debug string to decode (not be generated with `columns = true`) - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} ByteBuffer - * @expose - * @see ByteBuffer#toDebug - */ - ByteBuffer.fromDebug = function(str, littleEndian, noAssert) { - var k = str.length, - bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert); - var i = 0, j = 0, ch, b, - rs = false, // Require symbol next - ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)? - fail = false; - while (i': - if (!noAssert) { - if (hl) { - fail = true; - break; - } - hl = true; - } - bb.limit = j; - rs = false; - break; - case "'": - if (!noAssert) { - if (hm) { - fail = true; - break; - } - hm = true; - } - bb.markedOffset = j; - rs = false; - break; - case ' ': - rs = false; - break; - default: - if (!noAssert) { - if (rs) { - fail = true; - break; - } - } - b = parseInt(ch+str.charAt(i++), 16); - if (!noAssert) { - if (isNaN(b) || b < 0 || b > 255) - throw TypeError("Illegal str: Not a debug encoded string"); - } - bb.view[j++] = b; - rs = true; - } - if (fail) - throw TypeError("Illegal str: Invalid symbol at "+i); - } - if (!noAssert) { - if (!ho || !hl) - throw TypeError("Illegal str: Missing offset or limit"); - if (j>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - var out = new Array(end - begin), - b; - while (begin < end) { - b = this.view[begin++]; - if (b < 0x10) - out.push("0", b.toString(16)); - else out.push(b.toString(16)); - } - return out.join(''); - }; - - /** - * Decodes a hex encoded string to a ByteBuffer. - * @param {string} str String to decode - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} ByteBuffer - * @expose - */ - ByteBuffer.fromHex = function(str, littleEndian, noAssert) { - if (!noAssert) { - if (typeof str !== 'string') - throw TypeError("Illegal str: Not a string"); - if (str.length % 2 !== 0) - throw TypeError("Illegal str: Length not a multiple of 2"); - } - var k = str.length, - bb = new ByteBuffer((k / 2) | 0, littleEndian), - b; - for (var i=0, j=0; i 255) - throw TypeError("Illegal str: Contains non-hex characters"); - bb.view[j++] = b; - } - bb.limit = j; - return bb; - }; - - // utfx-embeddable - - /** - * utfx-embeddable (c) 2014 Daniel Wirtz - * Released under the Apache License, Version 2.0 - * see: https://github.com/dcodeIO/utfx for details - */ - var utfx = function() { - "use strict"; - - /** - * utfx namespace. - * @inner - * @type {!Object.} - */ - var utfx = {}; - - /** - * Maximum valid code point. - * @type {number} - * @const - */ - utfx.MAX_CODEPOINT = 0x10FFFF; - - /** - * Encodes UTF8 code points to UTF8 bytes. - * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point - * respectively `null` if there are no more code points left or a single numeric code point. - * @param {!function(number)} dst Bytes destination as a function successively called with the next byte - */ - utfx.encodeUTF8 = function(src, dst) { - var cp = null; - if (typeof src === 'number') - cp = src, - src = function() { return null; }; - while (cp !== null || (cp = src()) !== null) { - if (cp < 0x80) - dst(cp&0x7F); - else if (cp < 0x800) - dst(((cp>>6)&0x1F)|0xC0), - dst((cp&0x3F)|0x80); - else if (cp < 0x10000) - dst(((cp>>12)&0x0F)|0xE0), - dst(((cp>>6)&0x3F)|0x80), - dst((cp&0x3F)|0x80); - else - dst(((cp>>18)&0x07)|0xF0), - dst(((cp>>12)&0x3F)|0x80), - dst(((cp>>6)&0x3F)|0x80), - dst((cp&0x3F)|0x80); - cp = null; - } - }; - - /** - * Decodes UTF8 bytes to UTF8 code points. - * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there - * are no more bytes left. - * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point. - * @throws {RangeError} If a starting byte is invalid in UTF8 - * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the - * remaining bytes. - */ - utfx.decodeUTF8 = function(src, dst) { - var a, b, c, d, fail = function(b) { - b = b.slice(0, b.indexOf(null)); - var err = Error(b.toString()); - err.name = "TruncatedError"; - err['bytes'] = b; - throw err; - }; - while ((a = src()) !== null) { - if ((a&0x80) === 0) - dst(a); - else if ((a&0xE0) === 0xC0) - ((b = src()) === null) && fail([a, b]), - dst(((a&0x1F)<<6) | (b&0x3F)); - else if ((a&0xF0) === 0xE0) - ((b=src()) === null || (c=src()) === null) && fail([a, b, c]), - dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F)); - else if ((a&0xF8) === 0xF0) - ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]), - dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F)); - else throw RangeError("Illegal starting byte: "+a); - } - }; - - /** - * Converts UTF16 characters to UTF8 code points. - * @param {!function():number|null} src Characters source as a function returning the next char code respectively - * `null` if there are no more characters left. - * @param {!function(number)} dst Code points destination as a function successively called with each converted code - * point. - */ - utfx.UTF16toUTF8 = function(src, dst) { - var c1, c2 = null; - while (true) { - if ((c1 = c2 !== null ? c2 : src()) === null) - break; - if (c1 >= 0xD800 && c1 <= 0xDFFF) { - if ((c2 = src()) !== null) { - if (c2 >= 0xDC00 && c2 <= 0xDFFF) { - dst((c1-0xD800)*0x400+c2-0xDC00+0x10000); - c2 = null; continue; - } - } - } - dst(c1); - } - if (c2 !== null) dst(c2); - }; - - /** - * Converts UTF8 code points to UTF16 characters. - * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point - * respectively `null` if there are no more code points left or a single numeric code point. - * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. - * @throws {RangeError} If a code point is out of range - */ - utfx.UTF8toUTF16 = function(src, dst) { - var cp = null; - if (typeof src === 'number') - cp = src, src = function() { return null; }; - while (cp !== null || (cp = src()) !== null) { - if (cp <= 0xFFFF) - dst(cp); - else - cp -= 0x10000, - dst((cp>>10)+0xD800), - dst((cp%0x400)+0xDC00); - cp = null; - } - }; - - /** - * Converts and encodes UTF16 characters to UTF8 bytes. - * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null` - * if there are no more characters left. - * @param {!function(number)} dst Bytes destination as a function successively called with the next byte. - */ - utfx.encodeUTF16toUTF8 = function(src, dst) { - utfx.UTF16toUTF8(src, function(cp) { - utfx.encodeUTF8(cp, dst); - }); - }; - - /** - * Decodes and converts UTF8 bytes to UTF16 characters. - * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there - * are no more bytes left. - * @param {!function(number)} dst Characters destination as a function successively called with each converted char code. - * @throws {RangeError} If a starting byte is invalid in UTF8 - * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes. - */ - utfx.decodeUTF8toUTF16 = function(src, dst) { - utfx.decodeUTF8(src, function(cp) { - utfx.UTF8toUTF16(cp, dst); - }); - }; - - /** - * Calculates the byte length of an UTF8 code point. - * @param {number} cp UTF8 code point - * @returns {number} Byte length - */ - utfx.calculateCodePoint = function(cp) { - return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; - }; - - /** - * Calculates the number of UTF8 bytes required to store UTF8 code points. - * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively - * `null` if there are no more code points left. - * @returns {number} The number of UTF8 bytes required - */ - utfx.calculateUTF8 = function(src) { - var cp, l=0; - while ((cp = src()) !== null) - l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; - return l; - }; - - /** - * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes. - * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively - * `null` if there are no more characters left. - * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1. - */ - utfx.calculateUTF16asUTF8 = function(src) { - var n=0, l=0; - utfx.UTF16toUTF8(src, function(cp) { - ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4; - }); - return [n,l]; - }; - - return utfx; - }(); - - // encodings/utf8 - - /** - * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded - * string. - * @returns {string} Hex encoded string - * @throws {RangeError} If `offset > limit` - * @expose - */ - ByteBufferPrototype.toUTF8 = function(begin, end) { - if (typeof begin === 'undefined') begin = this.offset; - if (typeof end === 'undefined') end = this.limit; - if (!this.noAssert) { - if (typeof begin !== 'number' || begin % 1 !== 0) - throw TypeError("Illegal begin: Not an integer"); - begin >>>= 0; - if (typeof end !== 'number' || end % 1 !== 0) - throw TypeError("Illegal end: Not an integer"); - end >>>= 0; - if (begin < 0 || begin > end || end > this.buffer.byteLength) - throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength); - } - var sd; try { - utfx.decodeUTF8toUTF16(function() { - return begin < end ? this.view[begin++] : null; - }.bind(this), sd = stringDestination()); - } catch (e) { - if (begin !== end) - throw RangeError("Illegal range: Truncated data, "+begin+" != "+end); - } - return sd(); - }; - - /** - * Decodes an UTF8 encoded string to a ByteBuffer. - * @param {string} str String to decode - * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to - * {@link ByteBuffer.DEFAULT_ENDIAN}. - * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to - * {@link ByteBuffer.DEFAULT_NOASSERT}. - * @returns {!ByteBuffer} ByteBuffer - * @expose - */ - ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) { - if (!noAssert) - if (typeof str !== 'string') - throw TypeError("Illegal str: Not a string"); - var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert), - i = 0; - utfx.encodeUTF16toUTF8(stringSource(str), function(b) { - bb.view[i++] = b; - }); - bb.limit = i; - return bb; - }; - - return ByteBuffer; -}); - - -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { - -var Buffer = __webpack_require__(0).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 - - -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = { "default": __webpack_require__(186), __esModule: true }; - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = __webpack_require__(107); -var enumBugKeys = __webpack_require__(76); - -module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); -}; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = function (it) { - return toString.call(it).slice(8, -1); -}; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - -module.exports = true; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = { "default": __webpack_require__(191), __esModule: true }; - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.__esModule = true; - -var _promise = __webpack_require__(39); - -var _promise2 = _interopRequireDefault(_promise); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function (fn) { - return function () { - var gen = fn.apply(this, arguments); - return new _promise2.default(function (resolve, reject) { - function step(key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - return _promise2.default.resolve(value).then(function (value) { - step("next", value); - }, function (err) { - step("throw", err); - }); - } - } - - return step("next"); - }); - }; -}; - -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.__esModule = true; - -var _iterator = __webpack_require__(241); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _symbol = __webpack_require__(243); - -var _symbol2 = _interopRequireDefault(_symbol); - -var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; }; - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { - return typeof obj === "undefined" ? "undefined" : _typeof(obj); -} : function (obj) { - return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); -}; - -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {module.exports = function xor (a, b) { - var length = Math.min(a.length, b.length) - var buffer = new Buffer(length) - - for (var i = 0; i < length; ++i) { - buffer[i] = a[i] ^ b[i] - } - - return buffer -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var assert = __webpack_require__(4); -var ecurve = __webpack_require__(93); -var BigInteger = __webpack_require__(16); -var secp256k1 = ecurve.getCurveByName('secp256k1'); - -var hash = __webpack_require__(25); -var keyUtils = __webpack_require__(46); - -var G = secp256k1.G; -var n = secp256k1.n; - -module.exports = PublicKey; - -/** @param {ecurve.Point} public key */ -function PublicKey(Q) { - if (typeof Q === 'string') { - var publicKey = PublicKey.fromString(Q); - assert(publicKey != null, 'Invalid public key'); - return publicKey; - } else if (Buffer.isBuffer(Q)) { - return PublicKey.fromBuffer(Q); - } else if ((typeof Q === 'undefined' ? 'undefined' : _typeof(Q)) === 'object' && Q.Q) { - return PublicKey(Q.Q); - } - - assert.equal(typeof Q === 'undefined' ? 'undefined' : _typeof(Q), 'object', 'Invalid public key'); - assert.equal(_typeof(Q.compressed), 'boolean', 'Invalid public key'); - - function toBuffer() { - var compressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Q.compressed; - - return Q.getEncoded(compressed); - } - - var pubdata = void 0; // cache - - // /** - // @todo secp224r1 - // @return {string} PUB_K1_base58pubkey.. - // */ - // function toString() { - // if(pubdata) { - // return pubdata - // } - // pubdata = `PUB_K1_` + keyUtils.checkEncode(toBuffer(), 'K1') - // return pubdata; - // } - - /** @todo rename to toStringLegacy - * @arg {string} [pubkey_prefix = 'EOS'] - public key prefix - */ - function toString() { - var pubkey_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EOS'; - - return pubkey_prefix + keyUtils.checkEncode(toBuffer()); - } - - function toUncompressed() { - var buf = Q.getEncoded(false); - var point = ecurve.Point.decodeFrom(secp256k1, buf); - return PublicKey.fromPoint(point); - } - - /** @deprecated */ - function child(offset) { - console.error('Deprecated warning: PublicKey.child'); - - assert(Buffer.isBuffer(offset), "Buffer required: offset"); - assert.equal(offset.length, 32, "offset length"); - - offset = Buffer.concat([toBuffer(), offset]); - offset = hash.sha256(offset); - - var c = BigInteger.fromBuffer(offset); - - if (c.compareTo(n) >= 0) throw new Error("Child offset went out of bounds, try again"); - - var cG = G.multiply(c); - var Qprime = Q.add(cG); - - if (secp256k1.isInfinity(Qprime)) throw new Error("Child offset derived to an invalid key, try again"); - - return PublicKey.fromPoint(Qprime); - } - - function toHex() { - return toBuffer().toString('hex'); - } - - return { - Q: Q, - toString: toString, - // toStringLegacy, - toUncompressed: toUncompressed, - toBuffer: toBuffer, - child: child, - toHex: toHex - }; -} - -PublicKey.isValid = function (text) { - try { - PublicKey(text); - return true; - } catch (e) { - return false; - } -}; - -PublicKey.fromBinary = function (bin) { - return PublicKey.fromBuffer(new Buffer(bin, 'binary')); -}; - -PublicKey.fromBuffer = function (buffer) { - return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer)); -}; - -PublicKey.fromPoint = function (point) { - return PublicKey(point); -}; - -/** - @arg {string} public_key - like PUB_K1_base58pubkey.. - @arg {string} [pubkey_prefix = 'EOS'] - public key prefix - @return PublicKey or `null` (invalid) -*/ -PublicKey.fromString = function (public_key) { - var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; - - try { - return PublicKey.fromStringOrThrow(public_key, pubkey_prefix); - } catch (e) { - return null; - } -}; - -/** - @arg {string} public_key - like PUB_K1_base58pubkey.. - @arg {string} [pubkey_prefix = 'EOS'] - public key prefix - - @throws {Error} if public key is invalid - - @return PublicKey -*/ -PublicKey.fromStringOrThrow = function (public_key) { - var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS'; - - assert.equal(typeof public_key === 'undefined' ? 'undefined' : _typeof(public_key), 'string', 'public_key'); - var match = public_key.match(/^PUB_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); - if (match === null) { - // legacy - // TELOS addition: support for variable public_key prefixes - var prefix_match = new RegExp("^" + pubkey_prefix); - if (prefix_match.test(public_key)) { - public_key = public_key.substring(pubkey_prefix.length); - } - return PublicKey.fromBuffer(keyUtils.checkDecode(public_key)); - } - assert(match.length === 3, 'Expecting public key like: PUB_K1_base58pubkey..'); - - var _match = _slicedToArray(match, 3), - keyType = _match[1], - keyString = _match[2]; - - assert.equal(keyType, 'K1', 'K1 private key expected'); - return PublicKey.fromBuffer(keyUtils.checkDecode(keyString, keyType)); -}; - -PublicKey.fromHex = function (hex) { - return PublicKey.fromBuffer(new Buffer(hex, 'hex')); -}; - -PublicKey.fromStringHex = function (hex) { - return PublicKey.fromString(new Buffer(hex, 'hex')); -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var inherits = __webpack_require__(1) -var MD5 = __webpack_require__(92) -var RIPEMD160 = __webpack_require__(152) -var sha = __webpack_require__(153) -var Base = __webpack_require__(23) - -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)) -} - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var base58 = __webpack_require__(288); -var assert = __webpack_require__(4); -var randomBytes = __webpack_require__(135); - -var hash = __webpack_require__(25); - -module.exports = { - random32ByteBuffer: random32ByteBuffer, - addEntropy: addEntropy, - cpuEntropy: cpuEntropy, - entropyCount: function entropyCount() { - return _entropyCount; - }, - checkDecode: checkDecode, - checkEncode: checkEncode -}; - -var entropyPos = 0, - _entropyCount = 0; - -var externalEntropyArray = randomBytes(101); - -/** - Additional forms of entropy are used. A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe. - - @arg {number} [cpuEntropyBits = 0] generate entropy on the fly. This is - not required, entropy can be added in advanced via addEntropy or initialize(). - - @arg {boolean} [safe = true] false for testing, otherwise this will be - true to ensure initialize() was called. - - @return a random buffer obtained from the secure random number generator. Additional entropy is used. -*/ -function random32ByteBuffer() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$cpuEntropyBits = _ref.cpuEntropyBits, - cpuEntropyBits = _ref$cpuEntropyBits === undefined ? 0 : _ref$cpuEntropyBits, - _ref$safe = _ref.safe, - safe = _ref$safe === undefined ? true : _ref$safe; - - assert.equal(typeof cpuEntropyBits === 'undefined' ? 'undefined' : _typeof(cpuEntropyBits), 'number', 'cpuEntropyBits'); - assert.equal(typeof safe === 'undefined' ? 'undefined' : _typeof(safe), 'boolean', 'boolean'); - - if (safe) { - assert(_entropyCount >= 128, 'Call initialize() to add entropy'); - } - - // if(entropyCount > 0) { - // console.log(`Additional private key entropy: ${entropyCount} events`) - // } - - var hash_array = []; - hash_array.push(randomBytes(32)); - hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits))); - hash_array.push(externalEntropyArray); - hash_array.push(browserEntropy()); - return hash.sha256(Buffer.concat(hash_array)); -} - -/** - Adds entropy. This may be called many times while the amount of data saved - is accumulatively reduced to 101 integers. Data is retained in RAM for the - life of this module. - - @example React - componentDidMount() { - this.refs.MyComponent.addEventListener("mousemove", this.onEntropyEvent, {capture: false, passive: true}) - } - componentWillUnmount() { - this.refs.MyComponent.removeEventListener("mousemove", this.onEntropyEvent); - } - onEntropyEvent = (e) => { - if(e.type === 'mousemove') - key_utils.addEntropy(e.pageX, e.pageY, e.screenX, e.screenY) - else - console.log('onEntropyEvent Unknown', e.type, e) - } - -*/ -function addEntropy() { - assert.equal(externalEntropyArray.length, 101, 'externalEntropyArray'); - - for (var _len = arguments.length, ints = Array(_len), _key = 0; _key < _len; _key++) { - ints[_key] = arguments[_key]; - } - - _entropyCount += ints.length; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = ints[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var i = _step.value; - - var pos = entropyPos++ % 101; - var i2 = externalEntropyArray[pos] += i; - if (i2 > 9007199254740991) externalEntropyArray[pos] = 0; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } -} - -/** - This runs in just under 1 second and ensures a minimum of cpuEntropyBits - bits of entropy are gathered. - - Based on more-entropy. @see https://github.com/keybase/more-entropy/blob/master/src/generator.iced - - @arg {number} [cpuEntropyBits = 128] - @return {array} counts gathered by measuring variations in the CPU speed during floating point operations. -*/ -function cpuEntropy() { - var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128; - - var collected = []; - var lastCount = null; - var lowEntropySamples = 0; - while (collected.length < cpuEntropyBits) { - var count = floatingPointCount(); - if (lastCount != null) { - var delta = count - lastCount; - if (Math.abs(delta) < 1) { - lowEntropySamples++; - continue; - } - // how many bits of entropy were in this sample - var bits = Math.floor(log2(Math.abs(delta)) + 1); - if (bits < 4) { - if (bits < 2) { - lowEntropySamples++; - } - continue; - } - collected.push(delta); - } - lastCount = count; - } - if (lowEntropySamples > 10) { - var pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2); - // Is this algorithm getting inefficient? - console.warn('WARN: ' + pct + '% low CPU entropy re-sampled'); - } - return collected; -} - -/** - @private - Count while performing floating point operations during a fixed time - (7 ms for example). Using a fixed time makes this algorithm - predictable in runtime. -*/ -function floatingPointCount() { - var workMinMs = 7; - var d = Date.now(); - var i = 0, - x = 0; - while (Date.now() < d + workMinMs + 1) { - x = Math.sin(Math.sqrt(Math.log(++i + x))); - } - return i; -} - -var log2 = function log2(x) { - return Math.log(x) / Math.LN2; -}; - -/** - @private - Attempt to gather and hash information from the browser's window, history, and supported mime types. For non-browser environments this simply includes secure random data. In any event, the information is re-hashed in a loop for 25 milliseconds seconds. - - @return {Buffer} 32 bytes -*/ -function browserEntropy() { - var entropyStr = Array(randomBytes(101)).join(); - try { - entropyStr += new Date().toString() + " " + window.screen.height + " " + window.screen.width + " " + window.screen.colorDepth + " " + " " + window.screen.availHeight + " " + window.screen.availWidth + " " + window.screen.pixelDepth + navigator.language + " " + window.location + " " + window.history.length; - - for (var i = 0, mimeType; i < navigator.mimeTypes.length; i++) { - mimeType = navigator.mimeTypes[i]; - entropyStr += mimeType.description + " " + mimeType.type + " " + mimeType.suffixes + " "; - } - } catch (error) { - //nodejs:ReferenceError: window is not defined - entropyStr += hash.sha256(new Date().toString()); - } - - var b = new Buffer(entropyStr); - entropyStr += b.toString('binary') + " " + new Date().toString(); - - var entropy = entropyStr; - var start_t = Date.now(); - while (Date.now() - start_t < 25) { - entropy = hash.sha256(entropy); - }return entropy; -} - -/** - @arg {Buffer} keyBuffer data - @arg {string} keyType = sha256x2, K1, etc - @return {string} checksum encoded base58 string -*/ -function checkEncode(keyBuffer) { - var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - - assert(Buffer.isBuffer(keyBuffer), 'expecting keyBuffer'); - if (keyType === 'sha256x2') { - // legacy - var checksum = hash.sha256(hash.sha256(keyBuffer)).slice(0, 4); - return base58.encode(Buffer.concat([keyBuffer, checksum])); - } else { - var check = [keyBuffer]; - if (keyType) { - check.push(Buffer.from(keyType)); - } - var _checksum = hash.ripemd160(Buffer.concat(check)).slice(0, 4); - return base58.encode(Buffer.concat([keyBuffer, _checksum])); - } -} - -/** - @arg {Buffer} keyString data - @arg {string} keyType = sha256x2, K1, etc - @return {string} checksum encoded base58 string -*/ -function checkDecode(keyString) { - var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - - assert(keyString != null, 'private key expected'); - var buffer = new Buffer(base58.decode(keyString)); - var checksum = buffer.slice(-4); - var key = buffer.slice(0, -4); - - var newCheck = void 0; - if (keyType === 'sha256x2') { - // legacy - newCheck = hash.sha256(hash.sha256(key)).slice(0, 4); // WIF (legacy) - } else { - var check = [key]; - if (keyType) { - check.push(Buffer.from(keyType)); - } - newCheck = hash.ripemd160(Buffer.concat(check)).slice(0, 4); //PVT - } - - if (checksum.toString() !== newCheck.toString()) { - throw new Error('Invalid checksum, ' + (checksum.toString('hex') + ' != ' + newCheck.toString('hex'))); - } - - return key; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var createKeccakHash = __webpack_require__(333); -var secp256k1 = __webpack_require__(339); -var assert = __webpack_require__(4); -var rlp = __webpack_require__(368); -var BN = __webpack_require__(9); -var createHash = __webpack_require__(45); -var Buffer = __webpack_require__(0).Buffer; -Object.assign(exports, __webpack_require__(170)); - -/** - * the max integer that this VM can handle (a ```BN```) - * @var {BN} MAX_INTEGER - */ -exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); - -/** - * 2^256 (a ```BN```) - * @var {BN} TWO_POW256 - */ -exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); - -/** - * Keccak-256 hash of null (a ```String```) - * @var {String} KECCAK256_NULL_S - */ -exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; -exports.SHA3_NULL_S = exports.KECCAK256_NULL_S; - -/** - * Keccak-256 hash of null (a ```Buffer```) - * @var {Buffer} KECCAK256_NULL - */ -exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); -exports.SHA3_NULL = exports.KECCAK256_NULL; - -/** - * Keccak-256 of an RLP of an empty array (a ```String```) - * @var {String} KECCAK256_RLP_ARRAY_S - */ -exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; -exports.SHA3_RLP_ARRAY_S = exports.KECCAK256_RLP_ARRAY_S; - -/** - * Keccak-256 of an RLP of an empty array (a ```Buffer```) - * @var {Buffer} KECCAK256_RLP_ARRAY - */ -exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); -exports.SHA3_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY; - -/** - * Keccak-256 hash of the RLP of null (a ```String```) - * @var {String} KECCAK256_RLP_S - */ -exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; -exports.SHA3_RLP_S = exports.KECCAK256_RLP_S; - -/** - * Keccak-256 hash of the RLP of null (a ```Buffer```) - * @var {Buffer} KECCAK256_RLP - */ -exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); -exports.SHA3_RLP = exports.KECCAK256_RLP; - -/** - * [`BN`](https://github.com/indutny/bn.js) - * @var {Function} - */ -exports.BN = BN; - -/** - * [`rlp`](https://github.com/ethereumjs/rlp) - * @var {Function} - */ -exports.rlp = rlp; - -/** - * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) - * @var {Object} - */ -exports.secp256k1 = secp256k1; - -/** - * Returns a buffer filled with 0s - * @method zeros - * @param {Number} bytes the number of bytes the buffer should be - * @return {Buffer} - */ -exports.zeros = function (bytes) { - return Buffer.allocUnsafe(bytes).fill(0); -}; - -/** - * Returns a zero address - * @method zeroAddress - * @return {String} - */ -exports.zeroAddress = function () { - var addressLength = 20; - var zeroAddress = exports.zeros(addressLength); - return exports.bufferToHex(zeroAddress); -}; - -/** - * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @method lsetLength - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @param {Boolean} [right=false] whether to start padding form the left or right - * @return {Buffer|Array} - */ -exports.setLengthLeft = exports.setLength = function (msg, length, right) { - var buf = exports.zeros(length); - msg = exports.toBuffer(msg); - if (right) { - if (msg.length < length) { - msg.copy(buf); - return buf; - } - return msg.slice(0, length); - } else { - if (msg.length < length) { - msg.copy(buf, length - msg.length); - return buf; - } - return msg.slice(-length); - } -}; - -/** - * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @return {Buffer|Array} - */ -exports.setLengthRight = function (msg, length) { - return exports.setLength(msg, length, true); -}; - -/** - * Trims leading zeros from a `Buffer` or an `Array` - * @param {Buffer|Array|String} a - * @return {Buffer|Array|String} - */ -exports.unpad = exports.stripZeros = function (a) { - a = exports.stripHexPrefix(a); - var first = a[0]; - while (a.length > 0 && first.toString() === '0') { - a = a.slice(1); - first = a[0]; - } - return a; -}; -/** - * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. - * @param {*} v the value - */ -exports.toBuffer = function (v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = Buffer.from(v); - } else if (typeof v === 'string') { - if (exports.isHexString(v)) { - v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); - } else { - v = Buffer.from(v); - } - } else if (typeof v === 'number') { - v = exports.intToBuffer(v); - } else if (v === null || v === undefined) { - v = Buffer.allocUnsafe(0); - } else if (BN.isBN(v)) { - v = v.toArrayLike(Buffer); - } else if (v.toArray) { - // converts a BN to a Buffer - v = Buffer.from(v.toArray()); - } else { - throw new Error('invalid type'); - } - } - return v; -}; - -/** - * Converts a `Buffer` to a `Number` - * @param {Buffer} buf - * @return {Number} - * @throws If the input number exceeds 53 bits. - */ -exports.bufferToInt = function (buf) { - return new BN(exports.toBuffer(buf)).toNumber(); -}; - -/** - * Converts a `Buffer` into a hex `String` - * @param {Buffer} buf - * @return {String} - */ -exports.bufferToHex = function (buf) { - buf = exports.toBuffer(buf); - return '0x' + buf.toString('hex'); -}; - -/** - * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. - * @param {Buffer} num - * @return {BN} - */ -exports.fromSigned = function (num) { - return new BN(num).fromTwos(256); -}; - -/** - * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. - * @param {BN} num - * @return {Buffer} - */ -exports.toUnsigned = function (num) { - return Buffer.from(num.toTwos(256).toArray()); -}; - -/** - * Creates Keccak hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bits=256] the Keccak width - * @return {Buffer} - */ -exports.keccak = function (a, bits) { - a = exports.toBuffer(a); - if (!bits) bits = 256; - - return createKeccakHash('keccak' + bits).update(a).digest(); -}; - -/** - * Creates Keccak-256 hash of the input, alias for keccak(a, 256) - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.keccak256 = function (a) { - return exports.keccak(a); -}; - -/** - * Creates SHA-3 (Keccak) hash of the input [OBSOLETE] - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bits=256] the SHA-3 width - * @return {Buffer} - */ -exports.sha3 = exports.keccak; - -/** - * Creates SHA256 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.sha256 = function (a) { - a = exports.toBuffer(a); - return createHash('sha256').update(a).digest(); -}; - -/** - * Creates RIPEMD160 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Boolean} padded whether it should be padded to 256 bits or not - * @return {Buffer} - */ -exports.ripemd160 = function (a, padded) { - a = exports.toBuffer(a); - var hash = createHash('rmd160').update(a).digest(); - if (padded === true) { - return exports.setLength(hash, 32); - } else { - return hash; - } -}; - -/** - * Creates SHA-3 hash of the RLP encoded version of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.rlphash = function (a) { - return exports.keccak(rlp.encode(a)); -}; - -/** - * Checks if the private key satisfies the rules of the curve secp256k1. - * @param {Buffer} privateKey - * @return {Boolean} - */ -exports.isValidPrivate = function (privateKey) { - return secp256k1.privateKeyVerify(privateKey); -}; - -/** - * Checks if the public key satisfies the rules of the curve secp256k1 - * and the requirements of Ethereum. - * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Boolean} - */ -exports.isValidPublic = function (publicKey, sanitize) { - if (publicKey.length === 64) { - // Convert to SEC1 for secp256k1 - return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); - } - - if (!sanitize) { - return false; - } - - return secp256k1.publicKeyVerify(publicKey); -}; - -/** - * Returns the ethereum address of a given public key. - * Accepts "Ethereum public keys" and SEC1 encoded keys. - * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Buffer} - */ -exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { - pubKey = exports.toBuffer(pubKey); - if (sanitize && pubKey.length !== 64) { - pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); - } - assert(pubKey.length === 64); - // Only take the lower 160bits of the hash - return exports.keccak(pubKey).slice(-20); -}; - -/** - * Returns the ethereum public key of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -var privateToPublic = exports.privateToPublic = function (privateKey) { - privateKey = exports.toBuffer(privateKey); - // skip the type flag and use the X, Y points - return secp256k1.publicKeyCreate(privateKey, false).slice(1); -}; - -/** - * Converts a public key to the Ethereum format. - * @param {Buffer} publicKey - * @return {Buffer} - */ -exports.importPublic = function (publicKey) { - publicKey = exports.toBuffer(publicKey); - if (publicKey.length !== 64) { - publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); - } - return publicKey; -}; - -/** - * ECDSA sign - * @param {Buffer} msgHash - * @param {Buffer} privateKey - * @return {Object} - */ -exports.ecsign = function (msgHash, privateKey) { - var sig = secp256k1.sign(msgHash, privateKey); - - var ret = {}; - ret.r = sig.signature.slice(0, 32); - ret.s = sig.signature.slice(32, 64); - ret.v = sig.recovery + 27; - return ret; -}; - -/** - * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. - * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` - * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key - * used to produce the signature. - * @param message - * @returns {Buffer} hash - */ -exports.hashPersonalMessage = function (message) { - var prefix = exports.toBuffer('\x19Ethereum Signed Message:\n' + message.length.toString()); - return exports.keccak(Buffer.concat([prefix, message])); -}; - -/** - * ECDSA public key recovery from signature - * @param {Buffer} msgHash - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {Buffer} publicKey - */ -exports.ecrecover = function (msgHash, v, r, s) { - var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); - var recovery = v - 27; - if (recovery !== 0 && recovery !== 1) { - throw new Error('Invalid signature v value'); - } - var senderPubKey = secp256k1.recover(msgHash, signature, recovery); - return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); -}; - -/** - * Convert signature parameters into the format of `eth_sign` RPC method - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {String} sig - */ -exports.toRpcSig = function (v, r, s) { - // NOTE: with potential introduction of chainId this might need to be updated - if (v !== 27 && v !== 28) { - throw new Error('Invalid recovery id'); - } - - // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin - // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 - return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v - 27)])); -}; - -/** - * Convert signature format of the `eth_sign` RPC method to signature parameters - * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 - * @param {String} sig - * @return {Object} - */ -exports.fromRpcSig = function (sig) { - sig = exports.toBuffer(sig); - - // NOTE: with potential introduction of chainId this might need to be updated - if (sig.length !== 65) { - throw new Error('Invalid signature length'); - } - - var v = sig[64]; - // support both versions of `eth_sign` responses - if (v < 27) { - v += 27; - } - - return { - v: v, - r: sig.slice(0, 32), - s: sig.slice(32, 64) - }; -}; - -/** - * Returns the ethereum address of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -exports.privateToAddress = function (privateKey) { - return exports.publicToAddress(privateToPublic(privateKey)); -}; - -/** - * Checks if the address is a valid. Accepts checksummed addresses too - * @param {String} address - * @return {Boolean} - */ -exports.isValidAddress = function (address) { - return (/^0x[0-9a-fA-F]{40}$/.test(address) - ); -}; - -/** - * Checks if a given address is a zero address - * @method isZeroAddress - * @param {String} address - * @return {Boolean} - */ -exports.isZeroAddress = function (address) { - var zeroAddress = exports.zeroAddress(); - return zeroAddress === exports.addHexPrefix(address); -}; - -/** - * Returns a checksummed address - * @param {String} address - * @return {String} - */ -exports.toChecksumAddress = function (address) { - address = exports.stripHexPrefix(address).toLowerCase(); - var hash = exports.keccak(address).toString('hex'); - var ret = '0x'; - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase(); - } else { - ret += address[i]; - } - } - - return ret; -}; - -/** - * Checks if the address is a valid checksummed address - * @param {Buffer} address - * @return {Boolean} - */ -exports.isValidChecksumAddress = function (address) { - return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; -}; - -/** - * Generates an address of a newly created contract - * @param {Buffer} from the address which is creating this new address - * @param {Buffer} nonce the nonce of the from account - * @return {Buffer} - */ -exports.generateAddress = function (from, nonce) { - from = exports.toBuffer(from); - nonce = new BN(nonce); - - if (nonce.isZero()) { - // in RLP we want to encode null in the case of zero nonce - // read the RLP documentation for an answer if you dare - nonce = null; - } else { - nonce = Buffer.from(nonce.toArray()); - } - - // Only take the lower 160bits of the hash - return exports.rlphash([from, nonce]).slice(-20); -}; - -/** - * Returns true if the supplied address belongs to a precompiled account (Byzantium) - * @param {Buffer|String} address - * @return {Boolean} - */ -exports.isPrecompiled = function (address) { - var a = exports.unpad(address); - return a.length === 1 && a[0] >= 1 && a[0] <= 8; -}; - -/** - * Adds "0x" to a given `String` if it does not already start with "0x" - * @param {String} str - * @return {String} - */ -exports.addHexPrefix = function (str) { - if (typeof str !== 'string') { - return str; - } - - return exports.isHexPrefixed(str) ? str : '0x' + str; -}; - -/** - * Validate ECDSA signature - * @method isValidSignature - * @param {Buffer} v - * @param {Buffer} r - * @param {Buffer} s - * @param {Boolean} [homestead=true] - * @return {Boolean} - */ - -exports.isValidSignature = function (v, r, s, homestead) { - var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); - - if (r.length !== 32 || s.length !== 32) { - return false; - } - - if (v !== 27 && v !== 28) { - return false; - } - - r = new BN(r); - s = new BN(s); - - if (r.isZero() || r.gt(SECP256K1_N) || s.isZero() || s.gt(SECP256K1_N)) { - return false; - } - - if (homestead === false && new BN(s).cmp(SECP256K1_N_DIV_2) === 1) { - return false; - } - - return true; -}; - -/** - * Converts a `Buffer` or `Array` to JSON - * @param {Buffer|Array} ba - * @return {Array|String|null} - */ -exports.baToJSON = function (ba) { - if (Buffer.isBuffer(ba)) { - return '0x' + ba.toString('hex'); - } else if (ba instanceof Array) { - var array = []; - for (var i = 0; i < ba.length; i++) { - array.push(exports.baToJSON(ba[i])); - } - return array; - } -}; - -/** - * Defines properties on a `Object`. It make the assumption that underlying data is binary. - * @param {Object} self the `Object` to define properties on - * @param {Array} fields an array fields to define. Fields can contain: - * * `name` - the name of the properties - * * `length` - the number of bytes the field can have - * * `allowLess` - if the field can be less than the length - * * `allowEmpty` - * @param {*} data data to be validated against the definitions - */ -exports.defineProperties = function (self, fields, data) { - self.raw = []; - self._fields = []; - - // attach the `toJSON` - self.toJSON = function (label) { - if (label) { - var obj = {}; - self._fields.forEach(function (field) { - obj[field] = '0x' + self[field].toString('hex'); - }); - return obj; - } - return exports.baToJSON(this.raw); - }; - - self.serialize = function serialize() { - return rlp.encode(self.raw); - }; - - fields.forEach(function (field, i) { - self._fields.push(field.name); - function getter() { - return self.raw[i]; - } - function setter(v) { - v = exports.toBuffer(v); - - if (v.toString('hex') === '00' && !field.allowZero) { - v = Buffer.allocUnsafe(0); - } - - if (field.allowLess && field.length) { - v = exports.stripZeros(v); - assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes'); - } else if (!(field.allowZero && v.length === 0) && field.length) { - assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length); - } - - self.raw[i] = v; - } - - Object.defineProperty(self, field.name, { - enumerable: true, - configurable: true, - get: getter, - set: setter - }); - - if (field.default) { - self[field.name] = field.default; - } - - // attach alias - if (field.alias) { - Object.defineProperty(self, field.alias, { - enumerable: false, - configurable: true, - set: setter, - get: getter - }); - } - }); - - // if the constuctor is passed data - if (data) { - if (typeof data === 'string') { - data = Buffer.from(exports.stripHexPrefix(data), 'hex'); - } - - if (Buffer.isBuffer(data)) { - data = rlp.decode(data); - } - - if (Array.isArray(data)) { - if (data.length > self._fields.length) { - throw new Error('wrong number of fields in data'); - } - - // make sure all the items are buffers - data.forEach(function (d, i) { - self[self._fields[i]] = exports.toBuffer(d); - }); - } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { - var keys = Object.keys(data); - fields.forEach(function (field) { - if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]; - if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; - }); - } else { - throw new Error('invalid data'); - } - } -}; - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(13); -var assert = __webpack_require__(26); - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports) { - -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} - -module.exports = noop; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - -const getRandomId = __webpack_require__(412) -const extend = __webpack_require__(67) - -module.exports = createPayload - - -function createPayload(data){ - return extend({ - // defaults - id: getRandomId(), - jsonrpc: '2.0', - params: [], - // user-specified - }, data) -} - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - -// optional / simple context binding -var aFunction = __webpack_require__(52); -module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; -}; - - -/***/ }), -/* 52 */ -/***/ (function(module, exports) { - -module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; -}; - - -/***/ }), -/* 53 */ -/***/ (function(module, exports) { - -module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; -}; - - -/***/ }), -/* 54 */ -/***/ (function(module, exports) { - -var id = 0; -var px = Math.random(); -module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; - - -/***/ }), -/* 55 */ -/***/ (function(module, exports) { - -exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var $at = __webpack_require__(192)(true); - -// 21.1.3.27 String.prototype[@@iterator]() -__webpack_require__(111)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index -// 21.1.5.2.1 %StringIteratorPrototype%.next() -}, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; -}); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - -var def = __webpack_require__(19).f; -var has = __webpack_require__(22); -var TAG = __webpack_require__(7)('toStringTag'); - -module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); -}; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - -__webpack_require__(196); -var global = __webpack_require__(6); -var hide = __webpack_require__(18); -var Iterators = __webpack_require__(30); -var TO_STRING_TAG = __webpack_require__(7)('toStringTag'); - -var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' + - 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' + - 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' + - 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' + - 'TextTrackList,TouchList').split(','); - -for (var i = 0; i < DOMIterables.length; i++) { - var NAME = DOMIterables[i]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = Iterators.Array; -} - - -/***/ }), -/* 59 */ -/***/ (function(module, exports) { - -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; - - -/***/ }), -/* 60 */ -/***/ (function(module, exports) { - -/** - * Compiles a querystring - * Returns string representation of the object - * - * @param {Object} - * @api private - */ - -exports.encode = function (obj) { - var str = ''; - - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - if (str.length) str += '&'; - str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); - } - } - - return str; -}; - -/** - * Parses a simple querystring into an object - * - * @param {String} qs - * @api private - */ - -exports.decode = function(qs){ - var qry = {}; - var pairs = qs.split('&'); - for (var i = 0, l = pairs.length; i < l; i++) { - var pair = pairs[i].split('='); - qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); - } - return qry; -}; - - -/***/ }), -/* 61 */ -/***/ (function(module, exports) { - - -module.exports = function(a, b){ - var fn = function(){}; - fn.prototype = b.prototype; - a.prototype = new fn; - a.prototype.constructor = a; -}; - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - -// based on the aes implimentation in triple sec -// https://github.com/keybase/triplesec -// which is in turn based on the one from crypto-js -// https://code.google.com/p/crypto-js/ - -var Buffer = __webpack_require__(0).Buffer - -function asUInt32Array (buf) { - if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) - - var len = (buf.length / 4) | 0 - var out = new Array(len) - - for (var i = 0; i < len; i++) { - out[i] = buf.readUInt32BE(i * 4) - } - - return out -} - -function scrubVec (v) { - for (var i = 0; i < v.length; v++) { - v[i] = 0 - } -} - -function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { - var SUB_MIX0 = SUB_MIX[0] - var SUB_MIX1 = SUB_MIX[1] - var SUB_MIX2 = SUB_MIX[2] - var SUB_MIX3 = SUB_MIX[3] - - var s0 = M[0] ^ keySchedule[0] - var s1 = M[1] ^ keySchedule[1] - var s2 = M[2] ^ keySchedule[2] - var s3 = M[3] ^ keySchedule[3] - var t0, t1, t2, t3 - var ksRow = 4 - - for (var round = 1; round < nRounds; round++) { - t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] - t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] - t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] - t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] - s0 = t0 - s1 = t1 - s2 = t2 - s3 = t3 - } - - t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] - t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] - t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] - t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] - t0 = t0 >>> 0 - t1 = t1 >>> 0 - t2 = t2 >>> 0 - t3 = t3 >>> 0 - - return [t0, t1, t2, t3] -} - -// AES constants -var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] -var G = (function () { - // Compute double table - var d = new Array(256) - for (var j = 0; j < 256; j++) { - if (j < 128) { - d[j] = j << 1 - } else { - d[j] = (j << 1) ^ 0x11b - } - } - - var SBOX = [] - var INV_SBOX = [] - var SUB_MIX = [[], [], [], []] - var INV_SUB_MIX = [[], [], [], []] - - // 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 - 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 - - if (x === 0) { - x = xi = 1 - } else { - x = x2 ^ d[d[d[x8 ^ x2]]] - xi ^= d[d[xi]] - } - } - - return { - SBOX: SBOX, - INV_SBOX: INV_SBOX, - SUB_MIX: SUB_MIX, - INV_SUB_MIX: INV_SUB_MIX - } -})() - -function AES (key) { - this._key = asUInt32Array(key) - this._reset() -} - -AES.blockSize = 4 * 4 -AES.keySize = 256 / 8 -AES.prototype.blockSize = AES.blockSize -AES.prototype.keySize = AES.keySize -AES.prototype._reset = function () { - var keyWords = this._key - var keySize = keyWords.length - var nRounds = keySize + 6 - var ksRows = (nRounds + 1) * 4 - - var keySchedule = [] - for (var k = 0; k < keySize; k++) { - keySchedule[k] = keyWords[k] - } - - for (k = keySize; k < ksRows; k++) { - var t = keySchedule[k - 1] - - if (k % keySize === 0) { - t = (t << 8) | (t >>> 24) - t = - (G.SBOX[t >>> 24] << 24) | - (G.SBOX[(t >>> 16) & 0xff] << 16) | - (G.SBOX[(t >>> 8) & 0xff] << 8) | - (G.SBOX[t & 0xff]) - - t ^= RCON[(k / keySize) | 0] << 24 - } else if (keySize > 6 && k % keySize === 4) { - t = - (G.SBOX[t >>> 24] << 24) | - (G.SBOX[(t >>> 16) & 0xff] << 16) | - (G.SBOX[(t >>> 8) & 0xff] << 8) | - (G.SBOX[t & 0xff]) - } - - keySchedule[k] = keySchedule[k - keySize] ^ t - } - - var invKeySchedule = [] - for (var ik = 0; ik < ksRows; ik++) { - var ksR = ksRows - ik - var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] - - if (ik < 4 || ksR <= 4) { - invKeySchedule[ik] = tt - } else { - invKeySchedule[ik] = - G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ - G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ - G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ - G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] - } - } - - this._nRounds = nRounds - this._keySchedule = keySchedule - this._invKeySchedule = invKeySchedule -} - -AES.prototype.encryptBlockRaw = function (M) { - M = asUInt32Array(M) - return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) -} - -AES.prototype.encryptBlock = function (M) { - var out = this.encryptBlockRaw(M) - var buf = Buffer.allocUnsafe(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[1], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[3], 12) - return buf -} - -AES.prototype.decryptBlock = function (M) { - M = asUInt32Array(M) - - // swap - var m1 = M[1] - M[1] = M[3] - M[3] = m1 - - var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) - var buf = Buffer.allocUnsafe(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[3], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[1], 12) - return buf -} - -AES.prototype.scrub = function () { - scrubVec(this._keySchedule) - scrubVec(this._invKeySchedule) - scrubVec(this._key) -} - -module.exports.AES = AES - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - -// 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 = __webpack_require__(12).EventEmitter; -var inherits = __webpack_require__(1); - -inherits(Stream, EE); -Stream.Readable = __webpack_require__(89); -Stream.Writable = __webpack_require__(270); -Stream.Duplex = __webpack_require__(271); -Stream.Transform = __webpack_require__(272); -Stream.PassThrough = __webpack_require__(273); - -// 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; -}; - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process -} - -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} - - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11))) - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - -var ecurve = __webpack_require__(93); -var Point = ecurve.Point; -var secp256k1 = ecurve.getCurveByName('secp256k1'); -var BigInteger = __webpack_require__(16); -var assert = __webpack_require__(4); - -var hash = __webpack_require__(25); -var PublicKey = __webpack_require__(44); -var keyUtils = __webpack_require__(46); -var createHash = __webpack_require__(45); -var promiseAsync = __webpack_require__(290); - -var G = secp256k1.G; -var n = secp256k1.n; - -module.exports = PrivateKey; - -/** - @typedef {string} wif - https://en.bitcoin.it/wiki/Wallet_import_format - @typedef {string} pubkey - EOSKey.. - @typedef {ecurve.Point} Point -*/ - -/** - @param {BigInteger} d -*/ -function PrivateKey(d) { - if (typeof d === 'string') { - return PrivateKey.fromString(d); - } else if (Buffer.isBuffer(d)) { - return PrivateKey.fromBuffer(d); - } else if ((typeof d === 'undefined' ? 'undefined' : _typeof(d)) === 'object' && BigInteger.isBigInteger(d.d)) { - return PrivateKey(d.d); - } - - if (!BigInteger.isBigInteger(d)) { - throw new TypeError('Invalid private key'); - } - - /** @return {string} private key like PVT_K1_base58privatekey.. */ - function toString() { - // todo, use PVT_K1_ - // return 'PVT_K1_' + keyUtils.checkEncode(toBuffer(), 'K1') - return toWif(); - } - - /** - @return {wif} - */ - function toWif() { - var private_key = toBuffer(); - // checksum includes the version - private_key = Buffer.concat([new Buffer([0x80]), private_key]); - return keyUtils.checkEncode(private_key, 'sha256x2'); - } - - var public_key = void 0; - - /** - @return {Point} - */ - function toPublic() { - if (public_key) { - // cache - // S L O W in the browser - return public_key; - } - var Q = secp256k1.G.multiply(d); - return public_key = PublicKey.fromPoint(Q); - } - - function toBuffer() { - return d.toBuffer(32); - } - - /** - ECIES - @arg {string|Object} pubkey wif, PublicKey object - @return {Buffer} 64 byte shared secret - */ - function getSharedSecret(public_key) { - public_key = PublicKey(public_key); - var KB = public_key.toUncompressed().toBuffer(); - var KBP = Point.fromAffine(secp256k1, BigInteger.fromBuffer(KB.slice(1, 33)), // x - BigInteger.fromBuffer(KB.slice(33, 65)) // y - ); - var r = toBuffer(); - var P = KBP.multiply(BigInteger.fromBuffer(r)); - var S = P.affineX.toBuffer({ size: 32 }); - // SHA512 used in ECIES - return hash.sha512(S); - } - - // /** ECIES TODO unit test - // @arg {string|Object} pubkey wif, PublicKey object - // @return {Buffer} 64 byte shared secret - // */ - // function getSharedSecret(public_key) { - // public_key = PublicKey(public_key).toUncompressed() - // var P = public_key.Q.multiply( d ); - // var S = P.affineX.toBuffer({size: 32}); - // // ECIES, adds an extra sha512 - // return hash.sha512(S); - // } - - /** - @arg {string} name - child key name. - @return {PrivateKey} - @example activePrivate = masterPrivate.getChildKey('owner').getChildKey('active') - @example activePrivate.getChildKey('mycontract').getChildKey('myperm') - */ - function getChildKey(name) { - // console.error('WARNING: getChildKey untested against eosd'); // no eosd impl yet - var index = createHash('sha256').update(toBuffer()).update(name).digest(); - return PrivateKey(index); - } - - function toHex() { - return toBuffer().toString('hex'); - } - - return { - d: d, - toWif: toWif, - toString: toString, - toPublic: toPublic, - toBuffer: toBuffer, - getSharedSecret: getSharedSecret, - getChildKey: getChildKey - }; -} - -/** @private */ -function parseKey(privateStr) { - assert.equal(typeof privateStr === 'undefined' ? 'undefined' : _typeof(privateStr), 'string', 'privateStr'); - var match = privateStr.match(/^PVT_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); - - if (match === null) { - // legacy WIF - checksum includes the version - var versionKey = keyUtils.checkDecode(privateStr, 'sha256x2'); - var version = versionKey.readUInt8(0); - assert.equal(0x80, version, 'Expected version ' + 0x80 + ', instead got ' + version); - var _privateKey = PrivateKey.fromBuffer(versionKey.slice(1)); - var _keyType = 'K1'; - var format = 'WIF'; - return { privateKey: _privateKey, format: format, keyType: _keyType }; - } - - assert(match.length === 3, 'Expecting private key like: PVT_K1_base58privateKey..'); - - var _match = _slicedToArray(match, 3), - keyType = _match[1], - keyString = _match[2]; - - assert.equal(keyType, 'K1', 'K1 private key expected'); - var privateKey = PrivateKey.fromBuffer(keyUtils.checkDecode(keyString, keyType)); - return { privateKey: privateKey, format: 'PVT', keyType: keyType }; -} - -PrivateKey.fromHex = function (hex) { - return PrivateKey.fromBuffer(new Buffer(hex, 'hex')); -}; - -PrivateKey.fromBuffer = function (buf) { - if (!Buffer.isBuffer(buf)) { - throw new Error("Expecting parameter to be a Buffer type"); - } - if (buf.length === 33 && buf[32] === 1) { - // remove compression flag - buf = buf.slice(0, -1); - } - if (32 !== buf.length) { - throw new Error('Expecting 32 bytes, instead got ' + buf.length); - } - return PrivateKey(BigInteger.fromBuffer(buf)); -}; - -/** - @arg {string} seed - any length string. This is private, the same seed - produces the same private key every time. - - @return {PrivateKey} -*/ -PrivateKey.fromSeed = function (seed) { - // generate_private_key - if (!(typeof seed === 'string')) { - throw new Error('seed must be of type string'); - } - return PrivateKey.fromBuffer(hash.sha256(seed)); -}; - -/** - @arg {wif} key - @return {boolean} true if key is in the Wallet Import Format -*/ -PrivateKey.isWif = function (text) { - try { - assert(parseKey(text).format === 'WIF'); - return true; - } catch (e) { - return false; - } -}; - -/** - @arg {wif|Buffer|PrivateKey} key - @return {boolean} true if key is convertable to a private key object. -*/ -PrivateKey.isValid = function (key) { - try { - PrivateKey(key); - return true; - } catch (e) { - return false; - } -}; - -/** @deprecated */ -PrivateKey.fromWif = function (str) { - console.log('PrivateKey.fromWif is deprecated, please use PrivateKey.fromString'); - return PrivateKey.fromString(str); -}; - -/** - @throws {AssertError|Error} parsing key - @arg {string} privateStr Eosio or Wallet Import Format (wif) -- a secret -*/ -PrivateKey.fromString = function (privateStr) { - return parseKey(privateStr).privateKey; -}; - -/** - Create a new random private key. - - Call initialize() first to run some self-checking code and gather some CPU - entropy. - - @arg {number} [cpuEntropyBits = 0] - additional CPU entropy, this already - happens once so it should not be needed again. - - @return {Promise} - random private key -*/ -PrivateKey.randomKey = function () { - var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - - return PrivateKey.initialize().then(function () { - return PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ cpuEntropyBits: cpuEntropyBits })); - }); -}; - -/** - @return {Promise} for testing, does not require initialize(). -*/ -PrivateKey.unsafeRandomKey = function () { - return Promise.resolve(PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ safe: false }))); -}; - -var initialized = false, - unitTested = false; - -/** - Run self-checking code and gather CPU entropy. - - Initialization happens once even if called multiple times. - - @return {Promise} -*/ -function initialize() { - if (initialized) { - return; - } - - unitTest(); - keyUtils.addEntropy.apply(keyUtils, _toConsumableArray(keyUtils.cpuEntropy())); - assert(keyUtils.entropyCount() >= 128, 'insufficient entropy'); - - initialized = true; -} - -PrivateKey.initialize = promiseAsync(initialize); - -/** - Unit test basic private and public key functionality. - - @throws {AssertError} -*/ -function unitTest() { - var pvt = PrivateKey(hash.sha256('')); - - var pvtError = 'key comparison test failed on a known private key'; - assert.equal(pvt.toWif(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError); - assert.equal(pvt.toString(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError); - // assert.equal(pvt.toString(), 'PVT_K1_2jH3nnhxhR3zPUcsKaWWZC9ZmZAnKm3GAnFD1xynGJE1Znuvjd', pvtError) - - var pub = pvt.toPublic(); - var pubError = 'pubkey string comparison test failed on a known public key'; - assert.equal(pub.toString(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError); - // assert.equal(pub.toString(), 'PUB_K1_859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2Ht7beeX', pubError) - // assert.equal(pub.toStringLegacy(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError) - - doesNotThrow(function () { - return PrivateKey.fromString(pvt.toWif()); - }, 'converting known wif from string'); - doesNotThrow(function () { - return PrivateKey.fromString(pvt.toString()); - }, 'converting known pvt from string'); - doesNotThrow(function () { - return PublicKey.fromString(pub.toString()); - }, 'converting known public key from string'); - // doesNotThrow(() => PublicKey.fromString(pub.toStringLegacy()), 'converting known public key from string') - - unitTested = true; -} - -/** @private */ -var doesNotThrow = function doesNotThrow(cb, msg) { - try { - cb(); - } catch (error) { - error.message = msg + ' ==> ' + error.message; - throw error; - } -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var curve = exports; - -curve.base = __webpack_require__(349); -curve.short = __webpack_require__(350); -curve.mont = __webpack_require__(351); -curve.edwards = __webpack_require__(352); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports) { - -module.exports = extend - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -function extend() { - var target = {} - - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] - - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - -var isFunction = __webpack_require__(377), - isLength = __webpack_require__(177); - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -module.exports = isArrayLike; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = slice; -function slice(arrayLike, start) { - start = start | 0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for (var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} -module.exports = exports["default"]; - -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { - -var isObject = __webpack_require__(20); -var document = __webpack_require__(6).document; -// typeof document.createElement is 'object' in old IE -var is = isObject(document) && isObject(document.createElement); -module.exports = function (it) { - return is ? document.createElement(it) : {}; -}; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - -// 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = __webpack_require__(20); -// instead of the ES6 spec version, we didn't implement @@toPrimitive case -// and the second argument - flag - preferred type is a string -module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); -}; - - -/***/ }), -/* 72 */ -/***/ (function(module, exports) { - -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; -}; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports) { - -// 7.1.4 ToInteger -var ceil = Math.ceil; -var floor = Math.floor; -module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - -var shared = __webpack_require__(75)('keys'); -var uid = __webpack_require__(54); -module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); -}; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -var core = __webpack_require__(5); -var global = __webpack_require__(6); -var SHARED = '__core-js_shared__'; -var store = global[SHARED] || (global[SHARED] = {}); - -(module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); -})('versions', []).push({ - version: core.version, - mode: __webpack_require__(38) ? 'pure' : 'global', - copyright: '© 2018 Denis Pushkarev (zloirock.ru)' -}); - - -/***/ }), -/* 76 */ -/***/ (function(module, exports) { - -// IE 8- don't enum bug keys -module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' -).split(','); - - -/***/ }), -/* 77 */ -/***/ (function(module, exports) { - -exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - -// 7.1.13 ToObject(argument) -var defined = __webpack_require__(72); -module.exports = function (it) { - return Object(defined(it)); -}; - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - -// getting tag from 19.1.3.6 Object.prototype.toString() -var cof = __webpack_require__(37); -var TAG = __webpack_require__(7)('toStringTag'); -// ES3 wrong here -var ARG = cof(function () { return arguments; }()) == 'Arguments'; - -// fallback for IE11 Script Access Denied error -var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } -}; - -module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// 25.4.1.5 NewPromiseCapability(C) -var aFunction = __webpack_require__(52); - -function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); -} - -module.exports.f = function (C) { - return new PromiseCapability(C); -}; - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _assign = __webpack_require__(35); - -var _assign2 = _interopRequireDefault(_assign); - -var _promise = __webpack_require__(39); - -var _promise2 = _interopRequireDefault(_promise); - -var _asyncToGenerator2 = __webpack_require__(40); - -var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); - -var _socket = __webpack_require__(212); - -var _socket2 = _interopRequireDefault(_socket); - -var _StorageService = __webpack_require__(235); - -var _StorageService2 = _interopRequireDefault(_StorageService); - -var _getRandomValues = __webpack_require__(236); - -var _getRandomValues2 = _interopRequireDefault(_getRandomValues); - -var _eosjs = __webpack_require__(238); - -var _eosjs2 = _interopRequireDefault(_eosjs); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const { ecc } = _eosjs2.default.modules; - -const host = 'http://127.0.0.1:50005'; - -let socket = null; -let connected = false; -let paired = false; - -let plugin; -let openRequests = []; - -let allowReconnects = true; -let reconnectionTimeout = null; - -const reconnectOnAbnormalDisconnection = (() => { - var _ref = (0, _asyncToGenerator3.default)(function* () { - if (!allowReconnects) return; - - clearTimeout(reconnectionTimeout); - reconnectionTimeout = setTimeout(function () { - SocketService.link(); - }, 1000); - }); - - return function reconnectOnAbnormalDisconnection() { - return _ref.apply(this, arguments); - }; -})(); - -const random = () => { - const array = new Uint8Array(24); - (0, _getRandomValues2.default)(array); - return array.join(''); -}; - -const getOrigin = () => { - let origin; - if (typeof location !== 'undefined') { - if (location.hasOwnProperty('hostname') && location.hostname.length && location.hostname !== 'localhost') origin = location.hostname;else origin = plugin; - } else origin = plugin; - return origin; -}; - -// StorageService.removeAppKey(); -// StorageService.removeNonce(); - -let appkey = _StorageService2.default.getAppKey(); -if (!appkey) appkey = 'appkey:' + random(); - -let pairingPromise = null; -const pair = (passthrough = false) => { - return new _promise2.default((resolve, reject) => { - pairingPromise = { resolve, reject }; - socket.emit('pair', { data: { appkey, origin: getOrigin(), passthrough }, plugin }); - }); -}; - -class SocketService { - - static init(_plugin, timeout = 60000) { - plugin = _plugin; - this.timeout = timeout; - } - - static link() { - var _this = this; - - return (0, _asyncToGenerator3.default)(function* () { - - return _promise2.default.race([new _promise2.default(function (resolve, reject) { - return setTimeout((0, _asyncToGenerator3.default)(function* () { - if (connected) return; - resolve(false); - - if (socket) { - socket.disconnect(); - socket = null; - } - - reconnectOnAbnormalDisconnection(); - }), _this.timeout); - }), new _promise2.default((() => { - var _ref3 = (0, _asyncToGenerator3.default)(function* (resolve, reject) { - socket = _socket2.default.connect(`${host}/scatter`, { secure: true, reconnection: false, rejectUnauthorized: false }); - - socket.on('connected', (0, _asyncToGenerator3.default)(function* () { - clearTimeout(reconnectionTimeout); - connected = true; - yield pair(true); - resolve(true); - })); - - socket.on('paired', (() => { - var _ref5 = (0, _asyncToGenerator3.default)(function* (result) { - paired = result; - - if (paired) { - const savedKey = _StorageService2.default.getAppKey(); - const hashed = appkey.indexOf('appkey:') > -1 ? ecc.sha256(appkey) : appkey; - - if (!savedKey || savedKey !== hashed) { - _StorageService2.default.setAppKey(hashed); - appkey = _StorageService2.default.getAppKey(); - } - } - - pairingPromise.resolve(result); - }); - - return function (_x3) { - return _ref5.apply(this, arguments); - }; - })()); - - socket.on('rekey', (0, _asyncToGenerator3.default)(function* () { - appkey = 'appkey:' + random(); - socket.emit('rekeyed', { data: { appkey, origin: getOrigin() }, plugin }); - })); - - socket.on('event', function (event) { - console.log('event', event); - }); - - socket.on('api', function (result) { - const openRequest = openRequests.find(function (x) { - return x.id === result.id; - }); - if (!openRequest) return; - if (typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result);else openRequest.resolve(result.result); - }); - - socket.on('disconnect', (0, _asyncToGenerator3.default)(function* () { - console.log('Disconnected'); - connected = false; - socket = null; - - // If bad disconnect, retry connection - reconnectOnAbnormalDisconnection(); - })); - - socket.on('connect_error', (0, _asyncToGenerator3.default)(function* () { - allowReconnects = false; - resolve(false); - })); - - socket.on('rejected', (() => { - var _ref9 = (0, _asyncToGenerator3.default)(function* (reason) { - console.error('reason', reason); - reject(reason); - }); - - return function (_x4) { - return _ref9.apply(this, arguments); - }; - })()); - }); - - return function (_x, _x2) { - return _ref3.apply(this, arguments); - }; - })())]); - })(); - } - - static isConnected() { - return connected; - } - - static disconnect() { - return (0, _asyncToGenerator3.default)(function* () { - socket.disconnect(); - return true; - })(); - } - - static sendApiRequest(request) { - return (0, _asyncToGenerator3.default)(function* () { - return new _promise2.default((() => { - var _ref10 = (0, _asyncToGenerator3.default)(function* (resolve, reject) { - if (request.type === 'identityFromPermissions' && !paired) return resolve(false); - - yield pair(); - if (!paired) return reject({ code: 'not_paired', message: 'The user did not allow this app to connect to their Scatter' }); - - // Request ID used for resolving promises - request.id = random(); - - // Set Application Key - request.appkey = appkey; - - // Nonce used to authenticate this request - request.nonce = _StorageService2.default.getNonce() || 0; - // Next nonce used to authenticate the next request - const nextNonce = random(); - request.nextNonce = ecc.sha256(nextNonce); - _StorageService2.default.setNonce(nextNonce); - - if (request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) request.payload.origin = getOrigin(); - - openRequests.push((0, _assign2.default)(request, { resolve, reject })); - socket.emit('api', { data: request, plugin }); - }); - - return function (_x5, _x6) { - return _ref10.apply(this, arguments); - }; - })()); - })(); - } - -} -exports.default = SocketService; - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var debug = __webpack_require__(15)('socket.io-parser'); -var Emitter = __webpack_require__(31); -var binary = __webpack_require__(216); -var isArray = __webpack_require__(83); -var isBuf = __webpack_require__(121); - -/** - * Protocol version. - * - * @api public - */ - -exports.protocol = 4; - -/** - * Packet types. - * - * @api public - */ - -exports.types = [ - 'CONNECT', - 'DISCONNECT', - 'EVENT', - 'ACK', - 'ERROR', - 'BINARY_EVENT', - 'BINARY_ACK' -]; - -/** - * Packet type `connect`. - * - * @api public - */ - -exports.CONNECT = 0; - -/** - * Packet type `disconnect`. - * - * @api public - */ - -exports.DISCONNECT = 1; - -/** - * Packet type `event`. - * - * @api public - */ - -exports.EVENT = 2; - -/** - * Packet type `ack`. - * - * @api public - */ - -exports.ACK = 3; - -/** - * Packet type `error`. - * - * @api public - */ - -exports.ERROR = 4; - -/** - * Packet type 'binary event' - * - * @api public - */ - -exports.BINARY_EVENT = 5; - -/** - * Packet type `binary ack`. For acks with binary arguments. - * - * @api public - */ - -exports.BINARY_ACK = 6; - -/** - * Encoder constructor. - * - * @api public - */ - -exports.Encoder = Encoder; - -/** - * Decoder constructor. - * - * @api public - */ - -exports.Decoder = Decoder; - -/** - * A socket.io Encoder instance - * - * @api public - */ - -function Encoder() {} - -var ERROR_PACKET = exports.ERROR + '"encode error"'; - -/** - * Encode a packet as a single string if non-binary, or as a - * buffer sequence, depending on packet type. - * - * @param {Object} obj - packet object - * @param {Function} callback - function to handle encodings (likely engine.write) - * @return Calls callback with Array of encodings - * @api public - */ - -Encoder.prototype.encode = function(obj, callback){ - debug('encoding packet %j', obj); - - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - encodeAsBinary(obj, callback); - } else { - var encoding = encodeAsString(obj); - callback([encoding]); - } -}; - -/** - * Encode packet as string. - * - * @param {Object} packet - * @return {String} encoded - * @api private - */ - -function encodeAsString(obj) { - - // first is type - var str = '' + obj.type; - - // attachments if we have them - if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { - str += obj.attachments + '-'; - } - - // if we have a namespace other than `/` - // we append it followed by a comma `,` - if (obj.nsp && '/' !== obj.nsp) { - str += obj.nsp + ','; - } - - // immediately followed by the id - if (null != obj.id) { - str += obj.id; - } - - // json data - if (null != obj.data) { - var payload = tryStringify(obj.data); - if (payload !== false) { - str += payload; - } else { - return ERROR_PACKET; - } - } - - debug('encoded %j as %s', obj, str); - return str; -} - -function tryStringify(str) { - try { - return JSON.stringify(str); - } catch(e){ - return false; - } -} - -/** - * Encode packet as 'buffer sequence' by removing blobs, and - * deconstructing packet into object with placeholders and - * a list of buffers. - * - * @param {Object} packet - * @return {Buffer} encoded - * @api private - */ - -function encodeAsBinary(obj, callback) { - - function writeEncoding(bloblessData) { - var deconstruction = binary.deconstructPacket(bloblessData); - var pack = encodeAsString(deconstruction.packet); - var buffers = deconstruction.buffers; - - buffers.unshift(pack); // add packet info to beginning of data list - callback(buffers); // write all the buffers - } - - binary.removeBlobs(obj, writeEncoding); -} - -/** - * A socket.io Decoder instance - * - * @return {Object} decoder - * @api public - */ - -function Decoder() { - this.reconstructor = null; -} - -/** - * Mix in `Emitter` with Decoder. - */ - -Emitter(Decoder.prototype); - -/** - * Decodes an ecoded packet string into packet JSON. - * - * @param {String} obj - encoded packet - * @return {Object} packet - * @api public - */ - -Decoder.prototype.add = function(obj) { - var packet; - if (typeof obj === 'string') { - packet = decodeString(obj); - if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json - this.reconstructor = new BinaryReconstructor(packet); - - // no attachments, labeled binary but no binary data to follow - if (this.reconstructor.reconPack.attachments === 0) { - this.emit('decoded', packet); - } - } else { // non-binary full packet - this.emit('decoded', packet); - } - } - else if (isBuf(obj) || obj.base64) { // raw binary data - if (!this.reconstructor) { - throw new Error('got binary data when not reconstructing a packet'); - } else { - packet = this.reconstructor.takeBinaryData(obj); - if (packet) { // received final buffer - this.reconstructor = null; - this.emit('decoded', packet); - } - } - } - else { - throw new Error('Unknown type: ' + obj); - } -}; - -/** - * Decode a packet String (JSON data) - * - * @param {String} str - * @return {Object} packet - * @api private - */ - -function decodeString(str) { - var i = 0; - // look up type - var p = { - type: Number(str.charAt(0)) - }; - - if (null == exports.types[p.type]) { - return error('unknown packet type ' + p.type); - } - - // look up attachments if type binary - if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { - var buf = ''; - while (str.charAt(++i) !== '-') { - buf += str.charAt(i); - if (i == str.length) break; - } - if (buf != Number(buf) || str.charAt(i) !== '-') { - throw new Error('Illegal attachments'); - } - p.attachments = Number(buf); - } - - // look up namespace (if any) - if ('/' === str.charAt(i + 1)) { - p.nsp = ''; - while (++i) { - var c = str.charAt(i); - if (',' === c) break; - p.nsp += c; - if (i === str.length) break; - } - } else { - p.nsp = '/'; - } - - // look up id - var next = str.charAt(i + 1); - if ('' !== next && Number(next) == next) { - p.id = ''; - while (++i) { - var c = str.charAt(i); - if (null == c || Number(c) != c) { - --i; - break; - } - p.id += str.charAt(i); - if (i === str.length) break; - } - p.id = Number(p.id); - } - - // look up json data - if (str.charAt(++i)) { - var payload = tryParse(str.substr(i)); - var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload)); - if (isPayloadValid) { - p.data = payload; - } else { - return error('invalid payload'); - } - } - - debug('decoded %s as %j', str, p); - return p; -} - -function tryParse(str) { - try { - return JSON.parse(str); - } catch(e){ - return false; - } -} - -/** - * Deallocates a parser's resources - * - * @api public - */ - -Decoder.prototype.destroy = function() { - if (this.reconstructor) { - this.reconstructor.finishedReconstruction(); - } -}; - -/** - * A manager of a binary event's 'buffer sequence'. Should - * be constructed whenever a packet of type BINARY_EVENT is - * decoded. - * - * @param {Object} packet - * @return {BinaryReconstructor} initialized reconstructor - * @api private - */ - -function BinaryReconstructor(packet) { - this.reconPack = packet; - this.buffers = []; -} - -/** - * Method to be called when binary data received from connection - * after a BINARY_EVENT packet. - * - * @param {Buffer | ArrayBuffer} binData - the raw binary data received - * @return {null | Object} returns null if more binary data is expected or - * a reconstructed packet object if all buffers have been received. - * @api private - */ - -BinaryReconstructor.prototype.takeBinaryData = function(binData) { - this.buffers.push(binData); - if (this.buffers.length === this.reconPack.attachments) { // done with buffer list - var packet = binary.reconstructPacket(this.reconPack, this.buffers); - this.finishedReconstruction(); - return packet; - } - return null; -}; - -/** - * Cleans up binary packet reconstruction variables. - * - * @api private - */ - -BinaryReconstructor.prototype.finishedReconstruction = function() { - this.reconPack = null; - this.buffers = []; -}; - -function error(msg) { - return { - type: exports.ERROR, - data: 'parser error: ' + msg - }; -} - - -/***/ }), -/* 83 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {// browser shim for xmlhttprequest module - -var hasCORS = __webpack_require__(219); - -module.exports = function (opts) { - var xdomain = opts.xdomain; - - // scheme must be same when usign XDomainRequest - // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx - var xscheme = opts.xscheme; - - // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default. - // https://github.com/Automattic/engine.io-client/pull/217 - var enablesXDR = opts.enablesXDR; - - // XMLHttpRequest can be disabled on IE - try { - if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { - return new XMLHttpRequest(); - } - } catch (e) { } - - // Use XDomainRequest for IE8 if enablesXDR is true - // because loading bar keeps flashing when using jsonp-polling - // https://github.com/yujiosaka/socke.io-ie8-loading-example - try { - if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) { - return new XDomainRequest(); - } - } catch (e) { } - - if (!xdomain) { - try { - return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP'); - } catch (e) { } - } -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Module dependencies. - */ - -var parser = __webpack_require__(32); -var Emitter = __webpack_require__(31); - -/** - * Module exports. - */ - -module.exports = Transport; - -/** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ - -function Transport (opts) { - this.path = opts.path; - this.hostname = opts.hostname; - this.port = opts.port; - this.secure = opts.secure; - this.query = opts.query; - this.timestampParam = opts.timestampParam; - this.timestampRequests = opts.timestampRequests; - this.readyState = ''; - this.agent = opts.agent || false; - this.socket = opts.socket; - this.enablesXDR = opts.enablesXDR; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - this.forceNode = opts.forceNode; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - this.localAddress = opts.localAddress; -} - -/** - * Mix in `Emitter`. - */ - -Emitter(Transport.prototype); - -/** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ - -Transport.prototype.onError = function (msg, desc) { - var err = new Error(msg); - err.type = 'TransportError'; - err.description = desc; - this.emit('error', err); - return this; -}; - -/** - * Opens the transport. - * - * @api public - */ - -Transport.prototype.open = function () { - if ('closed' === this.readyState || '' === this.readyState) { - this.readyState = 'opening'; - this.doOpen(); - } - - return this; -}; - -/** - * Closes the transport. - * - * @api private - */ - -Transport.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.doClose(); - this.onClose(); - } - - return this; -}; - -/** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ - -Transport.prototype.send = function (packets) { - if ('open' === this.readyState) { - this.write(packets); - } else { - throw new Error('Transport not open'); - } -}; - -/** - * Called upon open - * - * @api private - */ - -Transport.prototype.onOpen = function () { - this.readyState = 'open'; - this.writable = true; - this.emit('open'); -}; - -/** - * Called with data. - * - * @param {String} data - * @api private - */ - -Transport.prototype.onData = function (data) { - var packet = parser.decodePacket(data, this.socket.binaryType); - this.onPacket(packet); -}; - -/** - * Called with a decoded packet. - */ - -Transport.prototype.onPacket = function (packet) { - this.emit('packet', packet); -}; - -/** - * Called upon close. - * - * @api private - */ - -Transport.prototype.onClose = function () { - this.readyState = 'closed'; - this.emit('close'); -}; - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - -exports.f = __webpack_require__(7); - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var LIBRARY = __webpack_require__(38); -var wksExt = __webpack_require__(86); -var defineProperty = __webpack_require__(19).f; -module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); -}; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var commonApi = __webpack_require__(253); -var objectApi = __webpack_require__(293); - -var ecc = Object.assign({}, commonApi, objectApi); - -module.exports = ecc; - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - -exports = module.exports = __webpack_require__(141); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = __webpack_require__(90); -exports.Duplex = __webpack_require__(24); -exports.Transform = __webpack_require__(145); -exports.PassThrough = __webpack_require__(269); - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// 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. - - - -/**/ - -var pna = __webpack_require__(64); -/**/ - -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 asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = __webpack_require__(43); -util.inherits = __webpack_require__(1); -/**/ - -/**/ -var internalUtil = { - deprecate: __webpack_require__(268) -}; -/**/ - -/**/ -var Stream = __webpack_require__(142); -/**/ - -/**/ - -var Buffer = __webpack_require__(0).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 = __webpack_require__(143); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(24); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // 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; - - // 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 () { - 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 (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || __webpack_require__(24); - - // 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. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -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 () { - 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 (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', 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; - - 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); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(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 Error('_write() is not implemented')); -}; - -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 && !state.finished) endWritable(this, state, cb); -}; - -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) { - stream.emit('error', 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.pendingcb++; - state.finalCalled = true; - pna.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'); - } - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - 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; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (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) { - this.end(); - cb(err); -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11), __webpack_require__(144).setImmediate, __webpack_require__(3))) - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// 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. - - - -/**/ - -var Buffer = __webpack_require__(0).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) : ''; -} - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { -var inherits = __webpack_require__(1) -var HashBase = __webpack_require__(148) - -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 = new Buffer(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 - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - -var Point = __webpack_require__(149) -var Curve = __webpack_require__(151) - -var getCurveByName = __webpack_require__(279) - -module.exports = { - Curve: Curve, - Point: Point, - getCurveByName: getCurveByName -} - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var Types = __webpack_require__(294); -var Fcbuffer = __webpack_require__(297); -var assert = __webpack_require__(4); - -var create = Fcbuffer.create; - -/** - @typedef {object} SerializerConfig - @property {boolean} [SerializerConfig.defaults = false] - Insert in defaults (like 0, false, '000...', or '') for any missing values. This helps test and inspect what a definition should look like. Do not enable in production. - @property {boolean} [SerializerConfig.debug = false] - Prints lots of HEX and field-level information to help debug binary serialization. - @property {object} [customTypes] - Add or overwrite low level types (see ./src/types.js `const types = {...}`). -*/ - -/** - @typedef {object} CreateStruct - @property {Array} CreateStruct.errors - If any errors exists, no struts will be created. - @property {Object} CreateStruct.struct - Struct objects keyed by definition name. - @property {String} CreateStruct.struct.structName - Struct object that will serialize this type. - @property {Struct} CreateStruct.struct.struct - Struct object that will serialize this type (see ./src/struct.js). -*/ - -/** - @arg {object} definitions - examples https://github.com/EOSIO/eosjs-json/blob/master/schema - @arg {SerializerConfig} config - @return {CreateStruct} -*/ - -module.exports = function (definitions) { - var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if ((typeof definitions === 'undefined' ? 'undefined' : _typeof(definitions)) !== 'object') { - throw new TypeError('definitions is a required parameter'); - } - - if (config.customTypes) { - definitions = Object.assign({}, definitions); //clone - for (var key in config.customTypes) { - // custom types overwrite definitions - delete definitions[key]; - } - } - - var types = Types(config); - - var _create = create(definitions, types), - errors = _create.errors, - structs = _create.structs; - - /** Extend with more JSON schema and type definitions */ - - - var _extend = function _extend(parent, child) { - var combined = Object.assign({}, parent, child); - - var _create2 = create(combined, types), - structs = _create2.structs, - errors = _create2.errors; - - return { - errors: errors, - structs: structs, - extend: function extend(child) { - return _extend(combined, child); - }, - fromBuffer: fromBuffer(types, structs), - toBuffer: toBuffer(types, structs) - }; - }; - - return { - errors: errors, - structs: structs, - types: types, - extend: function extend(child) { - return _extend(definitions, child); - }, - - /** - @arg {string} typeName lookup struct or type by name - @arg {Buffer} buf serialized data to be parsed - @return {object} deserialized object - */ - fromBuffer: fromBuffer(types, structs), - - /** - @arg {string} typeName lookup struct or type by name - @arg {Object} object for serialization - @return {Buffer} serialized object - */ - toBuffer: toBuffer(types, structs) - }; -}; - -var fromBuffer = function fromBuffer(types, structs) { - return function (typeName, buf) { - assert.equal(typeof typeName === 'undefined' ? 'undefined' : _typeof(typeName), 'string', 'typeName (type or struct name)'); - if (typeof buf === 'string') { - buf = Buffer.from(buf, 'hex'); - } - assert(Buffer.isBuffer(buf), 'expecting buf'); - - var type = types[typeName]; - if (type) { - type = type(); - } else { - type = structs[typeName]; - } - assert(type, 'missing type or struct: ' + typeName); - return Fcbuffer.fromBuffer(type, buf); - }; -}; - -var toBuffer = function toBuffer(types, structs) { - return function (typeName, object) { - assert.equal(typeof typeName === 'undefined' ? 'undefined' : _typeof(typeName), 'string', 'typeName (type or struct name)'); - assert.equal(typeof object === 'undefined' ? 'undefined' : _typeof(object), 'object', 'object'); - - var type = types[typeName]; - if (type) { - type = type(); - } else { - type = structs[typeName]; - } - assert(type, 'missing type or struct: ' + typeName); - return Fcbuffer.toBuffer(type, object); - }; -}; - -module.exports.fromBuffer = Fcbuffer.fromBuffer; -module.exports.toBuffer = Fcbuffer.toBuffer; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _slicedToArray2 = __webpack_require__(96); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _typeof2 = __webpack_require__(41); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _require = __webpack_require__(88), - Signature = _require.Signature, - PublicKey = _require.PublicKey; - -var Fcbuffer = __webpack_require__(94); -var ByteBuffer = __webpack_require__(33); -var assert = __webpack_require__(4); - -var json = { schema: __webpack_require__(161) }; - -var _require2 = __webpack_require__(162), - isName = _require2.isName, - encodeName = _require2.encodeName, - decodeName = _require2.decodeName, - DecimalPad = _require2.DecimalPad, - DecimalImply = _require2.DecimalImply, - DecimalUnimply = _require2.DecimalUnimply, - printAsset = _require2.printAsset, - parseAsset = _require2.parseAsset; - -/** Configures Fcbuffer for EOS specific structs and types. */ - - -module.exports = function () { - var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var extendedSchema = arguments[1]; - - var structLookup = function structLookup(lookupName, account) { - var cachedCode = new Set(['eosio', 'eosio.token', 'eosio.null']); - if (cachedCode.has(account)) { - return structs[lookupName]; - } - var abi = config.abiCache.abi(account); - var struct = abi.structs[lookupName]; - if (struct != null) { - return struct; - } - // TODO: move up (before `const struct = abi.structs[lookupName]`) - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = abi.abi.actions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var action = _step.value; - var name = action.name, - type = action.type; - - if (name === lookupName) { - var _struct = abi.structs[type]; - if (_struct != null) { - return _struct; - } - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - throw new Error('Missing ABI struct or action: ' + lookupName); - }; - - // If nodeos does not have an ABI setup for a certain action.type, it will throw - // an error: `Invalid cast from object_type to string` .. forceActionDataHex - // may be used to until native ABI is added or fixed. - var forceActionDataHex = config.forceActionDataHex != null ? config.forceActionDataHex : true; - - var override = Object.assign({}, authorityOverride, abiOverride(structLookup), wasmCodeOverride(config), actionDataOverride(structLookup, forceActionDataHex), config.override); - - var eosTypes = { - name: function name() { - return [Name]; - }, - public_key: function public_key() { - return [variant(PublicKeyEcc)]; - }, - - symbol: function symbol() { - return [_Symbol]; - }, - symbol_code: function symbol_code() { - return [SymbolCode]; - }, - extended_symbol: function extended_symbol() { - return [ExtendedSymbol]; - }, - - asset: function asset() { - return [Asset]; - }, // After Symbol: amount, precision, symbol, contract - extended_asset: function extended_asset() { - return [ExtendedAsset]; - }, // After Asset: amount, precision, symbol, contract - - signature: function signature() { - return [variant(SignatureType)]; - } - }; - - var customTypes = Object.assign({}, eosTypes, config.customTypes); - config = Object.assign({ override: override }, { customTypes: customTypes }, config); - - // Do not sort transaction actions - config.sort = Object.assign({}, config.sort); - config.sort['action.authorization'] = true; - config.sort['signed_transaction.signature'] = true; - config.sort['authority.accounts'] = true; - config.sort['authority.keys'] = true; - - var schema = Object.assign({}, json.schema, extendedSchema); - - var _Fcbuffer = Fcbuffer(schema, config), - structs = _Fcbuffer.structs, - types = _Fcbuffer.types, - errors = _Fcbuffer.errors, - fromBuffer = _Fcbuffer.fromBuffer, - toBuffer = _Fcbuffer.toBuffer; - - if (errors.length !== 0) { - throw new Error(JSON.stringify(errors, null, 4)); - } - - return { structs: structs, types: types, fromBuffer: fromBuffer, toBuffer: toBuffer }; -}; - -/** - Name eos::types native.hpp -*/ -var Name = function Name(validation) { - return { - fromByteBuffer: function fromByteBuffer(b) { - var n = decodeName(b.readUint64(), false); // b is already in littleEndian - // if(validation.debug) { - // console.error(`${n}`, '(Name.fromByteBuffer)') - // } - return n; - }, - appendByteBuffer: function appendByteBuffer(b, value) { - // if(validation.debug) { - // console.error(`${value}`, (Name.appendByteBuffer)) - // } - b.writeUint64(encodeName(value, false)); // b is already in littleEndian - }, - fromObject: function fromObject(value) { - return value; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return ''; - } - return value; - } - }; -}; - -/** - A variant is like having a version of an object. A varint comes - first and identifies which type of object this is. - - @arg {Array} variantArray array of types -*/ -var variant = function variant() { - for (var _len = arguments.length, variantArray = Array(_len), _key = 0; _key < _len; _key++) { - variantArray[_key] = arguments[_key]; - } - - return function (validation, baseTypes, customTypes) { - var variants = variantArray.map(function (Type) { - return Type(validation, baseTypes, customTypes); - }); - var staticVariant = baseTypes.static_variant(variants); - - return { - fromByteBuffer: function fromByteBuffer(b) { - return staticVariant.fromByteBuffer(b); - }, - appendByteBuffer: function appendByteBuffer(b, value) { - if (!Array.isArray(value)) { - value = [0, value]; - } - staticVariant.appendByteBuffer(b, value); - }, - fromObject: function fromObject(value) { - if (!Array.isArray(value)) { - value = [0, value]; - } - return staticVariant.fromObject(value)[1]; - }, - toObject: function toObject(value) { - if (!Array.isArray(value)) { - value = [0, value]; - } - return staticVariant.toObject(value)[1]; - } - }; - }; -}; - -var PublicKeyEcc = function PublicKeyEcc(validation) { - return { - fromByteBuffer: function fromByteBuffer(b) { - var bcopy = b.copy(b.offset, b.offset + 33); - b.skip(33); - var pubbuf = Buffer.from(bcopy.toBinary(), 'binary'); - return PublicKey.fromBuffer(pubbuf).toString(); - }, - appendByteBuffer: function appendByteBuffer(b, value) { - // if(validation.debug) { - // console.error(`${value}`, 'PublicKeyType.appendByteBuffer') - // } - var buf = PublicKey.fromStringOrThrow(value).toBuffer(); - b.append(buf.toString('binary'), 'binary'); - }, - fromObject: function fromObject(value) { - return value; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return 'EOS6MRy..'; - } - return value; - } - }; -}; - -/** - Internal: precision, symbol - External: symbol - @example 'SYS' -*/ -var _Symbol = function _Symbol(validation) { - return { - fromByteBuffer: function fromByteBuffer(b) { - var bcopy = b.copy(b.offset, b.offset + 8); - b.skip(8); - - var precision = bcopy.readUint8(); - var bin = bcopy.toBinary(); - - var symbol = ''; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = bin[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var code = _step2.value; - - if (code == '\0') { - break; - } - symbol += code; - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - return precision + ',' + symbol; - }, - appendByteBuffer: function appendByteBuffer(b, value) { - var _parseAsset = parseAsset(value), - symbol = _parseAsset.symbol, - precision = _parseAsset.precision; - - assert(precision != null, 'Precision unknown for symbol: ' + value); - var pad = '\0'.repeat(7 - symbol.length); - b.append(String.fromCharCode(precision) + symbol + pad); - }, - fromObject: function fromObject(value) { - assert(value != null, 'Symbol is required: ' + value); - - var _parseAsset2 = parseAsset(value), - symbol = _parseAsset2.symbol, - precision = _parseAsset2.precision; - - if (precision == null) { - return symbol; - } else { - // Internal object, this can have the precision prefix - return precision + ',' + symbol; - } - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return 'SYS'; - } - // symbol only (without precision prefix) - return parseAsset(value).symbol; - } - }; -}; - -/** Symbol type without the precision */ -var SymbolCode = function SymbolCode(validation) { - return { - fromByteBuffer: function fromByteBuffer(b) { - var bcopy = b.copy(b.offset, b.offset + 8); - b.skip(8); - - var bin = bcopy.toBinary(); - - var symbol = ''; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = bin[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var code = _step3.value; - - if (code == '\0') { - break; - } - symbol += code; - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - return '' + symbol; - }, - appendByteBuffer: function appendByteBuffer(b, value) { - var _parseAsset3 = parseAsset(value), - symbol = _parseAsset3.symbol; - - var pad = '\0'.repeat(8 - symbol.length); - b.append(symbol + pad); - }, - fromObject: function fromObject(value) { - assert(value != null, 'Symbol is required: ' + value); - - var _parseAsset4 = parseAsset(value), - symbol = _parseAsset4.symbol; - - return symbol; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return 'SYS'; - } - return parseAsset(value).symbol; - } - }; -}; - -/** - Internal: precision, symbol, contract - External: symbol, contract - @example 'SYS@contract' -*/ -var ExtendedSymbol = function ExtendedSymbol(validation, baseTypes, customTypes) { - var symbolType = customTypes.symbol(validation); - var contractName = customTypes.name(validation); - - return { - fromByteBuffer: function fromByteBuffer(b) { - var symbol = symbolType.fromByteBuffer(b); - var contract = contractName.fromByteBuffer(b); - return symbol + '@' + contract; - }, - appendByteBuffer: function appendByteBuffer(b, value) { - assert.equal(typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value), 'string', 'Invalid extended symbol: ' + value); - - var _value$split = value.split('@'), - _value$split2 = (0, _slicedToArray3.default)(_value$split, 2), - symbol = _value$split2[0], - contract = _value$split2[1]; - - assert(contract != null, 'Missing @contract suffix in extended symbol: ' + value); - - symbolType.appendByteBuffer(b, symbol); - contractName.appendByteBuffer(b, contract); - }, - fromObject: function fromObject(value) { - return value; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return 'SYS@contract'; - } - return value; - } - }; -}; - -/** - Internal: amount, precision, symbol, contract - @example '1.0000 SYS' -*/ -var Asset = function Asset(validation, baseTypes, customTypes) { - var amountType = baseTypes.int64(validation); - var symbolType = customTypes.symbol(validation); - - return { - fromByteBuffer: function fromByteBuffer(b) { - var amount = amountType.fromByteBuffer(b); - assert(amount != null, 'amount'); - - var sym = symbolType.fromByteBuffer(b); - - var _parseAsset5 = parseAsset('' + sym), - precision = _parseAsset5.precision, - symbol = _parseAsset5.symbol; - - assert(precision != null, 'precision'); - assert(symbol != null, 'symbol'); - - return DecimalUnimply(amount, precision) + ' ' + symbol; - }, - appendByteBuffer: function appendByteBuffer(b, value) { - var _parseAsset6 = parseAsset(value), - amount = _parseAsset6.amount, - precision = _parseAsset6.precision, - symbol = _parseAsset6.symbol; - - assert(amount != null, 'amount'); - assert(precision != null, 'precision'); - assert(symbol != null, 'symbol'); - - amountType.appendByteBuffer(b, DecimalImply(amount, precision)); - symbolType.appendByteBuffer(b, precision + ',' + symbol); - }, - fromObject: function fromObject(value) { - var _parseAsset7 = parseAsset(value), - amount = _parseAsset7.amount, - precision = _parseAsset7.precision, - symbol = _parseAsset7.symbol; - - assert(amount != null, 'amount'); - assert(precision != null, 'precision'); - assert(symbol != null, 'symbol'); - - return DecimalPad(amount, precision) + ' ' + symbol; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return '0.0001 SYS'; - } - - var _parseAsset8 = parseAsset(value), - amount = _parseAsset8.amount, - precision = _parseAsset8.precision, - symbol = _parseAsset8.symbol; - - assert(amount != null, 'amount'); - assert(precision != null, 'precision'); - assert(symbol != null, 'symbol'); - - return DecimalPad(amount, precision) + ' ' + symbol; - } - }; -}; - -/** - @example '1.0000 SYS@contract' -*/ -var ExtendedAsset = function ExtendedAsset(validation, baseTypes, customTypes) { - var assetType = customTypes.asset(validation); - var contractName = customTypes.name(validation); - - return { - fromByteBuffer: function fromByteBuffer(b) { - var asset = assetType.fromByteBuffer(b); - var contract = contractName.fromByteBuffer(b); - return parseAsset(asset + '@' + contract); - }, - appendByteBuffer: function appendByteBuffer(b, value) { - assert.equal(typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value), 'object', 'expecting extended_asset object, got ' + (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value))); - - var asset = printAsset(value); - - var _asset$split = asset.split('@'), - _asset$split2 = (0, _slicedToArray3.default)(_asset$split, 2), - contract = _asset$split2[1]; - - assert.equal(typeof contract === 'undefined' ? 'undefined' : (0, _typeof3.default)(contract), 'string', 'Invalid extended asset: ' + value); - - // asset includes contract (assetType needs this) - assetType.appendByteBuffer(b, asset); - contractName.appendByteBuffer(b, contract); - }, - fromObject: function fromObject(value) { - // like: 1.0000 SYS@contract or 1 SYS@contract - var asset = {}; - if (typeof value === 'string') { - Object.assign(asset, parseAsset(value)); - } else if ((typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object') { - Object.assign(asset, value); - } else { - assert(false, 'expecting extended_asset, got: ' + (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value))); - } - - var amount = asset.amount, - precision = asset.precision, - symbol = asset.symbol, - contract = asset.contract; - - assert(amount != null, 'missing amount'); - assert(precision != null, 'missing precision'); - assert(symbol != null, 'missing symbol'); - assert(contract != null, 'missing contract'); - - return { amount: amount, precision: precision, symbol: symbol, contract: contract }; - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return { - amount: '1.0000', - precision: 4, - symbol: 'SYS', - contract: 'eosio.token' - }; - } - - assert.equal(typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value), 'object', 'expecting extended_asset object'); - var amount = value.amount, - precision = value.precision, - symbol = value.symbol, - contract = value.contract; - - - return { - amount: DecimalPad(amount, precision), - precision: precision, - symbol: symbol, - contract: contract - }; - } - }; -}; - -var SignatureType = function SignatureType(validation, baseTypes) { - var signatureType = baseTypes.fixed_bytes65(validation); - return { - fromByteBuffer: function fromByteBuffer(b) { - var signatureBuffer = signatureType.fromByteBuffer(b); - var signature = Signature.from(signatureBuffer); - return signature.toString(); - }, - appendByteBuffer: function appendByteBuffer(b, value) { - var signature = Signature.from(value); - signatureType.appendByteBuffer(b, signature.toBuffer()); - }, - fromObject: function fromObject(value) { - var signature = Signature.from(value); - return signature.toString(); - }, - toObject: function toObject(value) { - if (validation.defaults && value == null) { - return 'SIG_K1_bas58signature..'; - } - var signature = Signature.from(value); - return signature.toString(); - } - }; -}; - -var authorityOverride = { - /** shorthand `EOS6MRyAj..` */ - 'authority.fromObject': function authorityFromObject(value) { - if (PublicKey.fromString(value)) { - return { - threshold: 1, - keys: [{ key: value, weight: 1 }] - }; - } - if (typeof value === 'string') { - var _value$split3 = value.split('@'), - _value$split4 = (0, _slicedToArray3.default)(_value$split3, 2), - account = _value$split4[0], - _value$split4$ = _value$split4[1], - permission = _value$split4$ === undefined ? 'active' : _value$split4$; - - return { - threshold: 1, - accounts: [{ - permission: { - actor: account, - permission: permission - }, - weight: 1 - }] - }; - } - } -}; - -var abiOverride = function abiOverride(structLookup) { - return { - 'abi_def.fromObject': function abi_defFromObject(value) { - if (typeof value === 'string') { - var _json = Buffer.from(value, 'hex').toString(); - if (_json.length === 0) { - _json = Buffer.from(value).toString(); - } - return JSON.parse(_json); - } - if (Buffer.isBuffer(value)) { - return JSON.parse(value.toString()); - } - return null; // let the default type take care of it - }, - - 'setabi.abi.appendByteBuffer': function setabiAbiAppendByteBuffer(_ref) { - var fields = _ref.fields, - object = _ref.object, - b = _ref.b; - - var ser = structLookup('abi_def', 'eosio'); - var b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - - if (Buffer.isBuffer(object.abi)) { - b2.append(object.abi); - } else if ((0, _typeof3.default)(object.abi) == 'object') { - ser.appendByteBuffer(b2, object.abi); - } - - b.writeVarint32(b2.offset); // length prefix - b.append(b2.copy(0, b2.offset), 'binary'); - } - }; -}; - -var wasmCodeOverride = function wasmCodeOverride(config) { - return { - 'setcode.code.fromObject': function setcodeCodeFromObject(_ref2) { - var object = _ref2.object, - result = _ref2.result; - - try { - var code = object.code.toString(); - if (/^\s*\(module/.test(code)) { - var binaryen = config.binaryen; - - assert(binaryen != null, 'required: config.binaryen = require("binaryen")'); - if (config.debug) { - console.log('Assembling WASM..'); - } - var wasm = Buffer.from(binaryen.parseText(code).emitBinary()); - result.code = wasm; - } else { - result.code = object.code; - } - } catch (error) { - console.error(error, object.code); - throw error; - } - } - }; -}; - -/** - Nested serialized structure. Nested struct may be in HEX or object format. -*/ -var actionDataOverride = function actionDataOverride(structLookup, forceActionDataHex) { - return { - 'action.data.fromByteBuffer': function actionDataFromByteBuffer(_ref3) { - var fields = _ref3.fields, - object = _ref3.object, - b = _ref3.b, - config = _ref3.config; - - var ser = (object.name || '') == '' ? fields.data : structLookup(object.name, object.account); - if (ser) { - b.readVarint32(); // length prefix (usefull if object.name is unknown) - object.data = ser.fromByteBuffer(b, config); - } else { - // console.log(`Unknown Action.name ${object.name}`) - var lenPrefix = b.readVarint32(); - var bCopy = b.copy(b.offset, b.offset + lenPrefix); - b.skip(lenPrefix); - object.data = Buffer.from(bCopy.toBinary(), 'binary'); - } - }, - - 'action.data.appendByteBuffer': function actionDataAppendByteBuffer(_ref4) { - var fields = _ref4.fields, - object = _ref4.object, - b = _ref4.b; - - var ser = (object.name || '') == '' ? fields.data : structLookup(object.name, object.account); - if (ser) { - var b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - ser.appendByteBuffer(b2, object.data); - b.writeVarint32(b2.offset); - b.append(b2.copy(0, b2.offset), 'binary'); - } else { - // console.log(`Unknown Action.name ${object.name}`) - var data = typeof object.data === 'string' ? new Buffer(object.data, 'hex') : object.data; - if (!Buffer.isBuffer(data)) { - throw new TypeError('Unknown struct \'' + object.name + '\' for contract \'' + object.account + '\', locate this struct or provide serialized action.data'); - } - b.writeVarint32(data.length); - b.append(data.toString('binary'), 'binary'); - } - }, - - 'action.data.fromObject': function actionDataFromObject(_ref5) { - var fields = _ref5.fields, - object = _ref5.object, - result = _ref5.result; - var data = object.data, - name = object.name; - - var ser = (name || '') == '' ? fields.data : structLookup(name, object.account); - if (ser) { - if ((typeof data === 'undefined' ? 'undefined' : (0, _typeof3.default)(data)) === 'object') { - result.data = ser.fromObject(data); // resolve shorthand - } else if (typeof data === 'string') { - var buf = new Buffer(data, 'hex'); - result.data = Fcbuffer.fromBuffer(ser, buf); - } else { - throw new TypeError('Expecting hex string or object in action.data'); - } - } else { - // console.log(`Unknown Action.name ${object.name}`) - result.data = data; - } - }, - - 'action.data.toObject': function actionDataToObject(_ref6) { - var fields = _ref6.fields, - object = _ref6.object, - result = _ref6.result, - config = _ref6.config; - - var _ref7 = object || {}, - data = _ref7.data, - name = _ref7.name; - - var ser = (name || '') == '' ? fields.data : structLookup(name, object.account); - if (!ser) { - // Types without an ABI will accept hex - result.data = Buffer.isBuffer(data) ? data.toString('hex') : data; - return; - } - - if (forceActionDataHex) { - var b2 = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - if (data) { - ser.appendByteBuffer(b2, data); - } - result.data = b2.copy(0, b2.offset).toString('hex'); - // console.log('result.data', result.data) - return; - } - - // Serializable JSON - result.data = ser.toObject(data, config); - } - }; -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.__esModule = true; - -var _isIterable2 = __webpack_require__(312); - -var _isIterable3 = _interopRequireDefault(_isIterable2); - -var _getIterator2 = __webpack_require__(315); - -var _getIterator3 = _interopRequireDefault(_getIterator2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.default = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = (0, _getIterator3.default)(arr), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if ((0, _isIterable3.default)(Object(arr))) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -const BLOCKCHAIN_SUPPORT = exports.BLOCKCHAIN_SUPPORT = 'blockchain_support'; - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.BlockchainsArray = exports.Blockchains = undefined; - -var _keys = __webpack_require__(325); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const Blockchains = exports.Blockchains = { - EOS: 'eos', - ETH: 'eth' -}; - -const BlockchainsArray = exports.BlockchainsArray = (0, _keys2.default)(Blockchains).map(key => ({ key, value: Blockchains[key] })); - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - -var hash = exports; - -hash.utils = __webpack_require__(13); -hash.common = __webpack_require__(48); -hash.sha = __webpack_require__(354); -hash.ripemd = __webpack_require__(358); -hash.hmac = __webpack_require__(359); - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -var Symbol = __webpack_require__(173), - getRawTag = __webpack_require__(378), - objectToString = __webpack_require__(379); - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); -} - -module.exports = baseGetTag; - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = once; -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; - -/***/ }), -/* 102 */ -/***/ (function(module, exports) { - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -module.exports = isObjectLike; - - -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = onlyOnce; -function onlyOnce(fn) { - return function () { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - -const createPayload = __webpack_require__(50) - -module.exports = SubProvider - -// this is the base class for a subprovider -- mostly helpers - - -function SubProvider() { - -} - -SubProvider.prototype.setEngine = function(engine) { - const self = this - self.engine = engine - engine.on('block', function(block) { - self.currentBlock = block - }) -} - -SubProvider.prototype.handleRequest = function(payload, next, end) { - throw new Error('Subproviders should override `handleRequest`.') -} - -SubProvider.prototype.emitPayload = function(payload, cb){ - const self = this - self.engine.sendAsync(createPayload(payload), cb) -} - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - -/* - * Copyright (c) 2012 Mathieu Turcotte - * Licensed under the MIT license. - */ - -module.exports = __webpack_require__(425); - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = !__webpack_require__(21) && !__webpack_require__(28)(function () { - return Object.defineProperty(__webpack_require__(70)('div'), 'a', { get: function () { return 7; } }).a != 7; -}); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -var has = __webpack_require__(22); -var toIObject = __webpack_require__(29); -var arrayIndexOf = __webpack_require__(189)(false); -var IE_PROTO = __webpack_require__(74)('IE_PROTO'); - -module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; -}; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = __webpack_require__(37); -// eslint-disable-next-line no-prototype-builtins -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); -}; - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -// 7.1.15 ToLength -var toInteger = __webpack_require__(73); -var min = Math.min; -module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; - - -/***/ }), -/* 110 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 111 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var LIBRARY = __webpack_require__(38); -var $export = __webpack_require__(17); -var redefine = __webpack_require__(112); -var hide = __webpack_require__(18); -var Iterators = __webpack_require__(30); -var $iterCreate = __webpack_require__(193); -var setToStringTag = __webpack_require__(57); -var getPrototypeOf = __webpack_require__(195); -var ITERATOR = __webpack_require__(7)('iterator'); -var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` -var FF_ITERATOR = '@@iterator'; -var KEYS = 'keys'; -var VALUES = 'values'; - -var returnThis = function () { return this; }; - -module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; -}; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(18); - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -var anObject = __webpack_require__(14); -var dPs = __webpack_require__(194); -var enumBugKeys = __webpack_require__(76); -var IE_PROTO = __webpack_require__(74)('IE_PROTO'); -var Empty = function () { /* empty */ }; -var PROTOTYPE = 'prototype'; - -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(70)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(114).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); -}; - -module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); -}; - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - -var document = __webpack_require__(6).document; -module.exports = document && document.documentElement; - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - -var classof = __webpack_require__(79); -var ITERATOR = __webpack_require__(7)('iterator'); -var Iterators = __webpack_require__(30); -module.exports = __webpack_require__(5).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; -}; - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - -// 7.3.20 SpeciesConstructor(O, defaultConstructor) -var anObject = __webpack_require__(14); -var aFunction = __webpack_require__(52); -var SPECIES = __webpack_require__(7)('species'); -module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); -}; - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - -var ctx = __webpack_require__(51); -var invoke = __webpack_require__(204); -var html = __webpack_require__(114); -var cel = __webpack_require__(70); -var global = __webpack_require__(6); -var process = global.process; -var setTask = global.setImmediate; -var clearTask = global.clearImmediate; -var MessageChannel = global.MessageChannel; -var Dispatch = global.Dispatch; -var counter = 0; -var queue = {}; -var ONREADYSTATECHANGE = 'onreadystatechange'; -var defer, channel, port; -var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } -}; -var listener = function (event) { - run.call(event.data); -}; -// Node.js 0.9+ & IE10+ has setImmediate, otherwise: -if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(37)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } -} -module.exports = { - set: setTask, - clear: clearTask -}; - - -/***/ }), -/* 118 */ -/***/ (function(module, exports) { - -module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } -}; - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - -var anObject = __webpack_require__(14); -var isObject = __webpack_require__(20); -var newPromiseCapability = __webpack_require__(80); - -module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; -}; - - -/***/ }), -/* 120 */ -/***/ (function(module, exports) { - -/** - * Parses an URI - * - * @author Steven Levithan (MIT license) - * @api private - */ - -var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - -var parts = [ - 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' -]; - -module.exports = function parseuri(str) { - var src = str, - b = str.indexOf('['), - e = str.indexOf(']'); - - if (b != -1 && e != -1) { - str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); - } - - var m = re.exec(str || ''), - uri = {}, - i = 14; - - while (i--) { - uri[parts[i]] = m[i] || ''; - } - - if (b != -1 && e != -1) { - uri.source = src; - uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); - uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); - uri.ipv6uri = true; - } - - return uri; -}; - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) { -module.exports = isBuf; - -var withNativeBuffer = typeof global.Buffer === 'function' && typeof global.Buffer.isBuffer === 'function'; -var withNativeArrayBuffer = typeof global.ArrayBuffer === 'function'; - -var isView = (function () { - if (withNativeArrayBuffer && typeof global.ArrayBuffer.isView === 'function') { - return global.ArrayBuffer.isView; - } else { - return function (obj) { return obj.buffer instanceof global.ArrayBuffer; }; - } -})(); - -/** - * Returns true if obj is a buffer or an arraybuffer. - * - * @api private - */ - -function isBuf(obj) { - return (withNativeBuffer && global.Buffer.isBuffer(obj)) || - (withNativeArrayBuffer && (obj instanceof global.ArrayBuffer || isView(obj))); -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var eio = __webpack_require__(217); -var Socket = __webpack_require__(128); -var Emitter = __webpack_require__(31); -var parser = __webpack_require__(82); -var on = __webpack_require__(129); -var bind = __webpack_require__(130); -var debug = __webpack_require__(15)('socket.io-client:manager'); -var indexOf = __webpack_require__(127); -var Backoff = __webpack_require__(234); - -/** - * IE6+ hasOwnProperty - */ - -var has = Object.prototype.hasOwnProperty; - -/** - * Module exports - */ - -module.exports = Manager; - -/** - * `Manager` constructor. - * - * @param {String} engine instance or engine uri/opts - * @param {Object} options - * @api public - */ - -function Manager (uri, opts) { - if (!(this instanceof Manager)) return new Manager(uri, opts); - if (uri && ('object' === typeof uri)) { - opts = uri; - uri = undefined; - } - opts = opts || {}; - - opts.path = opts.path || '/socket.io'; - this.nsps = {}; - this.subs = []; - this.opts = opts; - this.reconnection(opts.reconnection !== false); - this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - this.reconnectionDelay(opts.reconnectionDelay || 1000); - this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - this.randomizationFactor(opts.randomizationFactor || 0.5); - this.backoff = new Backoff({ - min: this.reconnectionDelay(), - max: this.reconnectionDelayMax(), - jitter: this.randomizationFactor() - }); - this.timeout(null == opts.timeout ? 20000 : opts.timeout); - this.readyState = 'closed'; - this.uri = uri; - this.connecting = []; - this.lastPing = null; - this.encoding = false; - this.packetBuffer = []; - var _parser = opts.parser || parser; - this.encoder = new _parser.Encoder(); - this.decoder = new _parser.Decoder(); - this.autoConnect = opts.autoConnect !== false; - if (this.autoConnect) this.open(); -} - -/** - * Propagate given event to sockets and emit on `this` - * - * @api private - */ - -Manager.prototype.emitAll = function () { - this.emit.apply(this, arguments); - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].emit.apply(this.nsps[nsp], arguments); - } - } -}; - -/** - * Update `socket.id` of all sockets - * - * @api private - */ - -Manager.prototype.updateSocketIds = function () { - for (var nsp in this.nsps) { - if (has.call(this.nsps, nsp)) { - this.nsps[nsp].id = this.generateId(nsp); - } - } -}; - -/** - * generate `socket.id` for the given `nsp` - * - * @param {String} nsp - * @return {String} - * @api private - */ - -Manager.prototype.generateId = function (nsp) { - return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id; -}; - -/** - * Mix in `Emitter`. - */ - -Emitter(Manager.prototype); - -/** - * Sets the `reconnection` config. - * - * @param {Boolean} true/false if it should automatically reconnect - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnection = function (v) { - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; -}; - -/** - * Sets the reconnection attempts config. - * - * @param {Number} max reconnection attempts before giving up - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionAttempts = function (v) { - if (!arguments.length) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; -}; - -/** - * Sets the delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionDelay = function (v) { - if (!arguments.length) return this._reconnectionDelay; - this._reconnectionDelay = v; - this.backoff && this.backoff.setMin(v); - return this; -}; - -Manager.prototype.randomizationFactor = function (v) { - if (!arguments.length) return this._randomizationFactor; - this._randomizationFactor = v; - this.backoff && this.backoff.setJitter(v); - return this; -}; - -/** - * Sets the maximum delay between reconnections. - * - * @param {Number} delay - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.reconnectionDelayMax = function (v) { - if (!arguments.length) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - this.backoff && this.backoff.setMax(v); - return this; -}; - -/** - * Sets the connection timeout. `false` to disable - * - * @return {Manager} self or value - * @api public - */ - -Manager.prototype.timeout = function (v) { - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; -}; - -/** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @api private - */ - -Manager.prototype.maybeReconnectOnOpen = function () { - // Only try to reconnect if it's the first time we're connecting - if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } -}; - -/** - * Sets the current transport `socket`. - * - * @param {Function} optional, callback - * @return {Manager} self - * @api public - */ - -Manager.prototype.open = -Manager.prototype.connect = function (fn, opts) { - debug('readyState %s', this.readyState); - if (~this.readyState.indexOf('open')) return this; - - debug('opening %s', this.uri); - this.engine = eio(this.uri, this.opts); - var socket = this.engine; - var self = this; - this.readyState = 'opening'; - this.skipReconnect = false; - - // emit `open` - var openSub = on(socket, 'open', function () { - self.onopen(); - fn && fn(); - }); - - // emit `connect_error` - var errorSub = on(socket, 'error', function (data) { - debug('connect_error'); - self.cleanup(); - self.readyState = 'closed'; - self.emitAll('connect_error', data); - if (fn) { - var err = new Error('Connection error'); - err.data = data; - fn(err); - } else { - // Only do this if there is no fn to handle the error - self.maybeReconnectOnOpen(); - } - }); - - // emit `connect_timeout` - if (false !== this._timeout) { - var timeout = this._timeout; - debug('connect attempt will timeout after %d', timeout); - - // set timer - var timer = setTimeout(function () { - debug('connect attempt timed out after %d', timeout); - openSub.destroy(); - socket.close(); - socket.emit('error', 'timeout'); - self.emitAll('connect_timeout', timeout); - }, timeout); - - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); - } - - this.subs.push(openSub); - this.subs.push(errorSub); - - return this; -}; - -/** - * Called upon transport open. - * - * @api private - */ - -Manager.prototype.onopen = function () { - debug('open'); - - // clear old subs - this.cleanup(); - - // mark as open - this.readyState = 'open'; - this.emit('open'); - - // add new subs - var socket = this.engine; - this.subs.push(on(socket, 'data', bind(this, 'ondata'))); - this.subs.push(on(socket, 'ping', bind(this, 'onping'))); - this.subs.push(on(socket, 'pong', bind(this, 'onpong'))); - this.subs.push(on(socket, 'error', bind(this, 'onerror'))); - this.subs.push(on(socket, 'close', bind(this, 'onclose'))); - this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded'))); -}; - -/** - * Called upon a ping. - * - * @api private - */ - -Manager.prototype.onping = function () { - this.lastPing = new Date(); - this.emitAll('ping'); -}; - -/** - * Called upon a packet. - * - * @api private - */ - -Manager.prototype.onpong = function () { - this.emitAll('pong', new Date() - this.lastPing); -}; - -/** - * Called with data. - * - * @api private - */ - -Manager.prototype.ondata = function (data) { - this.decoder.add(data); -}; - -/** - * Called when parser fully decodes a packet. - * - * @api private - */ - -Manager.prototype.ondecoded = function (packet) { - this.emit('packet', packet); -}; - -/** - * Called upon socket error. - * - * @api private - */ - -Manager.prototype.onerror = function (err) { - debug('error', err); - this.emitAll('error', err); -}; - -/** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @api public - */ - -Manager.prototype.socket = function (nsp, opts) { - var socket = this.nsps[nsp]; - if (!socket) { - socket = new Socket(this, nsp, opts); - this.nsps[nsp] = socket; - var self = this; - socket.on('connecting', onConnecting); - socket.on('connect', function () { - socket.id = self.generateId(nsp); - }); - - if (this.autoConnect) { - // manually call here since connecting event is fired before listening - onConnecting(); - } - } - - function onConnecting () { - if (!~indexOf(self.connecting, socket)) { - self.connecting.push(socket); - } - } - - return socket; -}; - -/** - * Called upon a socket close. - * - * @param {Socket} socket - */ - -Manager.prototype.destroy = function (socket) { - var index = indexOf(this.connecting, socket); - if (~index) this.connecting.splice(index, 1); - if (this.connecting.length) return; - - this.close(); -}; - -/** - * Writes a packet. - * - * @param {Object} packet - * @api private - */ - -Manager.prototype.packet = function (packet) { - debug('writing packet %j', packet); - var self = this; - if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query; - - if (!self.encoding) { - // encode, then write to engine with result - self.encoding = true; - this.encoder.encode(packet, function (encodedPackets) { - for (var i = 0; i < encodedPackets.length; i++) { - self.engine.write(encodedPackets[i], packet.options); - } - self.encoding = false; - self.processPacketQueue(); - }); - } else { // add packet to the queue - self.packetBuffer.push(packet); - } -}; - -/** - * If packet buffer is non-empty, begins encoding the - * next packet in line. - * - * @api private - */ - -Manager.prototype.processPacketQueue = function () { - if (this.packetBuffer.length > 0 && !this.encoding) { - var pack = this.packetBuffer.shift(); - this.packet(pack); - } -}; - -/** - * Clean up transport subscriptions and packet buffer. - * - * @api private - */ - -Manager.prototype.cleanup = function () { - debug('cleanup'); - - var subsLength = this.subs.length; - for (var i = 0; i < subsLength; i++) { - var sub = this.subs.shift(); - sub.destroy(); - } - - this.packetBuffer = []; - this.encoding = false; - this.lastPing = null; - - this.decoder.destroy(); -}; - -/** - * Close the current socket. - * - * @api private - */ - -Manager.prototype.close = -Manager.prototype.disconnect = function () { - debug('disconnect'); - this.skipReconnect = true; - this.reconnecting = false; - if ('opening' === this.readyState) { - // `onclose` will not fire because - // an open event never happened - this.cleanup(); - } - this.backoff.reset(); - this.readyState = 'closed'; - if (this.engine) this.engine.close(); -}; - -/** - * Called upon engine close. - * - * @api private - */ - -Manager.prototype.onclose = function (reason) { - debug('onclose'); - - this.cleanup(); - this.backoff.reset(); - this.readyState = 'closed'; - this.emit('close', reason); - - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } -}; - -/** - * Attempt a reconnection. - * - * @api private - */ - -Manager.prototype.reconnect = function () { - if (this.reconnecting || this.skipReconnect) return this; - - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug('reconnect failed'); - this.backoff.reset(); - this.emitAll('reconnect_failed'); - this.reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug('will wait %dms before reconnect attempt', delay); - - this.reconnecting = true; - var timer = setTimeout(function () { - if (self.skipReconnect) return; - - debug('attempting reconnect'); - self.emitAll('reconnect_attempt', self.backoff.attempts); - self.emitAll('reconnecting', self.backoff.attempts); - - // check again for the case socket closed in above events - if (self.skipReconnect) return; - - self.open(function (err) { - if (err) { - debug('reconnect attempt error'); - self.reconnecting = false; - self.reconnect(); - self.emitAll('reconnect_error', err.data); - } else { - debug('reconnect success'); - self.onreconnect(); - } - }); - }, delay); - - this.subs.push({ - destroy: function () { - clearTimeout(timer); - } - }); - } -}; - -/** - * Called upon successful reconnect. - * - * @api private - */ - -Manager.prototype.onreconnect = function () { - var attempt = this.backoff.attempts; - this.reconnecting = false; - this.backoff.reset(); - this.updateSocketIds(); - this.emitAll('reconnect', attempt); -}; - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies - */ - -var XMLHttpRequest = __webpack_require__(84); -var XHR = __webpack_require__(220); -var JSONP = __webpack_require__(230); -var websocket = __webpack_require__(231); - -/** - * Export transports. - */ - -exports.polling = polling; -exports.websocket = websocket; - -/** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ - -function polling (opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; - - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; - - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; - } - - xd = opts.hostname !== location.hostname || port !== opts.port; - xs = opts.secure !== isSSL; - } - - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); - - if ('open' in xhr && !opts.forceJSONP) { - return new XHR(opts); - } else { - if (!jsonp) throw new Error('JSONP disabled'); - return new JSONP(opts); - } -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * Module dependencies. - */ - -var Transport = __webpack_require__(85); -var parseqs = __webpack_require__(60); -var parser = __webpack_require__(32); -var inherit = __webpack_require__(61); -var yeast = __webpack_require__(126); -var debug = __webpack_require__(15)('engine.io-client:polling'); - -/** - * Module exports. - */ - -module.exports = Polling; - -/** - * Is XHR2 supported? - */ - -var hasXHR2 = (function () { - var XMLHttpRequest = __webpack_require__(84); - var xhr = new XMLHttpRequest({ xdomain: false }); - return null != xhr.responseType; -})(); - -/** - * Polling interface. - * - * @param {Object} opts - * @api private - */ - -function Polling (opts) { - var forceBase64 = (opts && opts.forceBase64); - if (!hasXHR2 || forceBase64) { - this.supportsBinary = false; - } - Transport.call(this, opts); -} - -/** - * Inherits from Transport. - */ - -inherit(Polling, Transport); - -/** - * Transport name. - */ - -Polling.prototype.name = 'polling'; - -/** - * Opens the socket (triggers polling). We write a PING message to determine - * when the transport is open. - * - * @api private - */ - -Polling.prototype.doOpen = function () { - this.poll(); -}; - -/** - * Pauses polling. - * - * @param {Function} callback upon buffers are flushed and transport is paused - * @api private - */ - -Polling.prototype.pause = function (onPause) { - var self = this; - - this.readyState = 'pausing'; - - function pause () { - debug('paused'); - self.readyState = 'paused'; - onPause(); - } - - if (this.polling || !this.writable) { - var total = 0; - - if (this.polling) { - debug('we are currently polling - waiting to pause'); - total++; - this.once('pollComplete', function () { - debug('pre-pause polling complete'); - --total || pause(); - }); - } - - if (!this.writable) { - debug('we are currently writing - waiting to pause'); - total++; - this.once('drain', function () { - debug('pre-pause writing complete'); - --total || pause(); - }); - } - } else { - pause(); - } -}; - -/** - * Starts polling cycle. - * - * @api public - */ - -Polling.prototype.poll = function () { - debug('polling'); - this.polling = true; - this.doPoll(); - this.emit('poll'); -}; - -/** - * Overloads onData to detect payloads. - * - * @api private - */ - -Polling.prototype.onData = function (data) { - var self = this; - debug('polling got data %s', data); - var callback = function (packet, index, total) { - // if its the first message we consider the transport open - if ('opening' === self.readyState) { - self.onOpen(); - } - - // if its a close packet, we close the ongoing requests - if ('close' === packet.type) { - self.onClose(); - return false; - } - - // otherwise bypass onData and handle the message - self.onPacket(packet); - }; - - // decode payload - parser.decodePayload(data, this.socket.binaryType, callback); - - // if an event did not trigger closing - if ('closed' !== this.readyState) { - // if we got data we're not polling - this.polling = false; - this.emit('pollComplete'); - - if ('open' === this.readyState) { - this.poll(); - } else { - debug('ignoring poll - transport state "%s"', this.readyState); - } - } -}; - -/** - * For polling, send a close packet. - * - * @api private - */ - -Polling.prototype.doClose = function () { - var self = this; - - function close () { - debug('writing close packet'); - self.write([{ type: 'close' }]); - } - - if ('open' === this.readyState) { - debug('transport open - closing'); - close(); - } else { - // in case we're trying to close while - // handshaking is in progress (GH-164) - debug('transport not open - deferring close'); - this.once('open', close); - } -}; - -/** - * Writes a packets payload. - * - * @param {Array} data packets - * @param {Function} drain callback - * @api private - */ - -Polling.prototype.write = function (packets) { - var self = this; - this.writable = false; - var callbackfn = function () { - self.writable = true; - self.emit('drain'); - }; - - parser.encodePayload(packets, this.supportsBinary, function (data) { - self.doWrite(data, callbackfn); - }); -}; - -/** - * Generates uri for connection. - * - * @api private - */ - -Polling.prototype.uri = function () { - var query = this.query || {}; - var schema = this.secure ? 'https' : 'http'; - var port = ''; - - // cache busting is forced - if (false !== this.timestampRequests) { - query[this.timestampParam] = yeast(); - } - - if (!this.supportsBinary && !query.sid) { - query.b64 = 1; - } - - query = parseqs.encode(query); - - // avoid port if default for schema - if (this.port && (('https' === schema && Number(this.port) !== 443) || - ('http' === schema && Number(this.port) !== 80))) { - port = ':' + this.port; - } - - // prepend ? to query - if (query.length) { - query = '?' + query; - } - - var ipv6 = this.hostname.indexOf(':') !== -1; - return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query; -}; - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(Buffer) {/* global Blob File */ - -/* - * Module requirements. - */ - -var isArray = __webpack_require__(83); - -var toString = Object.prototype.toString; -var withNativeBlob = typeof Blob === 'function' || - typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'; -var withNativeFile = typeof File === 'function' || - typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'; - -/** - * Module exports. - */ - -module.exports = hasBinary; - -/** - * Checks for binary data. - * - * Supports Buffer, ArrayBuffer, Blob and File. - * - * @param {Object} anything - * @api public - */ - -function hasBinary (obj) { - if (!obj || typeof obj !== 'object') { - return false; - } - - if (isArray(obj)) { - for (var i = 0, l = obj.length; i < l; i++) { - if (hasBinary(obj[i])) { - return true; - } - } - return false; - } - - if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) || - (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) || - (withNativeBlob && obj instanceof Blob) || - (withNativeFile && obj instanceof File) - ) { - return true; - } - - // see: https://github.com/Automattic/has-binary/pull/4 - if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) { - return hasBinary(obj.toJSON(), true); - } - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { - return true; - } - } - - return false; -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') - , length = 64 - , map = {} - , seed = 0 - , i = 0 - , prev; - -/** - * Return a string representing the specified number. - * - * @param {Number} num The number to convert. - * @returns {String} The string representation of the number. - * @api public - */ -function encode(num) { - var encoded = ''; - - do { - encoded = alphabet[num % length] + encoded; - num = Math.floor(num / length); - } while (num > 0); - - return encoded; -} - -/** - * Return the integer value specified by the given string. - * - * @param {String} str The string to convert. - * @returns {Number} The integer value represented by the string. - * @api public - */ -function decode(str) { - var decoded = 0; - - for (i = 0; i < str.length; i++) { - decoded = decoded * length + map[str.charAt(i)]; - } - - return decoded; -} - -/** - * Yeast: A tiny growing id generator. - * - * @returns {String} A unique id. - * @api public - */ -function yeast() { - var now = encode(+new Date()); - - if (now !== prev) return seed = 0, prev = now; - return now +'.'+ encode(seed++); -} - -// -// Map each character to its index. -// -for (; i < length; i++) map[alphabet[i]] = i; - -// -// Expose the `yeast`, `encode` and `decode` functions. -// -yeast.encode = encode; -yeast.decode = decode; -module.exports = yeast; - - -/***/ }), -/* 127 */ -/***/ (function(module, exports) { - - -var indexOf = [].indexOf; - -module.exports = function(arr, obj){ - if (indexOf) return arr.indexOf(obj); - for (var i = 0; i < arr.length; ++i) { - if (arr[i] === obj) return i; - } - return -1; -}; - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var parser = __webpack_require__(82); -var Emitter = __webpack_require__(31); -var toArray = __webpack_require__(233); -var on = __webpack_require__(129); -var bind = __webpack_require__(130); -var debug = __webpack_require__(15)('socket.io-client:socket'); -var parseqs = __webpack_require__(60); -var hasBin = __webpack_require__(125); - -/** - * Module exports. - */ - -module.exports = exports = Socket; - -/** - * Internal events (blacklisted). - * These events can't be emitted by the user. - * - * @api private - */ - -var events = { - connect: 1, - connect_error: 1, - connect_timeout: 1, - connecting: 1, - disconnect: 1, - error: 1, - reconnect: 1, - reconnect_attempt: 1, - reconnect_failed: 1, - reconnect_error: 1, - reconnecting: 1, - ping: 1, - pong: 1 -}; - -/** - * Shortcut to `Emitter#emit`. - */ - -var emit = Emitter.prototype.emit; - -/** - * `Socket` constructor. - * - * @api public - */ - -function Socket (io, nsp, opts) { - this.io = io; - this.nsp = nsp; - this.json = this; // compat - this.ids = 0; - this.acks = {}; - this.receiveBuffer = []; - this.sendBuffer = []; - this.connected = false; - this.disconnected = true; - this.flags = {}; - if (opts && opts.query) { - this.query = opts.query; - } - if (this.io.autoConnect) this.open(); -} - -/** - * Mix in `Emitter`. - */ - -Emitter(Socket.prototype); - -/** - * Subscribe to open, close and packet events - * - * @api private - */ - -Socket.prototype.subEvents = function () { - if (this.subs) return; - - var io = this.io; - this.subs = [ - on(io, 'open', bind(this, 'onopen')), - on(io, 'packet', bind(this, 'onpacket')), - on(io, 'close', bind(this, 'onclose')) - ]; -}; - -/** - * "Opens" the socket. - * - * @api public - */ - -Socket.prototype.open = -Socket.prototype.connect = function () { - if (this.connected) return this; - - this.subEvents(); - this.io.open(); // ensure open - if ('open' === this.io.readyState) this.onopen(); - this.emit('connecting'); - return this; -}; - -/** - * Sends a `message` event. - * - * @return {Socket} self - * @api public - */ - -Socket.prototype.send = function () { - var args = toArray(arguments); - args.unshift('message'); - this.emit.apply(this, args); - return this; -}; - -/** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param {String} event name - * @return {Socket} self - * @api public - */ - -Socket.prototype.emit = function (ev) { - if (events.hasOwnProperty(ev)) { - emit.apply(this, arguments); - return this; - } - - var args = toArray(arguments); - var packet = { - type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT, - data: args - }; - - packet.options = {}; - packet.options.compress = !this.flags || false !== this.flags.compress; - - // event ack callback - if ('function' === typeof args[args.length - 1]) { - debug('emitting packet with ack id %d', this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; - } - - if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - - this.flags = {}; - - return this; -}; - -/** - * Sends a packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.packet = function (packet) { - packet.nsp = this.nsp; - this.io.packet(packet); -}; - -/** - * Called upon engine `open`. - * - * @api private - */ - -Socket.prototype.onopen = function () { - debug('transport is open - connecting'); - - // write connect packet if necessary - if ('/' !== this.nsp) { - if (this.query) { - var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query; - debug('sending connect packet with query %s', query); - this.packet({type: parser.CONNECT, query: query}); - } else { - this.packet({type: parser.CONNECT}); - } - } -}; - -/** - * Called upon engine `close`. - * - * @param {String} reason - * @api private - */ - -Socket.prototype.onclose = function (reason) { - debug('close (%s)', reason); - this.connected = false; - this.disconnected = true; - delete this.id; - this.emit('disconnect', reason); -}; - -/** - * Called with socket packet. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onpacket = function (packet) { - var sameNamespace = packet.nsp === this.nsp; - var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/'; - - if (!sameNamespace && !rootNamespaceError) return; - - switch (packet.type) { - case parser.CONNECT: - this.onconnect(); - break; - - case parser.EVENT: - this.onevent(packet); - break; - - case parser.BINARY_EVENT: - this.onevent(packet); - break; - - case parser.ACK: - this.onack(packet); - break; - - case parser.BINARY_ACK: - this.onack(packet); - break; - - case parser.DISCONNECT: - this.ondisconnect(); - break; - - case parser.ERROR: - this.emit('error', packet.data); - break; - } -}; - -/** - * Called upon a server event. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onevent = function (packet) { - var args = packet.data || []; - debug('emitting event %j', args); - - if (null != packet.id) { - debug('attaching ack callback to event'); - args.push(this.ack(packet.id)); - } - - if (this.connected) { - emit.apply(this, args); - } else { - this.receiveBuffer.push(args); - } -}; - -/** - * Produces an ack callback to emit with an event. - * - * @api private - */ - -Socket.prototype.ack = function (id) { - var self = this; - var sent = false; - return function () { - // prevent double callbacks - if (sent) return; - sent = true; - var args = toArray(arguments); - debug('sending ack %j', args); - - self.packet({ - type: hasBin(args) ? parser.BINARY_ACK : parser.ACK, - id: id, - data: args - }); - }; -}; - -/** - * Called upon a server acknowlegement. - * - * @param {Object} packet - * @api private - */ - -Socket.prototype.onack = function (packet) { - var ack = this.acks[packet.id]; - if ('function' === typeof ack) { - debug('calling ack %s with %j', packet.id, packet.data); - ack.apply(this, packet.data); - delete this.acks[packet.id]; - } else { - debug('bad ack %s', packet.id); - } -}; - -/** - * Called upon server connect. - * - * @api private - */ - -Socket.prototype.onconnect = function () { - this.connected = true; - this.disconnected = false; - this.emit('connect'); - this.emitBuffered(); -}; - -/** - * Emit buffered events (received and emitted). - * - * @api private - */ - -Socket.prototype.emitBuffered = function () { - var i; - for (i = 0; i < this.receiveBuffer.length; i++) { - emit.apply(this, this.receiveBuffer[i]); - } - this.receiveBuffer = []; - - for (i = 0; i < this.sendBuffer.length; i++) { - this.packet(this.sendBuffer[i]); - } - this.sendBuffer = []; -}; - -/** - * Called upon server disconnect. - * - * @api private - */ - -Socket.prototype.ondisconnect = function () { - debug('server disconnect (%s)', this.nsp); - this.destroy(); - this.onclose('io server disconnect'); -}; - -/** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @api private. - */ - -Socket.prototype.destroy = function () { - if (this.subs) { - // clean subscriptions to avoid reconnections - for (var i = 0; i < this.subs.length; i++) { - this.subs[i].destroy(); - } - this.subs = null; - } - - this.io.destroy(this); -}; - -/** - * Disconnects the socket manually. - * - * @return {Socket} self - * @api public - */ - -Socket.prototype.close = -Socket.prototype.disconnect = function () { - if (this.connected) { - debug('performing disconnect (%s)', this.nsp); - this.packet({ type: parser.DISCONNECT }); - } - - // remove socket from pool - this.destroy(); - - if (this.connected) { - // fire events - this.onclose('io client disconnect'); - } - return this; -}; - -/** - * Sets the compress flag. - * - * @param {Boolean} if `true`, compresses the sending data - * @return {Socket} self - * @api public - */ - -Socket.prototype.compress = function (compress) { - this.flags.compress = compress; - return this; -}; - -/** - * Sets the binary flag - * - * @param {Boolean} whether the emitted data contains binary - * @return {Socket} self - * @api public - */ - -Socket.prototype.binary = function (binary) { - this.flags.binary = binary; - return this; -}; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports) { - - -/** - * Module exports. - */ - -module.exports = on; - -/** - * Helper for subscriptions. - * - * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter` - * @param {String} event name - * @param {Function} callback - * @api public - */ - -function on (obj, ev, fn) { - obj.on(ev, fn); - return { - destroy: function () { - obj.removeListener(ev, fn); - } - }; -} - - -/***/ }), -/* 130 */ -/***/ (function(module, exports) { - -/** - * Slice reference. - */ - -var slice = [].slice; - -/** - * Bind `obj` to `fn`. - * - * @param {Object} obj - * @param {Function|String} fn or string - * @return {Function} - * @api public - */ - -module.exports = function(obj, fn){ - if ('string' == typeof fn) fn = obj[fn]; - if ('function' != typeof fn) throw new Error('bind() requires a function'); - var args = slice.call(arguments, 2); - return function(){ - return fn.apply(obj, args.concat(slice.call(arguments))); - } -}; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var win; - -if (typeof window !== "undefined") { - win = window; -} else if (typeof global !== "undefined") { - win = global; -} else if (typeof self !== "undefined"){ - win = self; -} else { - win = {}; -} - -module.exports = win; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(239); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) -var $keys = __webpack_require__(107); -var hiddenKeys = __webpack_require__(76).concat('length', 'prototype'); - -exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); -}; - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var randomBytes = __webpack_require__(135); -var ByteBuffer = __webpack_require__(33); -var crypto = __webpack_require__(255); -var assert = __webpack_require__(4); -var PublicKey = __webpack_require__(44); -var PrivateKey = __webpack_require__(65); -var hash = __webpack_require__(25); - -var Long = ByteBuffer.Long; - -module.exports = { - encrypt: encrypt, - decrypt: decrypt - - /** - Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem - - @throws {Error|TypeError} - "Invalid Key, ..." - - @arg {PrivateKey} private_key - required and used for decryption - @arg {PublicKey} public_key - required and used to calcualte the shared secret - @arg {string} [nonce = uniqueNonce()] - assigned a random unique uint64 - - @return {object} - @property {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. - @property {Buffer} message - Plain text message - @property {number} checksum - shared secret checksum - */ -};function encrypt(private_key, public_key, message) { - var nonce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : uniqueNonce(); - - return crypt(private_key, public_key, nonce, message); -} - -/** - Spec: http://localhost:3002/steem/@dantheman/how-to-encrypt-a-memo-when-transferring-steem - - @arg {PrivateKey} private_key - required and used for decryption - @arg {PublicKey} public_key - required and used to calcualte the shared secret - @arg {string} nonce - random or unique uint64, provides entropy when re-using the same private/public keys. - @arg {Buffer} message - Encrypted or plain text message - @arg {number} checksum - shared secret checksum - - @throws {Error|TypeError} - "Invalid Key, ..." - - @return {Buffer} - message -*/ -function decrypt(private_key, public_key, nonce, message, checksum) { - return crypt(private_key, public_key, nonce, message, checksum).message; -} - -/** - @arg {Buffer} message - Encrypted or plain text message (see checksum) - @arg {number} checksum - shared secret checksum (null to encrypt, non-null to decrypt) - @private -*/ -function crypt(private_key, public_key, nonce, message, checksum) { - private_key = PrivateKey(private_key); - if (!private_key) throw new TypeError('private_key is required'); - - public_key = PublicKey(public_key); - if (!public_key) throw new TypeError('public_key is required'); - - nonce = toLongObj(nonce); - if (!nonce) throw new TypeError('nonce is required'); - - if (!Buffer.isBuffer(message)) { - if (typeof message !== 'string') throw new TypeError('message should be buffer or string'); - message = new Buffer(message, 'binary'); - } - if (checksum && typeof checksum !== 'number') throw new TypeError('checksum should be a number'); - - var S = private_key.getSharedSecret(public_key); - var ebuf = new ByteBuffer(ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - ebuf.writeUint64(nonce); - ebuf.append(S.toString('binary'), 'binary'); - ebuf = new Buffer(ebuf.copy(0, ebuf.offset).toBinary(), 'binary'); - var encryption_key = hash.sha512(ebuf); - - // D E B U G - // console.log('crypt', { - // priv_to_pub: private_key.toPublic().toString(), - // pub: public_key.toString(), - // nonce: nonce.toString(), - // message: message.length, - // checksum, - // S: S.toString('hex'), - // encryption_key: encryption_key.toString('hex'), - // }) - - var iv = encryption_key.slice(32, 48); - var key = encryption_key.slice(0, 32); - - // check is first 64 bit of sha256 hash treated as uint64_t truncated to 32 bits. - var check = hash.sha256(encryption_key); - check = check.slice(0, 4); - var cbuf = ByteBuffer.fromBinary(check.toString('binary'), ByteBuffer.DEFAULT_CAPACITY, ByteBuffer.LITTLE_ENDIAN); - check = cbuf.readUint32(); - - if (checksum) { - if (check !== checksum) throw new Error('Invalid key'); - message = cryptoJsDecrypt(message, key, iv); - } else { - message = cryptoJsEncrypt(message, key, iv); - } - return { nonce: nonce, message: message, checksum: check }; -} - -/** This method does not use a checksum, the returned data must be validated some other way. - - @arg {string|Buffer} message - ciphertext binary format - @arg {string|Buffer} key - 256bit - @arg {string|Buffer} iv - 128bit - - @return {Buffer} -*/ -function cryptoJsDecrypt(message, key, iv) { - assert(message, "Missing cipher text"); - message = toBinaryBuffer(message); - var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); - // decipher.setAutoPadding(true) - message = Buffer.concat([decipher.update(message), decipher.final()]); - return message; -} - -/** This method does not use a checksum, the returned data must be validated some other way. - @arg {string|Buffer} message - plaintext binary format - @arg {string|Buffer} key - 256bit - @arg {string|Buffer} iv - 128bit - - @return {Buffer} -*/ -function cryptoJsEncrypt(message, key, iv) { - assert(message, "Missing plain text"); - message = toBinaryBuffer(message); - var cipher = crypto.createCipheriv('aes-256-cbc', key, iv); - // cipher.setAutoPadding(true) - message = Buffer.concat([cipher.update(message), cipher.final()]); - return message; -} - -/** @return {string} unique 64 bit unsigned number string. Being time based, this is careful to never choose the same nonce twice. This value could be recorded in the blockchain for a long time. -*/ -function uniqueNonce() { - if (unique_nonce_entropy === null) { - var b = new Uint8Array(randomBytes(2)); - unique_nonce_entropy = parseInt(b[0] << 8 | b[1], 10); - } - var long = Long.fromNumber(Date.now()); - var entropy = ++unique_nonce_entropy % 0xFFFF; - // console.log('uniqueNonce date\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) - // console.log('uniqueNonce entropy\t', ByteBuffer.allocate(8).writeUint64(Long.fromNumber(entropy)).toHex(0)) - long = long.shiftLeft(16).or(Long.fromNumber(entropy)); - // console.log('uniqueNonce final\t', ByteBuffer.allocate(8).writeUint64(long).toHex(0)) - return long.toString(); -} -var unique_nonce_entropy = null; -// for(let i=1; i < 10; i++) key.uniqueNonce() - -var toLongObj = function toLongObj(o) { - return o ? Long.isLong(o) ? o : Long.fromString(o) : o; -}; -var toBinaryBuffer = function toBinaryBuffer(o) { - return o ? Buffer.isBuffer(o) ? o : new Buffer(o, 'binary') : o; -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) { - -function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') -} - -var Buffer = __webpack_require__(0).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 > 65536) throw new Error('requested too many random bytes') - // in case browserify isn't using the Uint8Array version - var rawBytes = new global.Uint8Array(size) - - // This will not work in older browsers. - // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - if (size > 0) { // getRandomValues fails on IE if size == 0 - crypto.getRandomValues(rawBytes) - } - - // XXX: phantomjs doesn't like a buffer being passed here - var bytes = Buffer.from(rawBytes.buffer) - - if (typeof cb === 'function') { - return process.nextTick(function () { - cb(null, bytes) - }) - } - - return bytes -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(11))) - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - -var modeModules = { - ECB: __webpack_require__(257), - CBC: __webpack_require__(258), - CFB: __webpack_require__(259), - CFB8: __webpack_require__(260), - CFB1: __webpack_require__(261), - OFB: __webpack_require__(262), - CTR: __webpack_require__(137), - GCM: __webpack_require__(137) -} - -var modes = __webpack_require__(139) - -for (var key in modes) { - modes[key].module = modeModules[modes[key].mode] -} - -module.exports = modes - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - -var xor = __webpack_require__(42) -var Buffer = __webpack_require__(0).Buffer -var incr32 = __webpack_require__(138) - -function getBlock (self) { - var out = self._cipher.encryptBlockRaw(self._prev) - incr32(self._prev) - return out -} - -var blockSize = 16 -exports.encrypt = function (self, chunk) { - var chunkNum = Math.ceil(chunk.length / blockSize) - var start = self._cache.length - self._cache = Buffer.concat([ - self._cache, - Buffer.allocUnsafe(chunkNum * blockSize) - ]) - for (var i = 0; i < chunkNum; i++) { - var out = getBlock(self) - var offset = start + i * blockSize - self._cache.writeUInt32BE(out[0], offset + 0) - self._cache.writeUInt32BE(out[1], offset + 4) - self._cache.writeUInt32BE(out[2], offset + 8) - self._cache.writeUInt32BE(out[3], offset + 12) - } - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} - - -/***/ }), -/* 138 */ -/***/ (function(module, exports) { - -function incr32 (iv) { - var len = iv.length - var item - while (len--) { - item = iv.readUInt8(len) - if (item === 255) { - iv.writeUInt8(0, len) - } else { - item++ - iv.writeUInt8(item, len) - break - } - } -} -module.exports = incr32 - - -/***/ }), -/* 139 */ -/***/ (function(module, exports) { - -module.exports = {"aes-128-ecb":{"cipher":"AES","key":128,"iv":0,"mode":"ECB","type":"block"},"aes-192-ecb":{"cipher":"AES","key":192,"iv":0,"mode":"ECB","type":"block"},"aes-256-ecb":{"cipher":"AES","key":256,"iv":0,"mode":"ECB","type":"block"},"aes-128-cbc":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes-192-cbc":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes-256-cbc":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes128":{"cipher":"AES","key":128,"iv":16,"mode":"CBC","type":"block"},"aes192":{"cipher":"AES","key":192,"iv":16,"mode":"CBC","type":"block"},"aes256":{"cipher":"AES","key":256,"iv":16,"mode":"CBC","type":"block"},"aes-128-cfb":{"cipher":"AES","key":128,"iv":16,"mode":"CFB","type":"stream"},"aes-192-cfb":{"cipher":"AES","key":192,"iv":16,"mode":"CFB","type":"stream"},"aes-256-cfb":{"cipher":"AES","key":256,"iv":16,"mode":"CFB","type":"stream"},"aes-128-cfb8":{"cipher":"AES","key":128,"iv":16,"mode":"CFB8","type":"stream"},"aes-192-cfb8":{"cipher":"AES","key":192,"iv":16,"mode":"CFB8","type":"stream"},"aes-256-cfb8":{"cipher":"AES","key":256,"iv":16,"mode":"CFB8","type":"stream"},"aes-128-cfb1":{"cipher":"AES","key":128,"iv":16,"mode":"CFB1","type":"stream"},"aes-192-cfb1":{"cipher":"AES","key":192,"iv":16,"mode":"CFB1","type":"stream"},"aes-256-cfb1":{"cipher":"AES","key":256,"iv":16,"mode":"CFB1","type":"stream"},"aes-128-ofb":{"cipher":"AES","key":128,"iv":16,"mode":"OFB","type":"stream"},"aes-192-ofb":{"cipher":"AES","key":192,"iv":16,"mode":"OFB","type":"stream"},"aes-256-ofb":{"cipher":"AES","key":256,"iv":16,"mode":"OFB","type":"stream"},"aes-128-ctr":{"cipher":"AES","key":128,"iv":16,"mode":"CTR","type":"stream"},"aes-192-ctr":{"cipher":"AES","key":192,"iv":16,"mode":"CTR","type":"stream"},"aes-256-ctr":{"cipher":"AES","key":256,"iv":16,"mode":"CTR","type":"stream"},"aes-128-gcm":{"cipher":"AES","key":128,"iv":12,"mode":"GCM","type":"auth"},"aes-192-gcm":{"cipher":"AES","key":192,"iv":12,"mode":"GCM","type":"auth"},"aes-256-gcm":{"cipher":"AES","key":256,"iv":12,"mode":"GCM","type":"auth"}} - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - -var aes = __webpack_require__(62) -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(23) -var inherits = __webpack_require__(1) -var GHASH = __webpack_require__(274) -var xor = __webpack_require__(42) -var incr32 = __webpack_require__(138) - -function xorTest (a, b) { - var out = 0 - if (a.length !== b.length) out++ - - var len = Math.min(a.length, b.length) - for (var i = 0; i < len; ++i) { - out += (a[i] ^ b[i]) - } - - return out -} - -function calcIv (self, iv, ck) { - if (iv.length === 12) { - self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) - return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) - } - var ghash = new GHASH(ck) - var len = iv.length - var toPad = len % 16 - ghash.update(iv) - if (toPad) { - toPad = 16 - toPad - ghash.update(Buffer.alloc(toPad, 0)) - } - ghash.update(Buffer.alloc(8, 0)) - var ivBits = len * 8 - var tail = Buffer.alloc(8) - tail.writeUIntBE(ivBits, 0, 8) - ghash.update(tail) - self._finID = ghash.state - var out = Buffer.from(self._finID) - incr32(out) - return out -} -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) - - var h = Buffer.alloc(4, 0) - - this._cipher = new aes.AES(key) - var ck = this._cipher.encryptBlock(h) - this._ghash = new GHASH(ck) - iv = calcIv(this, iv, ck) - - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._alen = 0 - this._len = 0 - this._mode = mode - - this._authTag = null - this._called = false -} - -inherits(StreamCipher, Transform) - -StreamCipher.prototype._update = function (chunk) { - if (!this._called && this._alen) { - var rump = 16 - (this._alen % 16) - if (rump < 16) { - rump = Buffer.alloc(rump, 0) - this._ghash.update(rump) - } - } - - this._called = true - var out = this._mode.encrypt(this, chunk) - if (this._decrypt) { - this._ghash.update(chunk) - } else { - this._ghash.update(out) - } - this._len += chunk.length - return out -} - -StreamCipher.prototype._final = function () { - if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') - - var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) - if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') - - this._authTag = tag - this._cipher.scrub() -} - -StreamCipher.prototype.getAuthTag = function getAuthTag () { - if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') - - return this._authTag -} - -StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { - if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') - - this._authTag = tag -} - -StreamCipher.prototype.setAAD = function setAAD (buf) { - if (this._called) throw new Error('Attempting to set AAD in unsupported state') - - this._ghash.update(buf) - this._alen += buf.length -} - -module.exports = StreamCipher - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global, process) {// 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. - - - -/**/ - -var pna = __webpack_require__(64); -/**/ - -module.exports = Readable; - -/**/ -var isArray = __webpack_require__(263); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = __webpack_require__(12).EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = __webpack_require__(142); -/**/ - -/**/ - -var Buffer = __webpack_require__(0).Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -/**/ -var util = __webpack_require__(43); -util.inherits = __webpack_require__(1); -/**/ - -/**/ -var debugUtil = __webpack_require__(264); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __webpack_require__(265); -var destroyImpl = __webpack_require__(143); -var StringDecoder; - -util.inherits(Readable, Stream); - -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 (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(24); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // 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; - - // 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 = __webpack_require__(91).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || __webpack_require__(24); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (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) { - this.push(null); - 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) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } 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; - } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(91).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - 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.length >= state.highWaterMark || 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 = true; - n = 0; - } else { - state.length -= n; - } - - 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) { - 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; - - // emit 'readable' now to make sure it gets picked up. - 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; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - 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; - pna.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - 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) { - this.emit('error', new Error('_read() is not implemented')); -}; - -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) pna.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(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // 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', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - 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) dest.emit('error', 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 () { - 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, unpipeInfo); - }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); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -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'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - 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 (method) { - return function () { - 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; -}; - -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 () { - return this._readableState.highWaterMark; - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// 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.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(11))) - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(12).EventEmitter; - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -/**/ - -var pna = __webpack_require__(64); -/**/ - -// 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 && (!this._writableState || !this._writableState.errorEmitted)) { - pna.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) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); - - return this; -} - -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.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) || - (typeof self !== "undefined" && self) || - window; -var apply = Function.prototype.apply; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { - if (timeout) { - timeout.close(); - } -}; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(scope, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// setimmediate attaches itself to the global object -__webpack_require__(267); -// On some exotic environments, it's not clear which object `setimmediate` was -// able to install onto. Search each possibility in the same order as the -// `setimmediate` library. -exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || - (typeof global !== "undefined" && global.setImmediate) || - (this && this.setImmediate); -exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || - (typeof global !== "undefined" && global.clearImmediate) || - (this && this.clearImmediate); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// 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. - - - -module.exports = Transform; - -var Duplex = __webpack_require__(24); - -/**/ -var util = __webpack_require__(43); -util.inherits = __webpack_require__(1); -/**/ - -util.inherits(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } - - 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._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) { - throw new Error('_transform() is not implemented'); -}; - -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.writecb && !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) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); -} - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - -var aes = __webpack_require__(62) -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(23) -var inherits = __webpack_require__(1) - -function StreamCipher (mode, key, iv, decrypt) { - Transform.call(this) - - this._cipher = new aes.AES(key) - this._prev = Buffer.from(iv) - this._cache = Buffer.allocUnsafe(0) - this._secCache = Buffer.allocUnsafe(0) - this._decrypt = decrypt - this._mode = mode -} - -inherits(StreamCipher, Transform) - -StreamCipher.prototype._update = function (chunk) { - return this._mode.encrypt(this, chunk, this._decrypt) -} - -StreamCipher.prototype._final = function () { - this._cipher.scrub() -} - -module.exports = StreamCipher - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - -var Buffer = __webpack_require__(0).Buffer -var MD5 = __webpack_require__(92) - -/* eslint-disable camelcase */ -function EVP_BytesToKey (password, salt, keyBits, ivLen) { - if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') - if (salt) { - if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') - if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') - } - - var keyLen = keyBits / 8 - var key = Buffer.alloc(keyLen) - var iv = Buffer.alloc(ivLen || 0) - var tmp = Buffer.alloc(0) - - while (keyLen > 0 || ivLen > 0) { - var hash = new MD5() - hash.update(tmp) - hash.update(password) - if (salt) hash.update(salt) - tmp = hash.digest() - - var used = 0 - - if (keyLen > 0) { - var keyStart = key.length - keyLen - used = Math.min(keyLen, tmp.length) - tmp.copy(key, keyStart, 0, used) - keyLen -= used - } - - if (used < tmp.length && ivLen > 0) { - var ivStart = iv.length - ivLen - var length = Math.min(ivLen, tmp.length - used) - tmp.copy(iv, ivStart, used, used + length) - ivLen -= length - } - } - - tmp.fill(0) - return { key: key, iv: iv } -} - -module.exports = EVP_BytesToKey - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(0).Buffer -var Transform = __webpack_require__(63).Transform -var inherits = __webpack_require__(1) - -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 - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - -var assert = __webpack_require__(4) -var Buffer = __webpack_require__(0).Buffer -var BigInteger = __webpack_require__(16) - -var THREE = BigInteger.valueOf(3) - -function Point (curve, x, y, z) { - assert.notStrictEqual(z, undefined, 'Missing Z coordinate') - - this.curve = curve - this.x = x - this.y = y - this.z = z - this._zInv = null - - this.compressed = true -} - -Object.defineProperty(Point.prototype, 'zInv', { - get: function () { - if (this._zInv === null) { - this._zInv = this.z.modInverse(this.curve.p) - } - - return this._zInv - } -}) - -Object.defineProperty(Point.prototype, 'affineX', { - get: function () { - return this.x.multiply(this.zInv).mod(this.curve.p) - } -}) - -Object.defineProperty(Point.prototype, 'affineY', { - get: function () { - return this.y.multiply(this.zInv).mod(this.curve.p) - } -}) - -Point.fromAffine = function (curve, x, y) { - return new Point(curve, x, y, BigInteger.ONE) -} - -Point.prototype.equals = function (other) { - if (other === this) return true - if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) - if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) - - // u = Y2 * Z1 - Y1 * Z2 - var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) - - if (u.signum() !== 0) return false - - // v = X2 * Z1 - X1 * Z2 - var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) - - return v.signum() === 0 -} - -Point.prototype.negate = function () { - var y = this.curve.p.subtract(this.y) - - return new Point(this.curve, this.x, y, this.z) -} - -Point.prototype.add = function (b) { - if (this.curve.isInfinity(this)) return b - if (this.curve.isInfinity(b)) return this - - var x1 = this.x - var y1 = this.y - var x2 = b.x - var y2 = b.y - - // u = Y2 * Z1 - Y1 * Z2 - var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) - // v = X2 * Z1 - X1 * Z2 - var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) - - if (v.signum() === 0) { - if (u.signum() === 0) { - return this.twice() // this == b, so double - } - - return this.curve.infinity // this = -b, so infinity - } - - var v2 = v.square() - var v3 = v2.multiply(v) - var x1v2 = x1.multiply(v2) - var zu2 = u.square().multiply(this.z) - - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.p) - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) - - return new Point(this.curve, x3, y3, z3) -} - -Point.prototype.twice = function () { - if (this.curve.isInfinity(this)) return this - if (this.y.signum() === 0) return this.curve.infinity - - var x1 = this.x - var y1 = this.y - - var y1z1 = y1.multiply(this.z).mod(this.curve.p) - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) - var a = this.curve.a - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE) - - if (a.signum() !== 0) { - w = w.add(this.z.square().multiply(a)) - } - - w = w.mod(this.curve.p) - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) - - return new Point(this.curve, x3, y3, z3) -} - -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -Point.prototype.multiply = function (k) { - if (this.curve.isInfinity(this)) return this - if (k.signum() === 0) return this.curve.infinity - - var e = k - var h = e.multiply(THREE) - - var neg = this.negate() - var R = this - - for (var i = h.bitLength() - 2; i > 0; --i) { - var hBit = h.testBit(i) - var eBit = e.testBit(i) - - R = R.twice() - - if (hBit !== eBit) { - R = R.add(hBit ? this : neg) - } - } - - return R -} - -// Compute this*j + x*k (simultaneous multiplication) -Point.prototype.multiplyTwo = function (j, x, k) { - var i = Math.max(j.bitLength(), k.bitLength()) - 1 - var R = this.curve.infinity - var both = this.add(x) - - while (i >= 0) { - var jBit = j.testBit(i) - var kBit = k.testBit(i) - - R = R.twice() - - if (jBit) { - if (kBit) { - R = R.add(both) - } else { - R = R.add(this) - } - } else if (kBit) { - R = R.add(x) - } - --i - } - - return R -} - -Point.prototype.getEncoded = function (compressed) { - if (compressed == null) compressed = this.compressed - if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00' - - var x = this.affineX - var y = this.affineY - var byteLength = this.curve.pLength - var buffer - - // 0x02/0x03 | X - if (compressed) { - buffer = Buffer.allocUnsafe(1 + byteLength) - buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) - - // 0x04 | X | Y - } else { - buffer = Buffer.allocUnsafe(1 + byteLength + byteLength) - buffer.writeUInt8(0x04, 0) - - y.toBuffer(byteLength).copy(buffer, 1 + byteLength) - } - - x.toBuffer(byteLength).copy(buffer, 1) - - return buffer -} - -Point.decodeFrom = function (curve, buffer) { - var type = buffer.readUInt8(0) - var compressed = (type !== 4) - - var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) - var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) - - var Q - if (compressed) { - assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') - assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') - - var isOdd = (type === 0x03) - Q = curve.pointFromX(isOdd, x) - } else { - assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') - - var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) - Q = Point.fromAffine(curve, x, y) - } - - Q.compressed = compressed - return Q -} - -Point.prototype.toString = function () { - if (this.curve.isInfinity(this)) return '(INFINITY)' - - return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' -} - -module.exports = Point - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - -// (public) Constructor -function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c) - - if (a != null) { - if ("number" == typeof a) this.fromNumber(a, b, c) - else if (b == null && "string" != typeof a) this.fromString(a, 256) - else this.fromString(a, b) - } -} - -var proto = BigInteger.prototype - -// duck-typed isBigInteger -proto.__bigi = __webpack_require__(277).version -BigInteger.isBigInteger = function (obj, check_ver) { - return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) -} - -// Bits per digit -var dbits - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c - c = Math.floor(v / 0x4000000) - w[j++] = v & 0x3ffffff - } - return c -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15 - while (--n >= 0) { - var l = this[i] & 0x7fff - var h = this[i++] >> 15 - var m = xh * l + h * xl - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) - w[j++] = l & 0x3fffffff - } - return c -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14 - while (--n >= 0) { - var l = this[i] & 0x3fff - var h = this[i++] >> 14 - var m = xh * l + h * xl - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c - c = (l >> 28) + (m >> 14) + xh * h - w[j++] = l & 0xfffffff - } - return c -} - -// wtf? -BigInteger.prototype.am = am1 -dbits = 26 - -BigInteger.prototype.DB = dbits -BigInteger.prototype.DM = ((1 << dbits) - 1) -var DV = BigInteger.prototype.DV = (1 << dbits) - -var BI_FP = 52 -BigInteger.prototype.FV = Math.pow(2, BI_FP) -BigInteger.prototype.F1 = BI_FP - dbits -BigInteger.prototype.F2 = 2 * dbits - BI_FP - -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" -var BI_RC = new Array() -var rr, vv -rr = "0".charCodeAt(0) -for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv -rr = "a".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -rr = "A".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv - -function int2char(n) { - return BI_RM.charAt(n) -} - -function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)] - return (c == null) ? -1 : c -} - -// (protected) copy this to r -function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] - r.t = this.t - r.s = this.s -} - -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1 - this.s = (x < 0) ? -1 : 0 - if (x > 0) this[0] = x - else if (x < -1) this[0] = x + DV - else this.t = 0 -} - -// return bigint initialized to value -function nbv(i) { - var r = new BigInteger() - r.fromInt(i) - return r -} - -// (protected) set from string and radix -function bnpFromString(s, b) { - var self = this - - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else { - self.fromRadix(s, b) - return - } - self.t = 0 - self.s = 0 - var i = s.length, - mi = false, - sh = 0 - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-") mi = true - continue - } - mi = false - if (sh == 0) - self[self.t++] = x - else if (sh + k > self.DB) { - self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh - self[self.t++] = (x >> (self.DB - sh)) - } else - self[self.t - 1] |= x << sh - sh += k - if (sh >= self.DB) sh -= self.DB - } - if (k == 8 && (s[0] & 0x80) != 0) { - self.s = -1 - if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh - } - self.clamp() - if (mi) BigInteger.ZERO.subTo(self, self) -} - -// (protected) clamp off excess high words -function bnpClamp() { - var c = this.s & this.DM - while (this.t > 0 && this[this.t - 1] == c)--this.t -} - -// (public) return string representation in given radix -function bnToString(b) { - var self = this - if (self.s < 0) return "-" + self.negate() - .toString(b) - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else return self.toRadix(b) - var km = (1 << k) - 1, - d, m = false, - r = "", - i = self.t - var p = self.DB - (i * self.DB) % k - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) > 0) { - m = true - r = int2char(d) - } - while (i >= 0) { - if (p < k) { - d = (self[i] & ((1 << p) - 1)) << (k - p) - d |= self[--i] >> (p += self.DB - k) - } else { - d = (self[i] >> (p -= k)) & km - if (p <= 0) { - p += self.DB - --i - } - } - if (d > 0) m = true - if (m) r += int2char(d) - } - } - return m ? r : "0" -} - -// (public) -this -function bnNegate() { - var r = new BigInteger() - BigInteger.ZERO.subTo(this, r) - return r -} - -// (public) |this| -function bnAbs() { - return (this.s < 0) ? this.negate() : this -} - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s - a.s - if (r != 0) return r - var i = this.t - r = i - a.t - if (r != 0) return (this.s < 0) ? -r : r - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r - return 0 -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, - t - if ((t = x >>> 16) != 0) { - x = t - r += 16 - } - if ((t = x >> 8) != 0) { - x = t - r += 8 - } - if ((t = x >> 4) != 0) { - x = t - r += 4 - } - if ((t = x >> 2) != 0) { - x = t - r += 2 - } - if ((t = x >> 1) != 0) { - x = t - r += 1 - } - return r -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if (this.t <= 0) return 0 - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) -} - -// (public) return the number of bytes in "this" -function bnByteLength() { - return this.bitLength() >> 3 -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n, r) { - var i - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] - for (i = n - 1; i >= 0; --i) r[i] = 0 - r.t = this.t + n - r.s = this.s -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i] - r.t = Math.max(this.t - n, 0) - r.s = this.s -} - -// (protected) r = this << n -function bnpLShiftTo(n, r) { - var self = this - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << cbs) - 1 - var ds = Math.floor(n / self.DB), - c = (self.s << bs) & self.DM, - i - for (i = self.t - 1; i >= 0; --i) { - r[i + ds + 1] = (self[i] >> cbs) | c - c = (self[i] & bm) << bs - } - for (i = ds - 1; i >= 0; --i) r[i] = 0 - r[ds] = c - r.t = self.t + ds + 1 - r.s = self.s - r.clamp() -} - -// (protected) r = this >> n -function bnpRShiftTo(n, r) { - var self = this - r.s = self.s - var ds = Math.floor(n / self.DB) - if (ds >= self.t) { - r.t = 0 - return - } - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << bs) - 1 - r[0] = self[ds] >> bs - for (var i = ds + 1; i < self.t; ++i) { - r[i - ds - 1] |= (self[i] & bm) << cbs - r[i - ds] = self[i] >> bs - } - if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs - r.t = self.t - ds - r.clamp() -} - -// (protected) r = this - a -function bnpSubTo(a, r) { - var self = this - var i = 0, - c = 0, - m = Math.min(a.t, self.t) - while (i < m) { - c += self[i] - a[i] - r[i++] = c & self.DM - c >>= self.DB - } - if (a.t < self.t) { - c -= a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c -= a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c -= a.s - } - r.s = (c < 0) ? -1 : 0 - if (c < -1) r[i++] = self.DV + c - else if (c > 0) r[i++] = c - r.t = i - r.clamp() -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs() - var i = x.t - r.t = i + y.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) - r.s = 0 - r.clamp() - if (this.s != a.s) BigInteger.ZERO.subTo(r, r) -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs() - var i = r.t = 2 * x.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1) - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV - r[i + x.t + 1] = 1 - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) - r.s = 0 - r.clamp() -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m, q, r) { - var self = this - var pm = m.abs() - if (pm.t <= 0) return - var pt = self.abs() - if (pt.t < pm.t) { - if (q != null) q.fromInt(0) - if (r != null) self.copyTo(r) - return - } - if (r == null) r = new BigInteger() - var y = new BigInteger(), - ts = self.s, - ms = m.s - var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y) - pt.lShiftTo(nsh, r) - } else { - pm.copyTo(y) - pt.copyTo(r) - } - var ys = y.t - var y0 = y[ys - 1] - if (y0 == 0) return - var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) - var d1 = self.FV / yt, - d2 = (1 << self.F1) / yt, - e = 1 << self.F2 - var i = r.t, - j = i - ys, - t = (q == null) ? new BigInteger() : q - y.dlShiftTo(j, t) - if (r.compareTo(t) >= 0) { - r[r.t++] = 1 - r.subTo(t, r) - } - BigInteger.ONE.dlShiftTo(ys, t) - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0 - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t) - r.subTo(t, r) - while (r[i] < --qd) r.subTo(t, r) - } - } - if (q != null) { - r.drShiftTo(ys, q) - if (ts != ms) BigInteger.ZERO.subTo(q, q) - } - r.t = ys - r.clamp() - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r) -} - -// (public) this mod a -function bnMod(a) { - var r = new BigInteger() - this.abs() - .divRemTo(a, null, r) - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) - return r -} - -// Modular reduction using "classic" algorithm -function Classic(m) { - this.m = m -} - -function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) - else return x -} - -function cRevert(x) { - return x -} - -function cReduce(x) { - x.divRemTo(this.m, null, x) -} - -function cMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -function cSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -Classic.prototype.convert = cConvert -Classic.prototype.revert = cRevert -Classic.prototype.reduce = cReduce -Classic.prototype.mulTo = cMulTo -Classic.prototype.sqrTo = cSqrTo - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if (this.t < 1) return 0 - var x = this[0] - if ((x & 1) == 0) return 0 - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m - this.mp = m.invDigit() - this.mpl = this.mp & 0x7fff - this.mph = this.mp >> 15 - this.um = (1 << (m.DB - 15)) - 1 - this.mt2 = 2 * m.t -} - -// xR mod m -function montConvert(x) { - var r = new BigInteger() - x.abs() - .dlShiftTo(this.m.t, r) - r.divRemTo(this.m, null, r) - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) - return r -} - -// x/R mod m -function montRevert(x) { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0 - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM - // use am to combine the multiply-shift-add into one call - j = i + this.m.t - x[j] += this.m.am(0, u0, x, i, 0, this.m.t) - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV - x[++j]++ - } - } - x.clamp() - x.drShiftTo(this.m.t, x) - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = "xy/R mod m"; x,y != r -function montMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Montgomery.prototype.convert = montConvert -Montgomery.prototype.revert = montRevert -Montgomery.prototype.reduce = montReduce -Montgomery.prototype.mulTo = montMulTo -Montgomery.prototype.sqrTo = montSqrTo - -// (protected) true iff this is even -function bnpIsEven() { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 -} - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE - var r = new BigInteger(), - r2 = new BigInteger(), - g = z.convert(this), - i = nbits(e) - 1 - g.copyTo(r) - while (--i >= 0) { - z.sqrTo(r, r2) - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) - else { - var t = r - r = r2 - r2 = t - } - } - return z.revert(r) -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e, m) { - var z - if (e < 256 || m.isEven()) z = new Classic(m) - else z = new Montgomery(m) - return this.exp(e, z) -} - -// protected -proto.copyTo = bnpCopyTo -proto.fromInt = bnpFromInt -proto.fromString = bnpFromString -proto.clamp = bnpClamp -proto.dlShiftTo = bnpDLShiftTo -proto.drShiftTo = bnpDRShiftTo -proto.lShiftTo = bnpLShiftTo -proto.rShiftTo = bnpRShiftTo -proto.subTo = bnpSubTo -proto.multiplyTo = bnpMultiplyTo -proto.squareTo = bnpSquareTo -proto.divRemTo = bnpDivRemTo -proto.invDigit = bnpInvDigit -proto.isEven = bnpIsEven -proto.exp = bnpExp - -// public -proto.toString = bnToString -proto.negate = bnNegate -proto.abs = bnAbs -proto.compareTo = bnCompareTo -proto.bitLength = bnBitLength -proto.byteLength = bnByteLength -proto.mod = bnMod -proto.modPowInt = bnModPowInt - -// (public) -function bnClone() { - var r = new BigInteger() - this.copyTo(r) - return r -} - -// (public) return value as integer -function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV - else if (this.t == 0) return -1 - } else if (this.t == 1) return this[0] - else if (this.t == 0) return 0 - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] -} - -// (public) return value as byte -function bnByteValue() { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24 -} - -// (public) return value as short (assumes DB>=16) -function bnShortValue() { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16 -} - -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)) -} - -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if (this.s < 0) return -1 - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 - else return 1 -} - -// (protected) convert to radix string -function bnpToRadix(b) { - if (b == null) b = 10 - if (this.signum() == 0 || b < 2 || b > 36) return "0" - var cs = this.chunkSize(b) - var a = Math.pow(b, cs) - var d = nbv(a), - y = new BigInteger(), - z = new BigInteger(), - r = "" - this.divRemTo(d, y, z) - while (y.signum() > 0) { - r = (a + z.intValue()) - .toString(b) - .substr(1) + r - y.divRemTo(d, y, z) - } - return z.intValue() - .toString(b) + r -} - -// (protected) convert from radix string -function bnpFromRadix(s, b) { - var self = this - self.fromInt(0) - if (b == null) b = 10 - var cs = self.chunkSize(b) - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0 - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-" && self.signum() == 0) mi = true - continue - } - w = b * w + x - if (++j >= cs) { - self.dMultiply(d) - self.dAddOffset(w, 0) - j = 0 - w = 0 - } - } - if (j > 0) { - self.dMultiply(Math.pow(b, j)) - self.dAddOffset(w, 0) - } - if (mi) BigInteger.ZERO.subTo(self, self) -} - -// (protected) alternate constructor -function bnpFromNumber(a, b, c) { - var self = this - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) self.fromInt(1) - else { - self.fromNumber(a, c) - if (!self.testBit(a - 1)) // force MSB set - self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) - if (self.isEven()) self.dAddOffset(1, 0); // force odd - while (!self.isProbablePrime(b)) { - self.dAddOffset(2, 0) - if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7 - x.length = (a >> 3) + 1 - b.nextBytes(x) - if (t > 0) x[0] &= ((1 << t) - 1) - else x[0] = 0 - self.fromString(x, 256) - } -} - -// (public) convert to bigendian byte array -function bnToByteArray() { - var self = this - var i = self.t, - r = new Array() - r[0] = self.s - var p = self.DB - (i * self.DB) % 8, - d, k = 0 - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) - r[k++] = d | (self.s << (self.DB - p)) - while (i >= 0) { - if (p < 8) { - d = (self[i] & ((1 << p) - 1)) << (8 - p) - d |= self[--i] >> (p += self.DB - 8) - } else { - d = (self[i] >> (p -= 8)) & 0xff - if (p <= 0) { - p += self.DB - --i - } - } - if ((d & 0x80) != 0) d |= -256 - if (k === 0 && (self.s & 0x80) != (d & 0x80))++k - if (k > 0 || d != self.s) r[k++] = d - } - } - return r -} - -function bnEquals(a) { - return (this.compareTo(a) == 0) -} - -function bnMin(a) { - return (this.compareTo(a) < 0) ? this : a -} - -function bnMax(a) { - return (this.compareTo(a) > 0) ? this : a -} - -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a, op, r) { - var self = this - var i, f, m = Math.min(a.t, self.t) - for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) - if (a.t < self.t) { - f = a.s & self.DM - for (i = m; i < self.t; ++i) r[i] = op(self[i], f) - r.t = self.t - } else { - f = self.s & self.DM - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) - r.t = a.t - } - r.s = op(self.s, a.s) - r.clamp() -} - -// (public) this & a -function op_and(x, y) { - return x & y -} - -function bnAnd(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_and, r) - return r -} - -// (public) this | a -function op_or(x, y) { - return x | y -} - -function bnOr(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_or, r) - return r -} - -// (public) this ^ a -function op_xor(x, y) { - return x ^ y -} - -function bnXor(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_xor, r) - return r -} - -// (public) this & ~a -function op_andnot(x, y) { - return x & ~y -} - -function bnAndNot(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_andnot, r) - return r -} - -// (public) ~this -function bnNot() { - var r = new BigInteger() - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] - r.t = this.t - r.s = ~this.s - return r -} - -// (public) this << n -function bnShiftLeft(n) { - var r = new BigInteger() - if (n < 0) this.rShiftTo(-n, r) - else this.lShiftTo(n, r) - return r -} - -// (public) this >> n -function bnShiftRight(n) { - var r = new BigInteger() - if (n < 0) this.lShiftTo(-n, r) - else this.rShiftTo(n, r) - return r -} - -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if (x == 0) return -1 - var r = 0 - if ((x & 0xffff) == 0) { - x >>= 16 - r += 16 - } - if ((x & 0xff) == 0) { - x >>= 8 - r += 8 - } - if ((x & 0xf) == 0) { - x >>= 4 - r += 4 - } - if ((x & 3) == 0) { - x >>= 2 - r += 2 - } - if ((x & 1) == 0)++r - return r -} - -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]) - if (this.s < 0) return this.t * this.DB - return -1 -} - -// return number of 1 bits in x -function cbit(x) { - var r = 0 - while (x != 0) { - x &= x - 1 - ++r - } - return r -} - -// (public) return number of set bits -function bnBitCount() { - var r = 0, - x = this.s & this.DM - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) - return r -} - -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n / this.DB) - if (j >= this.t) return (this.s != 0) - return ((this[j] & (1 << (n % this.DB))) != 0) -} - -// (protected) this op (1<>= self.DB - } - if (a.t < self.t) { - c += a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c += a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += a.s - } - r.s = (c < 0) ? -1 : 0 - if (c > 0) r[i++] = c - else if (c < -1) r[i++] = self.DV + c - r.t = i - r.clamp() -} - -// (public) this + a -function bnAdd(a) { - var r = new BigInteger() - this.addTo(a, r) - return r -} - -// (public) this - a -function bnSubtract(a) { - var r = new BigInteger() - this.subTo(a, r) - return r -} - -// (public) this * a -function bnMultiply(a) { - var r = new BigInteger() - this.multiplyTo(a, r) - return r -} - -// (public) this^2 -function bnSquare() { - var r = new BigInteger() - this.squareTo(r) - return r -} - -// (public) this / a -function bnDivide(a) { - var r = new BigInteger() - this.divRemTo(a, r, null) - return r -} - -// (public) this % a -function bnRemainder(a) { - var r = new BigInteger() - this.divRemTo(a, null, r) - return r -} - -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = new BigInteger(), - r = new BigInteger() - this.divRemTo(a, q, r) - return new Array(q, r) -} - -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) - ++this.t - this.clamp() -} - -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n, w) { - if (n == 0) return - while (this.t <= w) this[this.t++] = 0 - this[w] += n - while (this[w] >= this.DV) { - this[w] -= this.DV - if (++w >= this.t) this[this.t++] = 0 - ++this[w] - } -} - -// A "null" reducer -function NullExp() {} - -function nNop(x) { - return x -} - -function nMulTo(x, y, r) { - x.multiplyTo(y, r) -} - -function nSqrTo(x, r) { - x.squareTo(r) -} - -NullExp.prototype.convert = nNop -NullExp.prototype.revert = nNop -NullExp.prototype.mulTo = nMulTo -NullExp.prototype.sqrTo = nSqrTo - -// (public) this^e -function bnPow(e) { - return this.exp(e, new NullExp()) -} - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n) - r.s = 0; // assumes a,this >= 0 - r.t = i - while (i > 0) r[--i] = 0 - var j - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) - r.clamp() -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a, n, r) { - --n - var i = r.t = this.t + a.t - n - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0 - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) - r.clamp() - r.drShiftTo(1, r) -} - -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = new BigInteger() - this.q3 = new BigInteger() - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) - this.mu = this.r2.divide(m) - this.m = m -} - -function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) - else if (x.compareTo(this.m) < 0) return x - else { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r - } -} - -function barrettRevert(x) { - return x -} - -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - var self = this - x.drShiftTo(self.m.t - 1, self.r2) - if (x.t > self.m.t + 1) { - x.t = self.m.t + 1 - x.clamp() - } - self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) - self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) - while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) - x.subTo(self.r2, x) - while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) -} - -// r = x^2 mod m; x != r -function barrettSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = x*y mod m; x,y != r -function barrettMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Barrett.prototype.convert = barrettConvert -Barrett.prototype.revert = barrettRevert -Barrett.prototype.reduce = barrettReduce -Barrett.prototype.mulTo = barrettMulTo -Barrett.prototype.sqrTo = barrettSqrTo - -// (public) this^e % m (HAC 14.85) -function bnModPow(e, m) { - var i = e.bitLength(), - k, r = nbv(1), - z - if (i <= 0) return r - else if (i < 18) k = 1 - else if (i < 48) k = 3 - else if (i < 144) k = 4 - else if (i < 768) k = 5 - else k = 6 - if (i < 8) - z = new Classic(m) - else if (m.isEven()) - z = new Barrett(m) - else - z = new Montgomery(m) - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1 - g[1] = z.convert(this) - if (k > 1) { - var g2 = new BigInteger() - z.sqrTo(g[1], g2) - while (n <= km) { - g[n] = new BigInteger() - z.mulTo(g2, g[n - 2], g[n]) - n += 2 - } - } - - var j = e.t - 1, - w, is1 = true, - r2 = new BigInteger(), - t - i = nbits(e[j]) - 1 - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) - } - - n = k - while ((w & 1) == 0) { - w >>= 1 - --n - } - if ((i -= n) < 0) { - i += this.DB - --j - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r) - is1 = false - } else { - while (n > 1) { - z.sqrTo(r, r2) - z.sqrTo(r2, r) - n -= 2 - } - if (n > 0) z.sqrTo(r, r2) - else { - t = r - r = r2 - r2 = t - } - z.mulTo(r2, g[w], r) - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2) - t = r - r = r2 - r2 = t - if (--i < 0) { - i = this.DB - 1 - --j - } - } - } - return z.revert(r) -} - -// (public) gcd(this,a) (HAC 14.54) -function bnGCD(a) { - var x = (this.s < 0) ? this.negate() : this.clone() - var y = (a.s < 0) ? a.negate() : a.clone() - if (x.compareTo(y) < 0) { - var t = x - x = y - y = t - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit() - if (g < 0) return x - if (i < g) g = i - if (g > 0) { - x.rShiftTo(g, x) - y.rShiftTo(g, y) - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) - if (x.compareTo(y) >= 0) { - x.subTo(y, x) - x.rShiftTo(1, x) - } else { - y.subTo(x, y) - y.rShiftTo(1, y) - } - } - if (g > 0) y.lShiftTo(g, y) - return y -} - -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if (n <= 0) return 0 - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0 - if (this.t > 0) - if (d == 0) r = this[0] % n - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n - return r -} - -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven() - if (this.signum() === 0) throw new Error('division by zero') - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO - var u = m.clone(), - v = this.clone() - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1) - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u) - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a) - b.subTo(m, b) - } - a.rShiftTo(1, a) - } else if (!b.isEven()) b.subTo(m, b) - b.rShiftTo(1, b) - } - while (v.isEven()) { - v.rShiftTo(1, v) - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c) - d.subTo(m, d) - } - c.rShiftTo(1, c) - } else if (!d.isEven()) d.subTo(m, d) - d.rShiftTo(1, d) - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u) - if (ac) a.subTo(c, a) - b.subTo(d, b) - } else { - v.subTo(u, v) - if (ac) c.subTo(a, c) - d.subTo(b, d) - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO - while (d.compareTo(m) >= 0) d.subTo(m, d) - while (d.signum() < 0) d.addTo(m, d) - return d -} - -var lowprimes = [ - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, - 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, - 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, - 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, - 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, - 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 -] - -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] - -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs() - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true - return false - } - if (x.isEven()) return false - i = 1 - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1 - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] - m = x.modInt(m) - while (i < j) if (m % lowprimes[i++] == 0) return false - } - return x.millerRabin(t) -} - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE) - var k = n1.getLowestSetBit() - if (k <= 0) return false - var r = n1.shiftRight(k) - t = (t + 1) >> 1 - if (t > lowprimes.length) t = lowprimes.length - var a = new BigInteger(null) - var j, bases = [] - for (var i = 0; i < t; ++i) { - for (;;) { - j = lowprimes[Math.floor(Math.random() * lowprimes.length)] - if (bases.indexOf(j) == -1) break - } - bases.push(j) - a.fromInt(j) - var y = a.modPow(r, this) - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1 - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this) - if (y.compareTo(BigInteger.ONE) == 0) return false - } - if (y.compareTo(n1) != 0) return false - } - } - return true -} - -// protected -proto.chunkSize = bnpChunkSize -proto.toRadix = bnpToRadix -proto.fromRadix = bnpFromRadix -proto.fromNumber = bnpFromNumber -proto.bitwiseTo = bnpBitwiseTo -proto.changeBit = bnpChangeBit -proto.addTo = bnpAddTo -proto.dMultiply = bnpDMultiply -proto.dAddOffset = bnpDAddOffset -proto.multiplyLowerTo = bnpMultiplyLowerTo -proto.multiplyUpperTo = bnpMultiplyUpperTo -proto.modInt = bnpModInt -proto.millerRabin = bnpMillerRabin - -// public -proto.clone = bnClone -proto.intValue = bnIntValue -proto.byteValue = bnByteValue -proto.shortValue = bnShortValue -proto.signum = bnSigNum -proto.toByteArray = bnToByteArray -proto.equals = bnEquals -proto.min = bnMin -proto.max = bnMax -proto.and = bnAnd -proto.or = bnOr -proto.xor = bnXor -proto.andNot = bnAndNot -proto.not = bnNot -proto.shiftLeft = bnShiftLeft -proto.shiftRight = bnShiftRight -proto.getLowestSetBit = bnGetLowestSetBit -proto.bitCount = bnBitCount -proto.testBit = bnTestBit -proto.setBit = bnSetBit -proto.clearBit = bnClearBit -proto.flipBit = bnFlipBit -proto.add = bnAdd -proto.subtract = bnSubtract -proto.multiply = bnMultiply -proto.divide = bnDivide -proto.remainder = bnRemainder -proto.divideAndRemainder = bnDivideAndRemainder -proto.modPow = bnModPow -proto.modInverse = bnModInverse -proto.pow = bnPow -proto.gcd = bnGCD -proto.isProbablePrime = bnIsProbablePrime - -// JSBN-specific extension -proto.square = bnSquare - -// constants -BigInteger.ZERO = nbv(0) -BigInteger.ONE = nbv(1) -BigInteger.valueOf = nbv - -module.exports = BigInteger - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - -var assert = __webpack_require__(4) -var BigInteger = __webpack_require__(16) - -var Point = __webpack_require__(149) - -function Curve (p, a, b, Gx, Gy, n, h) { - this.p = p - this.a = a - this.b = b - this.G = Point.fromAffine(this, Gx, Gy) - this.n = n - this.h = h - - this.infinity = new Point(this, null, null, BigInteger.ZERO) - - // result caching - this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) - - // determine size of p in bytes - this.pLength = Math.floor((this.p.bitLength() + 7) / 8) -} - -Curve.prototype.pointFromX = function (isOdd, x) { - var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) - var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves - - var y = beta - if (beta.isEven() ^ !isOdd) { - y = this.p.subtract(y) // -y % p - } - - return Point.fromAffine(this, x, y) -} - -Curve.prototype.isInfinity = function (Q) { - if (Q === this.infinity) return true - - return Q.z.signum() === 0 && Q.y.signum() !== 0 -} - -Curve.prototype.isOnCurve = function (Q) { - if (this.isInfinity(Q)) return true - - var x = Q.affineX - var y = Q.affineY - var a = this.a - var b = this.b - var p = this.p - - // Check that xQ and yQ are integers in the interval [0, p - 1] - if (x.signum() < 0 || x.compareTo(p) >= 0) return false - if (y.signum() < 0 || y.compareTo(p) >= 0) return false - - // and check that y^2 = x^3 + ax + b (mod p) - var lhs = y.square().mod(p) - var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) - return lhs.equals(rhs) -} - -/** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ -Curve.prototype.validate = function (Q) { - // Check Q != O - assert(!this.isInfinity(Q), 'Point is at infinity') - assert(this.isOnCurve(Q), 'Point is not on the curve') - - // Check nQ = O (where Q is a scalar multiple of G) - var nQ = Q.multiply(this.n) - assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') - - return true -} - -module.exports = Curve - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var Buffer = __webpack_require__(2).Buffer -var inherits = __webpack_require__(1) -var HashBase = __webpack_require__(148) - -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 - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - -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 = __webpack_require__(281) -exports.sha1 = __webpack_require__(282) -exports.sha224 = __webpack_require__(283) -exports.sha256 = __webpack_require__(154) -exports.sha384 = __webpack_require__(284) -exports.sha512 = __webpack_require__(155) - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - -/** - * 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 = __webpack_require__(1) -var Hash = __webpack_require__(34) -var Buffer = __webpack_require__(0).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 - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - -var inherits = __webpack_require__(1) -var Hash = __webpack_require__(34) -var Buffer = __webpack_require__(0).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 - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var ecdsa = __webpack_require__(291); -var hash = __webpack_require__(25); -var curve = __webpack_require__(93).getCurveByName('secp256k1'); -var assert = __webpack_require__(4); -var BigInteger = __webpack_require__(16); -var keyUtils = __webpack_require__(46); -var PublicKey = __webpack_require__(44); -var PrivateKey = __webpack_require__(65); - -module.exports = Signature; - -function Signature(r, s, i) { - assert.equal(r != null, true, 'Missing parameter'); - assert.equal(s != null, true, 'Missing parameter'); - assert.equal(i != null, true, 'Missing parameter'); - - /** - Verify signed data. - @arg {String|Buffer} data - full data - @arg {pubkey|PublicKey} pubkey - EOSKey.. - @arg {String} [encoding = 'utf8'] - data encoding (if data is a string) - @return {boolean} - */ - function verify(data, pubkey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - return verifyHash(data, pubkey); - } - - /** - Verify a buffer of exactally 32 bytes in size (sha256(text)) - @arg {String|Buffer} dataSha256 - 32 byte buffer or string - @arg {String|PublicKey} pubkey - EOSKey.. - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - @return {boolean} - */ - function verifyHash(dataSha256, pubkey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 bytes required"); - - var publicKey = PublicKey(pubkey); - assert(publicKey, 'pubkey required'); - - return ecdsa.verify(curve, dataSha256, { r: r, s: s }, publicKey.Q); - }; - - /** @deprecated - Verify hex data by converting to a buffer then hashing. - @return {boolean} - */ - function verifyHex(hex, pubkey) { - console.log('Deprecated: use verify(data, pubkey, "hex")'); - - var buf = Buffer.from(hex, 'hex'); - return verify(buf, pubkey); - }; - - /** - Recover the public key used to create this signature using full data. - @arg {String|Buffer} data - full data - @arg {String} [encoding = 'utf8'] - data encoding (if string) - @return {PublicKey} - */ - function recover(data) { - var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - - return recoverHash(data); - }; - - /** - @arg {String|Buffer} dataSha256 - sha256 hash 32 byte buffer or hex string - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - @return {PublicKey} - */ - function recoverHash(dataSha256) { - var encoding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) { - throw new Error("dataSha256: 32 byte String or buffer requred"); - } - - var e = BigInteger.fromBuffer(dataSha256); - var i2 = i; - i2 -= 27; - i2 = i2 & 3; - var Q = ecdsa.recoverPubKey(curve, e, { r: r, s: s, i: i }, i2); - return PublicKey.fromPoint(Q); - }; - - function toBuffer() { - var buf; - buf = new Buffer(65); - buf.writeUInt8(i, 0); - r.toBuffer(32).copy(buf, 1); - s.toBuffer(32).copy(buf, 33); - return buf; - }; - - function toHex() { - return toBuffer().toString("hex"); - }; - - var signatureCache = void 0; - - function toString() { - if (signatureCache) { - return signatureCache; - } - signatureCache = 'SIG_K1_' + keyUtils.checkEncode(toBuffer(), 'K1'); - return signatureCache; - } - - return { - r: r, s: s, i: i, - toBuffer: toBuffer, - verify: verify, - verifyHash: verifyHash, - verifyHex: verifyHex, // deprecated - recover: recover, - recoverHash: recoverHash, - toHex: toHex, - toString: toString, - - /** @deprecated use verify (same arguments and return) */ - verifyBuffer: function verifyBuffer() { - console.log('Deprecated: use signature.verify instead (same arguments)'); - return verify.apply(undefined, arguments); - }, - - /** @deprecated use recover (same arguments and return) */ - recoverPublicKey: function recoverPublicKey() { - console.log('Deprecated: use signature.recover instead (same arguments)'); - return recover.apply(undefined, arguments); - }, - - /** @deprecated use recoverHash (same arguments and return) */ - recoverPublicKeyFromBuffer: function recoverPublicKeyFromBuffer() { - console.log('Deprecated: use signature.recoverHash instead (same arguments)'); - return recoverHash.apply(undefined, arguments); - } - }; -} - -/** - Hash and sign arbitrary data. - - @arg {string|Buffer} data - full data - @arg {wif|PrivateKey} privateKey - @arg {String} [encoding = 'utf8'] - data encoding (if string) - - @return {Signature} -*/ -Signature.sign = function (data, privateKey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'utf8'; - - if (typeof data === 'string') { - data = Buffer.from(data, encoding); - } - assert(Buffer.isBuffer(data), 'data is a required String or Buffer'); - data = hash.sha256(data); - return Signature.signHash(data, privateKey); -}; - -/** - Sign a buffer of exactally 32 bytes in size (sha256(text)) - - @arg {string|Buffer} dataSha256 - 32 byte buffer or string - @arg {wif|PrivateKey} privateKey - @arg {String} [encoding = 'hex'] - dataSha256 encoding (if string) - - @return {Signature} -*/ -Signature.signHash = function (dataSha256, privateKey) { - var encoding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'hex'; - - if (typeof dataSha256 === 'string') { - dataSha256 = Buffer.from(dataSha256, encoding); - } - if (dataSha256.length !== 32 || !Buffer.isBuffer(dataSha256)) throw new Error("dataSha256: 32 byte buffer requred"); - - privateKey = PrivateKey(privateKey); - assert(privateKey, 'privateKey required'); - - var der, e, ecsignature, i, lenR, lenS, nonce; - i = null; - nonce = 0; - e = BigInteger.fromBuffer(dataSha256); - while (true) { - ecsignature = ecdsa.sign(curve, dataSha256, privateKey.d, nonce++); - der = ecsignature.toDER(); - lenR = der[3]; - lenS = der[5 + lenR]; - if (lenR === 32 && lenS === 32) { - i = ecdsa.calcPubKeyRecoveryParam(curve, e, ecsignature, privateKey.toPublic().Q); - i += 4; // compressed - i += 27; // compact // 24 or 27 :( forcing odd-y 2nd key candidate) - break; - } - if (nonce % 10 === 0) { - console.log("WARN: " + nonce + " attempts to find canonical signature"); - } - } - return Signature(ecsignature.r, ecsignature.s, i); -}; - -Signature.fromBuffer = function (buf) { - var i, r, s; - assert(Buffer.isBuffer(buf), 'Buffer is required'); - assert.equal(buf.length, 65, 'Invalid signature length'); - i = buf.readUInt8(0); - assert.equal(i - 27, i - 27 & 7, 'Invalid signature parameter'); - r = BigInteger.fromBuffer(buf.slice(1, 33)); - s = BigInteger.fromBuffer(buf.slice(33)); - return Signature(r, s, i); -}; - -Signature.fromHex = function (hex) { - return Signature.fromBuffer(Buffer.from(hex, "hex")); -}; - -/** - @arg {string} signature - like SIG_K1_base58signature.. - @return {Signature} or `null` (invalid) -*/ -Signature.fromString = function (signature) { - try { - return Signature.fromStringOrThrow(signature); - } catch (e) { - return null; - } -}; - -/** - @arg {string} signature - like SIG_K1_base58signature.. - @throws {Error} invalid - @return {Signature} -*/ -Signature.fromStringOrThrow = function (signature) { - assert.equal(typeof signature === 'undefined' ? 'undefined' : _typeof(signature), 'string', 'signature'); - var match = signature.match(/^SIG_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/); - assert(match != null && match.length === 3, 'Expecting signature like: SIG_K1_base58signature..'); - - var _match = _slicedToArray(match, 3), - keyType = _match[1], - keyString = _match[2]; - - assert.equal(keyType, 'K1', 'K1 signature expected'); - return Signature.fromBuffer(keyUtils.checkDecode(keyString, keyType)); -}; - -/** - @arg {String|Signature} o - hex string - @return {Signature} -*/ -Signature.from = function (o) { - var signature = o ? o.r && o.s && o.i ? o : typeof o === 'string' && o.length === 130 ? Signature.fromHex(o) : typeof o === 'string' && o.length !== 130 ? Signature.fromStringOrThrow(o) : Buffer.isBuffer(o) ? Signature.fromBuffer(o) : null : o; /*null or undefined*/ - - if (!signature) { - throw new TypeError('signature should be a hex string or buffer'); - } - return signature; -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -module.exports = function enforce(type, value) { - // Copied from https://github.com/bitcoinjs/bitcoinjs-lib - switch (type) { - case 'Array': - { - if (Array.isArray(value)) return; - break; - } - - case 'Boolean': - { - if (typeof value === 'boolean') return; - break; - } - - case 'Buffer': - { - if (Buffer.isBuffer(value)) return; - break; - } - - case 'Number': - { - if (typeof value === 'number') return; - break; - } - - case 'String': - { - if (typeof value === 'string') return; - break; - } - - default: - { - if (getName(value.constructor) === getName(type)) return; - } - } - - throw new TypeError('Expected ' + (getName(type) || type) + ', got ' + value); -}; - -function getName(fn) { - // Why not fn.name: https://kangax.github.io/compat-table/es6/#function_name_property - var match = fn.toString().match(/function (.*?)\(/); - return match ? match[1] : null; -} -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var api = __webpack_require__(299); -var apiGen = __webpack_require__(302); -var processArgs = __webpack_require__(160); - -var EosApi = function EosApi(config) { - return apiGen('v1', api, config); -}; - -Object.assign(EosApi, { - processArgs: processArgs, - api: api, - - /** @deprecated */ - Testnet: function Testnet(config) { - console.error('deprecated, change EosApi.Testnet(..) to just EosApi(..)'); - return EosApi(config); - }, - - /** @deprecated */ - Localnet: function Localnet(config) { - console.error('deprecated, change EosApi.Localnet(..) to just EosApi(..)'); - return EosApi(config); - } -}); - -module.exports = EosApi; - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - -// the whatwg-fetch polyfill installs the fetch() function -// on the global object (window or self) -// -// Return that as the export for use in Webpack, Browserify etc. -__webpack_require__(303); -module.exports = self.fetch.bind(self); - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -module.exports = processArgs; - -/** - @typedef {object} processedArgs - Normalized object containing arguments, and - a chained promise and a callback. - - @property {object} params - normalized args only, parameters by name, no extra options or callback. - - @property {object} options - non-null or non-undefined return value from invocation of - optionsFormatter(optionsParam). - - @property {function} callback -chained to optional callback provided in args. Resolves - or rejects returnPromise. - - @property {Promise} returnPromise - promise is returned when no callback is provided in - args[args.length - 1]. Undefined when a callback is provided. -*/ -/** - Convert args array or object into a normalized value object. Suppoorts extra - options and(or) callback parameters. - - Per the Promise API feature promisifyAll (see also sb-promisify), the callback - (if provided) must always be last. - - @arg {Array|object} args - User-provided parameter object or array of parameters - @arg {Array} defParams - Names for the parameters. - @arg {string} methodName - for error reporting - @arg {function} [optionsFormatter(extraParam) = null] - optional callback used if an - extra optional (non-callback) parameter is provided. - - - @return {processedArgs} processedArgs - @throws TypeError - when parameter count is not exact (after adjusting for - options and callback) - - @example api.processArgs(args, ['account'], 'contract', optionsFormatter) -*/ -function processArgs(args, defParams) { - var methodName = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'method'; - var optionsFormatter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; - - var params = {}; - var options = {}; - - var expectedArgCount = defParams.length; - - // Extra callback argument? Last per promisifyAll standard. - var callbackArg = void 0; - if (typeof args[args.length - 1] === 'function') { - callbackArg = args[args.length - 1]; - args = args.slice(0, args.length - 1); - } - - var callback = void 0; - var returnPromise = void 0; - if (callbackArg) { - callback = function callback(err, result) { - if (err) { - callbackArg(err); - } else { - callbackArg(null, result); - } - }; - } else { - returnPromise = new Promise(function (resolve, reject) { - callback = function callback(err, result) { - if (err) { - reject(err); - } else { - resolve(result); - } - }; - }); - } - - // Look for the options parameter (after potential callback was removed) - if (typeof optionsFormatter === 'function' && args.length > 0 && (_typeof(args[0]) === 'object' && args.length === 2 || args.length === expectedArgCount + 1)) { - //An extra options argument - options = optionsFormatter(args[args.length - 1]); - if (options != null) { - // It is valid, remove it to avoid parameter count an error below - args = args.slice(0, args.length - 1); - } - } - - // Parameteters (args) can be ordered or an object - if (args.length === 1 && _typeof(args[0]) === 'object') { - params = args[0]; - } else { - // give ordered paramaters names - - if (args.length > expectedArgCount) { - // console.log('typeof defParams[expectedArgCount]', args) - throw new TypeError(methodName + ' is expecting ' + expectedArgCount + ' parameters but ' + args.length + ' where provided'); - } - - // convert ordered parameters into a value object by parameter name - var pos = 0; - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = defParams[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var defParam = _step.value; - - params[defParam] = args[pos]; - pos++; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - return { params: params, options: options, callback: callback, returnPromise: returnPromise }; -} - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var schema = Object.assign({}, __webpack_require__(318), __webpack_require__(319), __webpack_require__(320)); - -module.exports = schema; - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var _slicedToArray2 = __webpack_require__(96); - -var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); - -var _typeof2 = __webpack_require__(41); - -var _typeof3 = _interopRequireDefault(_typeof2); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var assert = __webpack_require__(4); - -var _require = __webpack_require__(33), - Long = _require.Long; - -module.exports = { - ULong: ULong, - isName: isName, - encodeName: encodeName, // encode human readable name to uint64 (number string) - decodeName: decodeName, // decode from uint64 to human readable - encodeNameHex: function encodeNameHex(name) { - return Long.fromString(encodeName(name), true).toString(16); - }, - decodeNameHex: function decodeNameHex(hex) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - return decodeName(Long.fromString(hex, true, 16).toString(), littleEndian); - }, - DecimalString: DecimalString, - DecimalPad: DecimalPad, - DecimalImply: DecimalImply, - DecimalUnimply: DecimalUnimply, - printAsset: printAsset, - parseAsset: parseAsset - - /** @private */ -};var signed = function signed(fn) { - return function () {}; -}; - -function ULong(value) { - var unsigned = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var radix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10; - - if (typeof value === 'number') { - // Some JSON libs use numbers for values under 53 bits or strings for larger. - // Accomidate but double-check it.. - if (value > Number.MAX_SAFE_INTEGER) throw new TypeError('value parameter overflow'); - - value = Long.fromString(String(value), unsigned, radix); - } else if (typeof value === 'string') { - value = Long.fromString(value, unsigned, radix); - } else if (!Long.isLong(value)) { - throw new TypeError('value parameter is a requied Long, Number or String'); - } - return value; -} - -function isName(str, err) { - try { - encodeName(str); - return true; - } catch (error) { - if (err) { - err(error); - } - return false; - } -} - -var charmap = '.12345abcdefghijklmnopqrstuvwxyz'; -var charidx = function charidx(ch) { - var idx = charmap.indexOf(ch); - if (idx === -1) throw new TypeError('Invalid character: \'' + ch + '\''); - - return idx; -}; - -/** Original Name encode and decode logic is in github.com/eosio/eos native.hpp */ - -/** - Encode a name (a base32 string) to a number. - - For performance reasons, the blockchain uses the numerical encoding of strings - for very common types like account names. - - @see types.hpp string_to_name - - @arg {string} name - A string to encode, up to 12 characters long. - @arg {string} [littleEndian = true] - Little or Bigendian encoding - - @return {string} - compressed string (from name arg). A string is - always used because a number could exceed JavaScript's 52 bit limit. -*/ -function encodeName(name) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - if (typeof name !== 'string') throw new TypeError('name parameter is a required string'); - - if (name.length > 12) throw new TypeError('A name can be up to 12 characters long'); - - var bitstr = ''; - for (var i = 0; i <= 12; i++) { - // process all 64 bits (even if name is short) - var c = i < name.length ? charidx(name[i]) : 0; - var bitlen = i < 12 ? 5 : 4; - var bits = Number(c).toString(2); - if (bits.length > bitlen) { - throw new TypeError('Invalid name ' + name); - } - bits = '0'.repeat(bitlen - bits.length) + bits; - bitstr += bits; - } - - var value = Long.fromString(bitstr, true, 2); - - // convert to LITTLE_ENDIAN - var leHex = ''; - var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = bytes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var b = _step.value; - - var n = Number(b).toString(16); - leHex += (n.length === 1 ? '0' : '') + n; - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var ulName = Long.fromString(leHex, true, 16).toString(); - - // console.log('encodeName', name, value.toString(), ulName.toString(), JSON.stringify(bitstr.split(/(.....)/).slice(1))) - - return ulName.toString(); -} - -/** - @arg {Long|String|number} value uint64 - @arg {string} [littleEndian = true] - Little or Bigendian encoding - - @return {string} -*/ -function decodeName(value) { - var littleEndian = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - value = ULong(value); - - // convert from LITTLE_ENDIAN - var beHex = ''; - var bytes = littleEndian ? value.toBytesLE() : value.toBytesBE(); - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = bytes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var b = _step2.value; - - var n = Number(b).toString(16); - beHex += (n.length === 1 ? '0' : '') + n; - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - beHex += '0'.repeat(16 - beHex.length); - - var fiveBits = Long.fromNumber(0x1f, true); - var fourBits = Long.fromNumber(0x0f, true); - var beValue = Long.fromString(beHex, true, 16); - - var str = ''; - var tmp = beValue; - - for (var i = 0; i <= 12; i++) { - var c = charmap[tmp.and(i === 0 ? fourBits : fiveBits)]; - str = c + str; - tmp = tmp.shiftRight(i === 0 ? 4 : 5); - } - str = str.replace(/\.+$/, ''); // remove trailing dots (all of them) - - // console.log('decodeName', str, beValue.toString(), value.toString(), JSON.stringify(beValue.toString(2).split(/(.....)/).slice(1))) - - return str; -} - -/** - Normalize and validate decimal string (potentially large values). Should - avoid internationalization issues if possible but will be safe and - throw an error for an invalid number. - - Normalization removes extra zeros or decimal. - - @return {string} value -*/ -function DecimalString(value) { - assert(value != null, 'value is required'); - value = value === 'object' && value.toString ? value.toString() : String(value); - - var neg = /^-/.test(value); - if (neg) { - value = value.substring(1); - } - - if (value[0] === '.') { - value = '0' + value; - } - - var part = value.split('.'); - assert(part.length <= 2, 'invalid decimal ' + value); - assert(/^\d+(,?\d)*\d*$/.test(part[0]), 'invalid decimal ' + value); - - if (part.length === 2) { - assert(/^\d*$/.test(part[1]), 'invalid decimal ' + value); - part[1] = part[1].replace(/0+$/, ''); // remove suffixing zeros - if (part[1] === '') { - part.pop(); - } - } - - part[0] = part[0].replace(/^0*/, ''); // remove leading zeros - if (part[0] === '') { - part[0] = '0'; - } - return (neg ? '-' : '') + part.join('.'); -} - -/** - Ensure a fixed number of decimal places. Safe for large numbers. - - @see ./format.test.js - - @example DecimalPad(10.2, 3) === '10.200' - - @arg {number|string|object.toString} num - @arg {number} [precision = null] - number of decimal places. Null skips - padding suffix but still applies number format normalization. - @return {string} decimal part is added and zero padded to match precision -*/ -function DecimalPad(num, precision) { - var value = DecimalString(num); - if (precision == null) { - return value; - } - - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - - var part = value.split('.'); - - if (precision === 0 && part.length === 1) { - return part[0]; - } - - if (part.length === 1) { - return part[0] + '.' + '0'.repeat(precision); - } else { - var pad = precision - part[1].length; - assert(pad >= 0, 'decimal \'' + value + '\' exceeds precision ' + precision); - return part[0] + '.' + part[1] + '0'.repeat(pad); - } -} - -/** Ensures proper trailing zeros then removes decimal place. */ -function DecimalImply(value, precision) { - return DecimalPad(value, precision).replace('.', ''); -} - -/** - Put the decimal place back in its position and return the normalized number - string (with any unnecessary zeros or an unnecessary decimal removed). - - @arg {string|number|value.toString} value 10000 - @arg {number} precision 4 - @return {number} 1.0000 -*/ -function DecimalUnimply(value, precision) { - assert(value != null, 'value is required'); - value = value === 'object' && value.toString ? value.toString() : String(value); - var neg = /^-/.test(value); - if (neg) { - value = value.substring(1); - } - assert(/^\d+$/.test(value), 'invalid whole number ' + value); - assert(precision != null, 'precision required'); - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - - // Ensure minimum length - var pad = precision - value.length; - if (pad > 0) { - value = '' + '0'.repeat(pad) + value; - } - - var dotIdx = value.length - precision; - value = value.slice(0, dotIdx) + '.' + value.slice(dotIdx); - return (neg ? '-' : '') + DecimalPad(value, precision); // Normalize -} - -/** @private for now, support for asset strings is limited -*/ -function printAsset(_ref) { - var amount = _ref.amount, - precision = _ref.precision, - symbol = _ref.symbol, - contract = _ref.contract; - - assert.equal(typeof symbol === 'undefined' ? 'undefined' : (0, _typeof3.default)(symbol), 'string', 'symbol is a required string'); - - if (amount != null && precision != null) { - amount = DecimalPad(amount, precision); - } - - var join = function join(e1, e2) { - return e1 == null ? '' : e2 == null ? '' : e1 + e2; - }; - - if (amount != null) { - // the amount contains the precision - return join(amount, ' ') + symbol + join('@', contract); - } - - return join(precision, ',') + symbol + join('@', contract); -} - -/** - Attempts to parse all forms of the asset strings (symbol, asset, or extended - versions). If the provided string contains any additional or appears to have - invalid information an error is thrown. - - @return {object} {amount, precision, symbol, contract} - @throws AssertionError -*/ -function parseAsset(str) { - var _str$split = str.split(' '), - _str$split2 = (0, _slicedToArray3.default)(_str$split, 1), - amountRaw = _str$split2[0]; - - var amountMatch = amountRaw.match(/^(-?[0-9]+(\.[0-9]+)?)( |$)/); - var amount = amountMatch ? amountMatch[1] : null; - - var precisionMatch = str.match(/(^| )([0-9]+),([A-Z]+)(@|$)/); - var precisionSymbol = precisionMatch ? Number(precisionMatch[2]) : null; - var precisionAmount = amount ? (amount.split('.')[1] || '').length : null; - var precision = precisionSymbol != null ? precisionSymbol : precisionAmount; - - var symbolMatch = str.match(/(^| |,)([A-Z]+)(@|$)/); - var symbol = symbolMatch ? symbolMatch[2] : null; - - var _str$split3 = str.split('@'), - _str$split4 = (0, _slicedToArray3.default)(_str$split3, 2), - _str$split4$ = _str$split4[1], - contractRaw = _str$split4$ === undefined ? '' : _str$split4$; - - var contract = /^[a-z0-5]+(\.[a-z0-5]+)*$/.test(contractRaw) ? contractRaw : null; - - var check = printAsset({ amount: amount, precision: precision, symbol: symbol, contract: contract }); - - assert.equal(str, check, 'Invalid asset string: ' + str + ' !== ' + check); - - if (precision != null) { - assert(precision >= 0 && precision <= 18, 'Precision should be 18 characters or less'); - } - if (symbol != null) { - assert(symbol.length <= 7, 'Asset symbol is 7 characters or less'); - } - if (contract != null) { - assert(contract.length <= 12, 'Contract is 12 characters or less'); - } - - return { amount: amount, precision: precision, symbol: symbol, contract: contract }; -} - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -class Plugin { - - constructor(_name = '', _type = '') { - this.name = _name; - this.type = _type; - } - -} -exports.default = Plugin; - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _stringify = __webpack_require__(329); - -var _stringify2 = _interopRequireDefault(_stringify); - -var _assign = __webpack_require__(35); - -var _assign2 = _interopRequireDefault(_assign); - -var _Blockchains = __webpack_require__(98); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -class Network { - constructor(_name = '', _protocol = 'https', _host = '', _port = 0, blockchain = _Blockchains.Blockchains.EOS, chainId = '') { - this.name = _name; - this.protocol = _protocol; - this.host = _host; - this.port = _port; - this.blockchain = blockchain; - this.chainId = chainId.toString(); - } - - static placeholder() { - return new Network(); - } - - static fromJson(json) { - const p = (0, _assign2.default)(Network.placeholder(), json); - p.chainId = p.chainId ? p.chainId.toString() : ''; - return p; - } - - static fromUnique(netString) { - const blockchain = netString.split(':')[0]; - if (netString.indexOf(':chain:') > -1) return new Network('', '', '', '', blockchain, netString.replace(`${blockchain}:chain:`, '')); - - const splits = netString.replace(`${blockchain}:`, '').split(':'); - return new Network('', '', splits[0], parseInt(splits[1] || 80), blockchain); - } - - unique() { - return (`${this.blockchain}:` + (this.chainId.length ? `chain:${this.chainId}` : `${this.host}:${this.port}`)).toLowerCase(); - } - hostport() { - return `${this.host}${this.port ? ':' : ''}${this.port}`; - } - fullhost() { - return `${this.protocol}://${this.host}${this.port ? ':' : ''}${this.port}`; - } - clone() { - return Network.fromJson(JSON.parse((0, _stringify2.default)(this))); - } - isEmpty() { - return !this.host.length; - } - isValid() { - return this.protocol.length && this.host.length && this.port || this.chainId.length; - } -} -exports.default = Network; - -/***/ }), -/* 165 */ -/***/ (function(module, exports) { - -module.exports = {"COMPRESSED_TYPE_INVALID":"compressed should be a boolean","EC_PRIVATE_KEY_TYPE_INVALID":"private key should be a Buffer","EC_PRIVATE_KEY_LENGTH_INVALID":"private key length is invalid","EC_PRIVATE_KEY_RANGE_INVALID":"private key range is invalid","EC_PRIVATE_KEY_TWEAK_ADD_FAIL":"tweak out of range or resulting private key is invalid","EC_PRIVATE_KEY_TWEAK_MUL_FAIL":"tweak out of range","EC_PRIVATE_KEY_EXPORT_DER_FAIL":"couldn't export to DER format","EC_PRIVATE_KEY_IMPORT_DER_FAIL":"couldn't import from DER format","EC_PUBLIC_KEYS_TYPE_INVALID":"public keys should be an Array","EC_PUBLIC_KEYS_LENGTH_INVALID":"public keys Array should have at least 1 element","EC_PUBLIC_KEY_TYPE_INVALID":"public key should be a Buffer","EC_PUBLIC_KEY_LENGTH_INVALID":"public key length is invalid","EC_PUBLIC_KEY_PARSE_FAIL":"the public key could not be parsed or is invalid","EC_PUBLIC_KEY_CREATE_FAIL":"private was invalid, try again","EC_PUBLIC_KEY_TWEAK_ADD_FAIL":"tweak out of range or resulting public key is invalid","EC_PUBLIC_KEY_TWEAK_MUL_FAIL":"tweak out of range","EC_PUBLIC_KEY_COMBINE_FAIL":"the sum of the public keys is not valid","ECDH_FAIL":"scalar was invalid (zero or overflow)","ECDSA_SIGNATURE_TYPE_INVALID":"signature should be a Buffer","ECDSA_SIGNATURE_LENGTH_INVALID":"signature length is invalid","ECDSA_SIGNATURE_PARSE_FAIL":"couldn't parse signature","ECDSA_SIGNATURE_PARSE_DER_FAIL":"couldn't parse DER signature","ECDSA_SIGNATURE_SERIALIZE_DER_FAIL":"couldn't serialize signature to DER format","ECDSA_SIGN_FAIL":"nonce generation function failed or private key is invalid","ECDSA_RECOVER_FAIL":"couldn't recover public key from signature","MSG32_TYPE_INVALID":"message should be a Buffer","MSG32_LENGTH_INVALID":"message length is invalid","OPTIONS_TYPE_INVALID":"options should be an Object","OPTIONS_DATA_TYPE_INVALID":"options.data should be a Buffer","OPTIONS_DATA_LENGTH_INVALID":"options.data length is invalid","OPTIONS_NONCEFN_TYPE_INVALID":"options.noncefn should be a Function","RECOVERY_ID_TYPE_INVALID":"recovery should be a Number","RECOVERY_ID_VALUE_INVALID":"recovery should have value between -1 and 4","TWEAK_TYPE_INVALID":"tweak should be a Buffer","TWEAK_LENGTH_INVALID":"tweak length is invalid"} - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - return res; -} -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(13); -var rotr32 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -exports.ft_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -exports.ch32 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -exports.maj32 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -exports.p32 = p32; - -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} -exports.s0_256 = s0_256; - -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} -exports.s1_256 = s1_256; - -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} -exports.g0_256 = g0_256; - -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); -} -exports.g1_256 = g1_256; - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(13); -var common = __webpack_require__(48); -var shaCommon = __webpack_require__(167); -var assert = __webpack_require__(26); - -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var ch32 = shaCommon.ch32; -var maj32 = shaCommon.maj32; -var s0_256 = shaCommon.s0_256; -var s1_256 = shaCommon.s1_256; -var g0_256 = shaCommon.g0_256; -var g1_256 = shaCommon.g1_256; - -var BlockHash = common.BlockHash; - -var sha256_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 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash); -module.exports = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - assert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var utils = __webpack_require__(13); -var common = __webpack_require__(48); -var assert = __webpack_require__(26); - -var rotr64_hi = utils.rotr64_hi; -var rotr64_lo = utils.rotr64_lo; -var shr64_hi = utils.shr64_hi; -var shr64_lo = utils.shr64_lo; -var sum64 = utils.sum64; -var sum64_hi = utils.sum64_hi; -var sum64_lo = utils.sum64_lo; -var sum64_4_hi = utils.sum64_4_hi; -var sum64_4_lo = utils.sum64_4_lo; -var sum64_5_hi = utils.sum64_5_hi; -var sum64_5_lo = utils.sum64_5_lo; - -var BlockHash = common.BlockHash; - -var sha512_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 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash); -module.exports = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64(this.h, 0, ah, al); - sum64(this.h, 2, bh, bl); - sum64(this.h, 4, ch, cl); - sum64(this.h, 6, dh, dl); - sum64(this.h, 8, eh, el); - sum64(this.h, 10, fh, fl); - sum64(this.h, 12, gh, gl); - sum64(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28); - var c1_hi = rotr64_hi(xl, xh, 2); // 34 - var c2_hi = rotr64_hi(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28); - var c1_lo = rotr64_lo(xl, xh, 2); // 34 - var c2_lo = rotr64_lo(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14); - var c1_hi = rotr64_hi(xh, xl, 18); - var c2_hi = rotr64_hi(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14); - var c1_lo = rotr64_lo(xh, xl, 18); - var c2_lo = rotr64_lo(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1); - var c1_hi = rotr64_hi(xh, xl, 8); - var c2_hi = shr64_hi(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1); - var c1_lo = rotr64_lo(xh, xl, 8); - var c2_lo = shr64_lo(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19); - var c1_hi = rotr64_hi(xl, xh, 29); // 61 - var c2_hi = shr64_hi(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19); - var c1_lo = rotr64_lo(xl, xh, 29); // 61 - var c2_lo = shr64_lo(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(Buffer) { - -var isHexPrefixed = __webpack_require__(171); -var stripHexPrefix = __webpack_require__(369); - -/** - * Pads a `String` to have an even length - * @param {String} value - * @return {String} output - */ -function padToEven(value) { - var a = value; // eslint-disable-line - - if (typeof a !== 'string') { - throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.'); - } - - if (a.length % 2) { - a = '0' + a; - } - - return a; -} - -/** - * Converts a `Number` into a hex `String` - * @param {Number} i - * @return {String} - */ -function intToHex(i) { - var hex = i.toString(16); // eslint-disable-line - - return '0x' + hex; -} - -/** - * Converts an `Number` to a `Buffer` - * @param {Number} i - * @return {Buffer} - */ -function intToBuffer(i) { - var hex = intToHex(i); - - return new Buffer(padToEven(hex.slice(2)), 'hex'); -} - -/** - * Get the binary size of a string - * @param {String} str - * @return {Number} - */ -function getBinarySize(str) { - if (typeof str !== 'string') { - throw new Error('[ethjs-util] while getting binary size, method getBinarySize requires input \'str\' to be type String, got \'' + typeof str + '\'.'); - } - - return Buffer.byteLength(str, 'utf8'); -} - -/** - * Returns TRUE if the first specified array contains all elements - * from the second one. FALSE otherwise. - * - * @param {array} superset - * @param {array} subset - * - * @returns {boolean} - */ -function arrayContainsArray(superset, subset, some) { - if (Array.isArray(superset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'superset\' to be an array got type \'' + typeof superset + '\''); - } - if (Array.isArray(subset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'subset\' to be an array got type \'' + typeof subset + '\''); - } - - return subset[Boolean(some) && 'some' || 'every'](function (value) { - return superset.indexOf(value) >= 0; - }); -} - -/** - * Should be called to get utf8 from it's hex representation - * - * @method toUtf8 - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toUtf8(hex) { - var bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex'); - - return bufferValue.toString('utf8'); -} - -/** - * Should be called to get ascii from it's hex representation - * - * @method toAscii - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toAscii(hex) { - var str = ''; // eslint-disable-line - var i = 0, - l = hex.length; // eslint-disable-line - - if (hex.substring(0, 2) === '0x') { - i = 2; - } - - for (; i < l; i += 2) { - var code = parseInt(hex.substr(i, 2), 16); - str += String.fromCharCode(code); - } - - return str; -} - -/** - * Should be called to get hex representation (prefixed by 0x) of utf8 string - * - * @method fromUtf8 - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromUtf8(stringValue) { - var str = new Buffer(stringValue, 'utf8'); - - return '0x' + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); -} - -/** - * Should be called to get hex representation (prefixed by 0x) of ascii string - * - * @method fromAscii - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromAscii(stringValue) { - var hex = ''; // eslint-disable-line - for (var i = 0; i < stringValue.length; i++) { - // eslint-disable-line - var code = stringValue.charCodeAt(i); - var n = code.toString(16); - hex += n.length < 2 ? '0' + n : n; - } - - return '0x' + hex; -} - -/** - * getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] - * - * @method getKeys get specific key from inner object array of objects - * @param {String} params - * @param {String} key - * @param {Boolean} allowEmpty - * @returns {Array} output just a simple array of output keys - */ -function getKeys(params, key, allowEmpty) { - if (!Array.isArray(params)) { - throw new Error('[ethjs-util] method getKeys expecting type Array as \'params\' input, got \'' + typeof params + '\''); - } - if (typeof key !== 'string') { - throw new Error('[ethjs-util] method getKeys expecting type String for input \'key\' got \'' + typeof key + '\'.'); - } - - var result = []; // eslint-disable-line - - for (var i = 0; i < params.length; i++) { - // eslint-disable-line - var value = params[i][key]; // eslint-disable-line - if (allowEmpty && !value) { - value = ''; - } else if (typeof value !== 'string') { - throw new Error('invalid abi'); - } - result.push(value); - } - - return result; -} - -/** - * Is the string a hex string. - * - * @method check if string is hex string of specific length - * @param {String} value - * @param {Number} length - * @returns {Boolean} output the string is a hex string - */ -function isHexString(value, length) { - if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - - if (length && value.length !== 2 + 2 * length) { - return false; - } - - return true; -} - -module.exports = { - arrayContainsArray: arrayContainsArray, - intToBuffer: intToBuffer, - getBinarySize: getBinarySize, - isHexPrefixed: isHexPrefixed, - stripHexPrefix: stripHexPrefix, - padToEven: padToEven, - intToHex: intToHex, - fromAscii: fromAscii, - fromUtf8: fromUtf8, - toAscii: toAscii, - toUtf8: toUtf8, - getKeys: getKeys, - isHexString: isHexString -}; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer)) - -/***/ }), -/* 171 */ -/***/ (function(module, exports) { - -/** - * Returns a `Boolean` on whether or not the a `String` starts with '0x' - * @param {String} str the string input value - * @return {Boolean} a boolean if it is or is not hex prefixed - * @throws if the str input is not a string - */ -module.exports = function isHexPrefixed(str) { - if (typeof str !== 'string') { - throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); - } - - return str.slice(0, 2) === '0x'; -} - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = __webpack_require__(68); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = __webpack_require__(178); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = __webpack_require__(380); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = __webpack_require__(181); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = __webpack_require__(49); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = __webpack_require__(101); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = __webpack_require__(103); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = __webpack_require__(27); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -module.exports = exports['default']; - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - -var root = __webpack_require__(174); - -/** Built-in value references. */ -var Symbol = root.Symbol; - -module.exports = Symbol; - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - -var freeGlobal = __webpack_require__(175); - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -module.exports = root; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -module.exports = freeGlobal; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 176 */ -/***/ (function(module, exports) { - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -module.exports = isObject; - - -/***/ }), -/* 177 */ -/***/ (function(module, exports) { - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -module.exports = isLength; - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -exports.default = {}; -module.exports = exports["default"]; - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _eachOfLimit; - -var _noop = __webpack_require__(49); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = __webpack_require__(101); - -var _once2 = _interopRequireDefault(_once); - -var _iterator = __webpack_require__(381); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _onlyOnce = __webpack_require__(103); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _breakLoop = __webpack_require__(178); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var running = 0; - var looping = false; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else if (!looping) { - replenish(); - } - } - - function replenish() { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); - } - looping = false; - } - - replenish(); - }; -} -module.exports = exports['default']; - -/***/ }), -/* 180 */ -/***/ (function(module, exports) { - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -module.exports = isArray; - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doLimit; -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} -module.exports = exports["default"]; - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright (c) 2012 Mathieu Turcotte -// Licensed under the MIT license. - -var events = __webpack_require__(12); -var precond = __webpack_require__(105); -var util = __webpack_require__(8); - -// A class to hold the state of a backoff operation. Accepts a backoff strategy -// to generate the backoff delays. -function Backoff(backoffStrategy) { - events.EventEmitter.call(this); - - this.backoffStrategy_ = backoffStrategy; - this.maxNumberOfRetry_ = -1; - this.backoffNumber_ = 0; - this.backoffDelay_ = 0; - this.timeoutID_ = -1; - - this.handlers = { - backoff: this.onBackoff_.bind(this) - }; -} -util.inherits(Backoff, events.EventEmitter); - -// Sets a limit, greater than 0, on the maximum number of backoffs. A 'fail' -// event will be emitted when the limit is reached. -Backoff.prototype.failAfter = function(maxNumberOfRetry) { - precond.checkArgument(maxNumberOfRetry > 0, - 'Expected a maximum number of retry greater than 0 but got %s.', - maxNumberOfRetry); - - this.maxNumberOfRetry_ = maxNumberOfRetry; -}; - -// Starts a backoff operation. Accepts an optional parameter to let the -// listeners know why the backoff operation was started. -Backoff.prototype.backoff = function(err) { - precond.checkState(this.timeoutID_ === -1, 'Backoff in progress.'); - - if (this.backoffNumber_ === this.maxNumberOfRetry_) { - this.emit('fail', err); - this.reset(); - } else { - this.backoffDelay_ = this.backoffStrategy_.next(); - this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_); - this.emit('backoff', this.backoffNumber_, this.backoffDelay_, err); - } -}; - -// Handles the backoff timeout completion. -Backoff.prototype.onBackoff_ = function() { - this.timeoutID_ = -1; - this.emit('ready', this.backoffNumber_, this.backoffDelay_); - this.backoffNumber_++; -}; - -// Stops any backoff operation and resets the backoff delay to its inital value. -Backoff.prototype.reset = function() { - this.backoffNumber_ = 0; - this.backoffStrategy_.reset(); - clearTimeout(this.timeoutID_); - this.timeoutID_ = -1; -}; - -module.exports = Backoff; - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright (c) 2012 Mathieu Turcotte -// Licensed under the MIT license. - -var events = __webpack_require__(12); -var util = __webpack_require__(8); - -function isDef(value) { - return value !== undefined && value !== null; -} - -// Abstract class defining the skeleton for the backoff strategies. Accepts an -// object holding the options for the backoff strategy: -// -// * `randomisationFactor`: The randomisation factor which must be between 0 -// and 1 where 1 equates to a randomization factor of 100% and 0 to no -// randomization. -// * `initialDelay`: The backoff initial delay in milliseconds. -// * `maxDelay`: The backoff maximal delay in milliseconds. -function BackoffStrategy(options) { - options = options || {}; - - if (isDef(options.initialDelay) && options.initialDelay < 1) { - throw new Error('The initial timeout must be greater than 0.'); - } else if (isDef(options.maxDelay) && options.maxDelay < 1) { - throw new Error('The maximal timeout must be greater than 0.'); - } - - this.initialDelay_ = options.initialDelay || 100; - this.maxDelay_ = options.maxDelay || 10000; - - if (this.maxDelay_ <= this.initialDelay_) { - throw new Error('The maximal backoff delay must be ' + - 'greater than the initial backoff delay.'); - } - - if (isDef(options.randomisationFactor) && - (options.randomisationFactor < 0 || options.randomisationFactor > 1)) { - throw new Error('The randomisation factor must be between 0 and 1.'); - } - - this.randomisationFactor_ = options.randomisationFactor || 0; -} - -// Gets the maximal backoff delay. -BackoffStrategy.prototype.getMaxDelay = function() { - return this.maxDelay_; -}; - -// Gets the initial backoff delay. -BackoffStrategy.prototype.getInitialDelay = function() { - return this.initialDelay_; -}; - -// Template method that computes and returns the next backoff delay in -// milliseconds. -BackoffStrategy.prototype.next = function() { - var backoffDelay = this.next_(); - var randomisationMultiple = 1 + Math.random() * this.randomisationFactor_; - var randomizedDelay = Math.round(backoffDelay * randomisationMultiple); - return randomizedDelay; -}; - -// Computes and returns the next backoff delay. Intended to be overridden by -// subclasses. -BackoffStrategy.prototype.next_ = function() { - throw new Error('BackoffStrategy.next_() unimplemented.'); -}; - -// Template method that resets the backoff delay to its initial value. -BackoffStrategy.prototype.reset = function() { - this.reset_(); -}; - -// Resets the backoff delay to its initial value. Intended to be overridden by -// subclasses. -BackoffStrategy.prototype.reset_ = function() { - throw new Error('BackoffStrategy.reset_() unimplemented.'); -}; - -module.exports = BackoffStrategy; - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright (c) 2012 Mathieu Turcotte -// Licensed under the MIT license. - -var util = __webpack_require__(8); - -var BackoffStrategy = __webpack_require__(183); - -// Fibonacci backoff strategy. -function FibonacciBackoffStrategy(options) { - BackoffStrategy.call(this, options); - this.backoffDelay_ = 0; - this.nextBackoffDelay_ = this.getInitialDelay(); -} -util.inherits(FibonacciBackoffStrategy, BackoffStrategy); - -FibonacciBackoffStrategy.prototype.next_ = function() { - var backoffDelay = Math.min(this.nextBackoffDelay_, this.getMaxDelay()); - this.nextBackoffDelay_ += this.backoffDelay_; - this.backoffDelay_ = backoffDelay; - return backoffDelay; -}; - -FibonacciBackoffStrategy.prototype.reset_ = function() { - this.nextBackoffDelay_ = this.getInitialDelay(); - this.backoffDelay_ = 0; -}; - -module.exports = FibonacciBackoffStrategy; - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _assign = __webpack_require__(35); - -var _assign2 = _interopRequireDefault(_assign); - -var _promise = __webpack_require__(39); - -var _promise2 = _interopRequireDefault(_promise); - -var _asyncToGenerator2 = __webpack_require__(40); - -var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2); - -var _SocketService = __webpack_require__(81); - -var _SocketService2 = _interopRequireDefault(_SocketService); - -var _PluginRepository = __webpack_require__(323); - -var _PluginRepository2 = _interopRequireDefault(_PluginRepository); - -__webpack_require__(159); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -let origin; - -const throwNoAuth = () => { - if (!holder.scatter.isExtension && !_SocketService2.default.isConnected()) throw new Error('Connect and Authenticate first - scatter.connect( pluginName )'); -}; - -const checkForPlugin = (resolve, tries = 0) => { - if (tries > 20) return; - if (holder.scatter.isExtension) return resolve(true); - setTimeout(() => checkForPlugin(resolve, tries + 1), 100); -}; - -class Scatter { - - constructor() { - const noIdFunc = () => { - if (!this.identity) throw new Error('No Identity'); - }; - - _PluginRepository2.default.signatureProviders().map(sigProvider => { - this[sigProvider.name] = sigProvider.signatureProvider(noIdFunc); - }); - - this.isExtension = false; - this.identity = null; - } - - isInstalled() { - return (0, _asyncToGenerator3.default)(function* () { - return new _promise2.default(function (resolve) { - setTimeout(function () { - resolve(false); - }, 3000); - - _promise2.default.race([checkForPlugin(resolve), _SocketService2.default.ping().then(function (found) { - console.log('found', found); - if (found) resolve(true); - })]); - - // Tries to set up Desktop Connection - }); - })(); - } - - connect(pluginName, options) { - var _this = this; - - return (0, _asyncToGenerator3.default)(function* () { - return new _promise2.default(function (resolve) { - if (!pluginName || !pluginName.length) throw new Error("You must specify a name for this connection"); - - // Setting options defaults - options = (0, _assign2.default)({ initTimeout: 10000, linkTimeout: 30000 }, options); - - // Auto failer - setTimeout(function () { - resolve(false); - }, options.initTimeout); - - // Defaults to scatter extension if exists - checkForPlugin(resolve); - - // Tries to set up Desktop Connection - _SocketService2.default.init(pluginName, options.linkTimeout); - _SocketService2.default.link().then((() => { - var _ref = (0, _asyncToGenerator3.default)(function* (authenticated) { - if (!authenticated) return false; - _this.identity = yield _this.getIdentityFromPermissions(); - return resolve(true); - }); - - return function (_x) { - return _ref.apply(this, arguments); - }; - })()); - }); - })(); - } - - disconnect() { - return _SocketService2.default.disconnect(); - } - - isConnected() { - return _SocketService2.default.isConnected(); - } - - getVersion() { - return _SocketService2.default.sendApiRequest({ - type: 'getVersion', - payload: {} - }); - } - - getIdentity(requiredFields) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'getOrRequestIdentity', - payload: { - fields: requiredFields - } - }).then(id => { - if (id) this.identity = id; - return id; - }); - } - - getIdentityFromPermissions() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'identityFromPermissions', - payload: {} - }).then(id => { - if (id) this.identity = id; - return id; - }); - } - - forgetIdentity() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'forgetIdentity', - payload: {} - }).then(res => { - this.identity = null; - return res; - }); - } - - authenticate() { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'authenticate', - payload: {} - }); - } - - getArbitrarySignature(publicKey, data, whatfor = '', isHash = false) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestArbitrarySignature', - payload: { - publicKey, - data, - whatfor, - isHash - } - }); - } - - getPublicKey(blockchain) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'getPublicKey', - payload: { blockchain } - }); - } - - linkAccount(publicKey, account, network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'linkAccount', - payload: { publicKey, account, network } - }); - } - - suggestNetwork(network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestAddNetwork', - payload: { - network - } - }); - } - - requestSignature(payload) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'requestSignature', - payload - }); - } - - createTransaction(blockchain, actions, account, network) { - throwNoAuth(); - return _SocketService2.default.sendApiRequest({ - type: 'createTransaction', - payload: { - blockchain, - actions, - account, - network - } - }); - } -} - -class Holder { - constructor(_scatter) { - this.scatter = _scatter; - } -} - -let holder = new Holder(new Scatter()); -if (typeof window !== 'undefined') { - - // Catching extension instead of Desktop - if (typeof document !== 'undefined') { - const bindScatterClassic = () => { - holder.scatter = window.scatter; - holder.scatter.isExtension = true; - holder.scatter.connect = () => new _promise2.default(resolve => resolve(true)); - }; - - if (typeof window.scatter !== 'undefined') bindScatterClassic();else document.addEventListener('scatterLoaded', () => bindScatterClassic()); - } - - if (!holder.scatter.isExtension) window.scatter = holder.scatter; -} - -exports.default = holder; - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - -__webpack_require__(187); -module.exports = __webpack_require__(5).Object.assign; - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.3.1 Object.assign(target, source) -var $export = __webpack_require__(17); - -$export($export.S + $export.F, 'Object', { assign: __webpack_require__(188) }); - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// 19.1.2.1 Object.assign(target, source, ...) -var getKeys = __webpack_require__(36); -var gOPS = __webpack_require__(77); -var pIE = __webpack_require__(55); -var toObject = __webpack_require__(78); -var IObject = __webpack_require__(108); -var $assign = Object.assign; - -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || __webpack_require__(28)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; -}) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; - } return T; -} : $assign; - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - -// false -> Array#indexOf -// true -> Array#includes -var toIObject = __webpack_require__(29); -var toLength = __webpack_require__(109); -var toAbsoluteIndex = __webpack_require__(190); -module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; -}; - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - -var toInteger = __webpack_require__(73); -var max = Math.max; -var min = Math.min; -module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - -__webpack_require__(110); -__webpack_require__(56); -__webpack_require__(58); -__webpack_require__(199); -__webpack_require__(210); -__webpack_require__(211); -module.exports = __webpack_require__(5).Promise; - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - -var toInteger = __webpack_require__(73); -var defined = __webpack_require__(72); -// true -> String#at -// false -> String#codePointAt -module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var create = __webpack_require__(113); -var descriptor = __webpack_require__(53); -var setToStringTag = __webpack_require__(57); -var IteratorPrototype = {}; - -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -__webpack_require__(18)(IteratorPrototype, __webpack_require__(7)('iterator'), function () { return this; }); - -module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); -}; - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - -var dP = __webpack_require__(19); -var anObject = __webpack_require__(14); -var getKeys = __webpack_require__(36); - -module.exports = __webpack_require__(21) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; -}; - - -/***/ }), -/* 195 */ -/***/ (function(module, exports, __webpack_require__) { - -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var has = __webpack_require__(22); -var toObject = __webpack_require__(78); -var IE_PROTO = __webpack_require__(74)('IE_PROTO'); -var ObjectProto = Object.prototype; - -module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; -}; - - -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var addToUnscopables = __webpack_require__(197); -var step = __webpack_require__(198); -var Iterators = __webpack_require__(30); -var toIObject = __webpack_require__(29); - -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = __webpack_require__(111)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); - -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; - -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); - - -/***/ }), -/* 197 */ -/***/ (function(module, exports) { - -module.exports = function () { /* empty */ }; - - -/***/ }), -/* 198 */ -/***/ (function(module, exports) { - -module.exports = function (done, value) { - return { value: value, done: !!done }; -}; - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var LIBRARY = __webpack_require__(38); -var global = __webpack_require__(6); -var ctx = __webpack_require__(51); -var classof = __webpack_require__(79); -var $export = __webpack_require__(17); -var isObject = __webpack_require__(20); -var aFunction = __webpack_require__(52); -var anInstance = __webpack_require__(200); -var forOf = __webpack_require__(201); -var speciesConstructor = __webpack_require__(116); -var task = __webpack_require__(117).set; -var microtask = __webpack_require__(205)(); -var newPromiseCapabilityModule = __webpack_require__(80); -var perform = __webpack_require__(118); -var userAgent = __webpack_require__(206); -var promiseResolve = __webpack_require__(119); -var PROMISE = 'Promise'; -var TypeError = global.TypeError; -var process = global.process; -var versions = process && process.versions; -var v8 = versions && versions.v8 || ''; -var $Promise = global[PROMISE]; -var isNode = classof(process) == 'process'; -var empty = function () { /* empty */ }; -var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; -var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - -var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(7)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } -}(); - -// helpers -var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; -}; -var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); -}; -var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); -}; -var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; -}; -var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); -}; -var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); -}; -var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } -}; - -// constructor polyfill -if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(207)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; -} - -$export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); -__webpack_require__(57)($Promise, PROMISE); -__webpack_require__(208)(PROMISE); -Wrapper = __webpack_require__(5)[PROMISE]; - -// statics -$export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } -}); -$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } -}); -$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(209)(function (iter) { - $Promise.all(iter)['catch'](empty); -})), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } -}); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports) { - -module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; -}; - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - -var ctx = __webpack_require__(51); -var call = __webpack_require__(202); -var isArrayIter = __webpack_require__(203); -var anObject = __webpack_require__(14); -var toLength = __webpack_require__(109); -var getIterFn = __webpack_require__(115); -var BREAK = {}; -var RETURN = {}; -var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } -}; -exports.BREAK = BREAK; -exports.RETURN = RETURN; - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - -// call something on iterator step with safe closing on error -var anObject = __webpack_require__(14); -module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } -}; - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - -// check on default Array iterator -var Iterators = __webpack_require__(30); -var ITERATOR = __webpack_require__(7)('iterator'); -var ArrayProto = Array.prototype; - -module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); -}; - - -/***/ }), -/* 204 */ -/***/ (function(module, exports) { - -// fast apply, http://jsperf.lnkit.com/fast-apply/5 -module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); -}; - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - -var global = __webpack_require__(6); -var macrotask = __webpack_require__(117).set; -var Observer = global.MutationObserver || global.WebKitMutationObserver; -var process = global.process; -var Promise = global.Promise; -var isNode = __webpack_require__(37)(process) == 'process'; - -module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; -}; - - -/***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { - -var global = __webpack_require__(6); -var navigator = global.navigator; - -module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - -var hide = __webpack_require__(18); -module.exports = function (target, src, safe) { - for (var key in src) { - if (safe && target[key]) target[key] = src[key]; - else hide(target, key, src[key]); - } return target; -}; - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var global = __webpack_require__(6); -var core = __webpack_require__(5); -var dP = __webpack_require__(19); -var DESCRIPTORS = __webpack_require__(21); -var SPECIES = __webpack_require__(7)('species'); - -module.exports = function (KEY) { - var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); -}; - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - -var ITERATOR = __webpack_require__(7)('iterator'); -var SAFE_CLOSING = false; - -try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); -} catch (e) { /* empty */ } - -module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; -}; - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -// https://github.com/tc39/proposal-promise-finally - -var $export = __webpack_require__(17); -var core = __webpack_require__(5); -var global = __webpack_require__(6); -var speciesConstructor = __webpack_require__(116); -var promiseResolve = __webpack_require__(119); - -$export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); -} }); - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// https://github.com/tc39/proposal-promise-try -var $export = __webpack_require__(17); -var newPromiseCapability = __webpack_require__(80); -var perform = __webpack_require__(118); - -$export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; -} }); - - -/***/ }), -/* 212 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * Module dependencies. - */ - -var url = __webpack_require__(213); -var parser = __webpack_require__(82); -var Manager = __webpack_require__(122); -var debug = __webpack_require__(15)('socket.io-client'); - -/** - * Module exports. - */ - -module.exports = exports = lookup; - -/** - * Managers cache. - */ - -var cache = exports.managers = {}; - -/** - * Looks up an existing `Manager` for multiplexing. - * If the user summons: - * - * `io('http://localhost/a');` - * `io('http://localhost/b');` - * - * We reuse the existing instance based on same scheme/port/host, - * and we initialize sockets for each namespace. - * - * @api public - */ - -function lookup (uri, opts) { - if (typeof uri === 'object') { - opts = uri; - uri = undefined; - } - - opts = opts || {}; - - var parsed = url(uri); - var source = parsed.source; - var id = parsed.id; - var path = parsed.path; - var sameNamespace = cache[id] && path in cache[id].nsps; - var newConnection = opts.forceNew || opts['force new connection'] || - false === opts.multiplex || sameNamespace; - - var io; - - if (newConnection) { - debug('ignoring socket cache for %s', source); - io = Manager(source, opts); - } else { - if (!cache[id]) { - debug('new io instance for %s', source); - cache[id] = Manager(source, opts); - } - io = cache[id]; - } - if (parsed.query && !opts.query) { - opts.query = parsed.query; - } - return io.socket(parsed.path, opts); -} - -/** - * Protocol version. - * - * @api public - */ - -exports.protocol = parser.protocol; - -/** - * `connect`. - * - * @param {String} uri - * @api public - */ - -exports.connect = lookup; - -/** - * Expose constructors for standalone build. - * - * @api public - */ - -exports.Manager = __webpack_require__(122); -exports.Socket = __webpack_require__(128); - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) { -/** - * Module dependencies. - */ - -var parseuri = __webpack_require__(120); -var debug = __webpack_require__(15)('socket.io-client:url'); - -/** - * Module exports. - */ - -module.exports = url; - -/** - * URL parser. - * - * @param {String} url - * @param {Object} An object meant to mimic window.location. - * Defaults to window.location. - * @api public - */ - -function url (uri, loc) { - var obj = uri; - - // default to window.location - loc = loc || global.location; - if (null == uri) uri = loc.protocol + '//' + loc.host; - - // relative path support - if ('string' === typeof uri) { - if ('/' === uri.charAt(0)) { - if ('/' === uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.host + uri; - } - } - - if (!/^(https?|wss?):\/\//.test(uri)) { - debug('protocol-less url %s', uri); - if ('undefined' !== typeof loc) { - uri = loc.protocol + '//' + uri; - } else { - uri = 'https://' + uri; - } - } - - // parse - debug('parse %s', uri); - obj = parseuri(uri); - } - - // make sure we treat `localhost:80` and `localhost` equally - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = '80'; - } else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = '443'; - } - } - - obj.path = obj.path || '/'; - - var ipv6 = obj.host.indexOf(':') !== -1; - var host = ipv6 ? '[' + obj.host + ']' : obj.host; - - // define unique id - obj.id = obj.protocol + '://' + host + ':' + obj.port; - // define href - obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port)); - - return obj; -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __webpack_require__(215); - -/** - * Active `debug` instances. - */ -exports.instances = []; - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - var prevTime; - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - debug.destroy = destroy; - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - exports.instances.push(debug); - - return debug; -} - -function destroy () { - var index = exports.instances.indexOf(this); - if (index !== -1) { - exports.instances.splice(index, 1); - return true; - } else { - return false; - } -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } - - for (i = 0; i < exports.instances.length; i++) { - var instance = exports.instances[i]; - instance.enabled = exports.enabled(instance.namespace); - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - - -/***/ }), -/* 215 */ -/***/ (function(module, exports) { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/*global Blob,File*/ - -/** - * Module requirements - */ - -var isArray = __webpack_require__(83); -var isBuf = __webpack_require__(121); -var toString = Object.prototype.toString; -var withNativeBlob = typeof global.Blob === 'function' || toString.call(global.Blob) === '[object BlobConstructor]'; -var withNativeFile = typeof global.File === 'function' || toString.call(global.File) === '[object FileConstructor]'; - -/** - * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. - * Anything with blobs or files should be fed through removeBlobs before coming - * here. - * - * @param {Object} packet - socket.io event packet - * @return {Object} with deconstructed packet and list of buffers - * @api public - */ - -exports.deconstructPacket = function(packet) { - var buffers = []; - var packetData = packet.data; - var pack = packet; - pack.data = _deconstructPacket(packetData, buffers); - pack.attachments = buffers.length; // number of binary 'attachments' - return {packet: pack, buffers: buffers}; -}; - -function _deconstructPacket(data, buffers) { - if (!data) return data; - - if (isBuf(data)) { - var placeholder = { _placeholder: true, num: buffers.length }; - buffers.push(data); - return placeholder; - } else if (isArray(data)) { - var newData = new Array(data.length); - for (var i = 0; i < data.length; i++) { - newData[i] = _deconstructPacket(data[i], buffers); - } - return newData; - } else if (typeof data === 'object' && !(data instanceof Date)) { - var newData = {}; - for (var key in data) { - newData[key] = _deconstructPacket(data[key], buffers); - } - return newData; - } - return data; -} - -/** - * Reconstructs a binary packet from its placeholder packet and buffers - * - * @param {Object} packet - event packet with placeholders - * @param {Array} buffers - binary buffers to put in placeholder positions - * @return {Object} reconstructed packet - * @api public - */ - -exports.reconstructPacket = function(packet, buffers) { - packet.data = _reconstructPacket(packet.data, buffers); - packet.attachments = undefined; // no longer useful - return packet; -}; - -function _reconstructPacket(data, buffers) { - if (!data) return data; - - if (data && data._placeholder) { - return buffers[data.num]; // appropriate buffer (should be natural order anyway) - } else if (isArray(data)) { - for (var i = 0; i < data.length; i++) { - data[i] = _reconstructPacket(data[i], buffers); - } - } else if (typeof data === 'object') { - for (var key in data) { - data[key] = _reconstructPacket(data[key], buffers); - } - } - - return data; -} - -/** - * Asynchronously removes Blobs or Files from data via - * FileReader's readAsArrayBuffer method. Used before encoding - * data as msgpack. Calls callback with the blobless data. - * - * @param {Object} data - * @param {Function} callback - * @api private - */ - -exports.removeBlobs = function(data, callback) { - function _removeBlobs(obj, curKey, containingObject) { - if (!obj) return obj; - - // convert any blob - if ((withNativeBlob && obj instanceof Blob) || - (withNativeFile && obj instanceof File)) { - pendingBlobs++; - - // async filereader - var fileReader = new FileReader(); - fileReader.onload = function() { // this.result == arraybuffer - if (containingObject) { - containingObject[curKey] = this.result; - } - else { - bloblessData = this.result; - } - - // if nothing pending its callback time - if(! --pendingBlobs) { - callback(bloblessData); - } - }; - - fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer - } else if (isArray(obj)) { // handle array - for (var i = 0; i < obj.length; i++) { - _removeBlobs(obj[i], i, obj); - } - } else if (typeof obj === 'object' && !isBuf(obj)) { // and object - for (var key in obj) { - _removeBlobs(obj[key], key, obj); - } - } - } - - var pendingBlobs = 0; - var bloblessData = data; - _removeBlobs(bloblessData); - if (!pendingBlobs) { - callback(bloblessData); - } -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - - -module.exports = __webpack_require__(218); - -/** - * Exports parser - * - * @api public - * - */ -module.exports.parser = __webpack_require__(32); - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - */ - -var transports = __webpack_require__(123); -var Emitter = __webpack_require__(31); -var debug = __webpack_require__(15)('engine.io-client:socket'); -var index = __webpack_require__(127); -var parser = __webpack_require__(32); -var parseuri = __webpack_require__(120); -var parseqs = __webpack_require__(60); - -/** - * Module exports. - */ - -module.exports = Socket; - -/** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ - -function Socket (uri, opts) { - if (!(this instanceof Socket)) return new Socket(uri, opts); - - opts = opts || {}; - - if (uri && 'object' === typeof uri) { - opts = uri; - uri = null; - } - - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === 'https' || uri.protocol === 'wss'; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } - - this.secure = null != opts.secure ? opts.secure - : (global.location && 'https:' === location.protocol); - - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = this.secure ? '443' : '80'; - } - - this.agent = opts.agent || false; - this.hostname = opts.hostname || - (global.location ? location.hostname : 'localhost'); - this.port = opts.port || (global.location && location.port - ? location.port - : (this.secure ? 443 : 80)); - this.query = opts.query || {}; - if ('string' === typeof this.query) this.query = parseqs.decode(this.query); - this.upgrade = false !== opts.upgrade; - this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/'; - this.forceJSONP = !!opts.forceJSONP; - this.jsonp = false !== opts.jsonp; - this.forceBase64 = !!opts.forceBase64; - this.enablesXDR = !!opts.enablesXDR; - this.timestampParam = opts.timestampParam || 't'; - this.timestampRequests = opts.timestampRequests; - this.transports = opts.transports || ['polling', 'websocket']; - this.transportOptions = opts.transportOptions || {}; - this.readyState = ''; - this.writeBuffer = []; - this.prevBufferLen = 0; - this.policyPort = opts.policyPort || 843; - this.rememberUpgrade = opts.rememberUpgrade || false; - this.binaryType = null; - this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades; - this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false; - - if (true === this.perMessageDeflate) this.perMessageDeflate = {}; - if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) { - this.perMessageDeflate.threshold = 1024; - } - - // SSL options for Node.js client - this.pfx = opts.pfx || null; - this.key = opts.key || null; - this.passphrase = opts.passphrase || null; - this.cert = opts.cert || null; - this.ca = opts.ca || null; - this.ciphers = opts.ciphers || null; - this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized; - this.forceNode = !!opts.forceNode; - - // other options for Node.js client - var freeGlobal = typeof global === 'object' && global; - if (freeGlobal.global === freeGlobal) { - if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) { - this.extraHeaders = opts.extraHeaders; - } - - if (opts.localAddress) { - this.localAddress = opts.localAddress; - } - } - - // set on handshake - this.id = null; - this.upgrades = null; - this.pingInterval = null; - this.pingTimeout = null; - - // set on heartbeat - this.pingIntervalTimer = null; - this.pingTimeoutTimer = null; - - this.open(); -} - -Socket.priorWebsocketSuccess = false; - -/** - * Mix in `Emitter`. - */ - -Emitter(Socket.prototype); - -/** - * Protocol version. - * - * @api public - */ - -Socket.protocol = parser.protocol; // this is an int - -/** - * Expose deps for legacy compatibility - * and standalone browser access. - */ - -Socket.Socket = Socket; -Socket.Transport = __webpack_require__(85); -Socket.transports = __webpack_require__(123); -Socket.parser = __webpack_require__(32); - -/** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ - -Socket.prototype.createTransport = function (name) { - debug('creating transport "%s"', name); - var query = clone(this.query); - - // append engine.io protocol identifier - query.EIO = parser.protocol; - - // transport name - query.transport = name; - - // per-transport options - var options = this.transportOptions[name] || {}; - - // session id if we already have one - if (this.id) query.sid = this.id; - - var transport = new transports[name]({ - query: query, - socket: this, - agent: options.agent || this.agent, - hostname: options.hostname || this.hostname, - port: options.port || this.port, - secure: options.secure || this.secure, - path: options.path || this.path, - forceJSONP: options.forceJSONP || this.forceJSONP, - jsonp: options.jsonp || this.jsonp, - forceBase64: options.forceBase64 || this.forceBase64, - enablesXDR: options.enablesXDR || this.enablesXDR, - timestampRequests: options.timestampRequests || this.timestampRequests, - timestampParam: options.timestampParam || this.timestampParam, - policyPort: options.policyPort || this.policyPort, - pfx: options.pfx || this.pfx, - key: options.key || this.key, - passphrase: options.passphrase || this.passphrase, - cert: options.cert || this.cert, - ca: options.ca || this.ca, - ciphers: options.ciphers || this.ciphers, - rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized, - perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate, - extraHeaders: options.extraHeaders || this.extraHeaders, - forceNode: options.forceNode || this.forceNode, - localAddress: options.localAddress || this.localAddress, - requestTimeout: options.requestTimeout || this.requestTimeout, - protocols: options.protocols || void (0) - }); - - return transport; -}; - -function clone (obj) { - var o = {}; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } - } - return o; -} - -/** - * Initializes transport to use and starts probe. - * - * @api private - */ -Socket.prototype.open = function () { - var transport; - if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) { - transport = 'websocket'; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit('error', 'No transports available'); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = 'opening'; - - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; - } - - transport.open(); - this.setTransport(transport); -}; - -/** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ - -Socket.prototype.setTransport = function (transport) { - debug('setting transport %s', transport.name); - var self = this; - - if (this.transport) { - debug('clearing existing transport %s', this.transport.name); - this.transport.removeAllListeners(); - } - - // set up transport - this.transport = transport; - - // set up transport listeners - transport - .on('drain', function () { - self.onDrain(); - }) - .on('packet', function (packet) { - self.onPacket(packet); - }) - .on('error', function (e) { - self.onError(e); - }) - .on('close', function () { - self.onClose('transport close'); - }); -}; - -/** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ - -Socket.prototype.probe = function (name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { probe: 1 }); - var failed = false; - var self = this; - - Socket.priorWebsocketSuccess = false; - - function onTransportOpen () { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - if (failed) return; - - debug('probe transport "%s" opened', name); - transport.send([{ type: 'ping', data: 'probe' }]); - transport.once('packet', function (msg) { - if (failed) return; - if ('pong' === msg.type && 'probe' === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit('upgrading', transport); - if (!transport) return; - Socket.priorWebsocketSuccess = 'websocket' === transport.name; - - debug('pausing current transport "%s"', self.transport.name); - self.transport.pause(function () { - if (failed) return; - if ('closed' === self.readyState) return; - debug('changing transport and sending upgrade packet'); - - cleanup(); - - self.setTransport(transport); - transport.send([{ type: 'upgrade' }]); - self.emit('upgrade', transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error('probe error'); - err.transport = transport.name; - self.emit('upgradeError', err); - } - }); - } - - function freezeTransport () { - if (failed) return; - - // Any callback called by transport should be ignored since now - failed = true; - - cleanup(); - - transport.close(); - transport = null; - } - - // Handle any error that happens while probing - function onerror (err) { - var error = new Error('probe error: ' + err); - error.transport = transport.name; - - freezeTransport(); - - debug('probe transport "%s" failed because of error: %s', name, err); - - self.emit('upgradeError', error); - } - - function onTransportClose () { - onerror('transport closed'); - } - - // When the socket is closed while we're probing - function onclose () { - onerror('socket closed'); - } - - // When the socket is upgraded while we're probing - function onupgrade (to) { - if (transport && to.name !== transport.name) { - debug('"%s" works - aborting "%s"', to.name, transport.name); - freezeTransport(); - } - } - - // Remove all listeners on the transport and on self - function cleanup () { - transport.removeListener('open', onTransportOpen); - transport.removeListener('error', onerror); - transport.removeListener('close', onTransportClose); - self.removeListener('close', onclose); - self.removeListener('upgrading', onupgrade); - } - - transport.once('open', onTransportOpen); - transport.once('error', onerror); - transport.once('close', onTransportClose); - - this.once('close', onclose); - this.once('upgrading', onupgrade); - - transport.open(); -}; - -/** - * Called when connection is deemed open. - * - * @api public - */ - -Socket.prototype.onOpen = function () { - debug('socket open'); - this.readyState = 'open'; - Socket.priorWebsocketSuccess = 'websocket' === this.transport.name; - this.emit('open'); - this.flush(); - - // we check for `readyState` in case an `open` - // listener already closed the socket - if ('open' === this.readyState && this.upgrade && this.transport.pause) { - debug('starting upgrade probes'); - for (var i = 0, l = this.upgrades.length; i < l; i++) { - this.probe(this.upgrades[i]); - } - } -}; - -/** - * Handles a packet. - * - * @api private - */ - -Socket.prototype.onPacket = function (packet) { - if ('opening' === this.readyState || 'open' === this.readyState || - 'closing' === this.readyState) { - debug('socket receive: type "%s", data "%s"', packet.type, packet.data); - - this.emit('packet', packet); - - // Socket is live - any packet counts - this.emit('heartbeat'); - - switch (packet.type) { - case 'open': - this.onHandshake(JSON.parse(packet.data)); - break; - - case 'pong': - this.setPing(); - this.emit('pong'); - break; - - case 'error': - var err = new Error('server error'); - err.code = packet.data; - this.onError(err); - break; - - case 'message': - this.emit('data', packet.data); - this.emit('message', packet.data); - break; - } - } else { - debug('packet received with socket readyState "%s"', this.readyState); - } -}; - -/** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ - -Socket.prototype.onHandshake = function (data) { - this.emit('handshake', data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); - // In case open handler closes socket - if ('closed' === this.readyState) return; - this.setPing(); - - // Prolong liveness of socket on heartbeat - this.removeListener('heartbeat', this.onHeartbeat); - this.on('heartbeat', this.onHeartbeat); -}; - -/** - * Resets ping timeout. - * - * @api private - */ - -Socket.prototype.onHeartbeat = function (timeout) { - clearTimeout(this.pingTimeoutTimer); - var self = this; - self.pingTimeoutTimer = setTimeout(function () { - if ('closed' === self.readyState) return; - self.onClose('ping timeout'); - }, timeout || (self.pingInterval + self.pingTimeout)); -}; - -/** - * Pings server every `this.pingInterval` and expects response - * within `this.pingTimeout` or closes connection. - * - * @api private - */ - -Socket.prototype.setPing = function () { - var self = this; - clearTimeout(self.pingIntervalTimer); - self.pingIntervalTimer = setTimeout(function () { - debug('writing ping packet - expecting pong within %sms', self.pingTimeout); - self.ping(); - self.onHeartbeat(self.pingTimeout); - }, self.pingInterval); -}; - -/** -* Sends a ping packet. -* -* @api private -*/ - -Socket.prototype.ping = function () { - var self = this; - this.sendPacket('ping', function () { - self.emit('ping'); - }); -}; - -/** - * Called on `drain` event - * - * @api private - */ - -Socket.prototype.onDrain = function () { - this.writeBuffer.splice(0, this.prevBufferLen); - - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; - - if (0 === this.writeBuffer.length) { - this.emit('drain'); - } else { - this.flush(); - } -}; - -/** - * Flush write buffers. - * - * @api private - */ - -Socket.prototype.flush = function () { - if ('closed' !== this.readyState && this.transport.writable && - !this.upgrading && this.writeBuffer.length) { - debug('flushing %d packets in socket', this.writeBuffer.length); - this.transport.send(this.writeBuffer); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = this.writeBuffer.length; - this.emit('flush'); - } -}; - -/** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. - * @api public - */ - -Socket.prototype.write = -Socket.prototype.send = function (msg, options, fn) { - this.sendPacket('message', msg, options, fn); - return this; -}; - -/** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ - -Socket.prototype.sendPacket = function (type, data, options, fn) { - if ('function' === typeof data) { - fn = data; - data = undefined; - } - - if ('function' === typeof options) { - fn = options; - options = null; - } - - if ('closing' === this.readyState || 'closed' === this.readyState) { - return; - } - - options = options || {}; - options.compress = false !== options.compress; - - var packet = { - type: type, - data: data, - options: options - }; - this.emit('packetCreate', packet); - this.writeBuffer.push(packet); - if (fn) this.once('flush', fn); - this.flush(); -}; - -/** - * Closes the connection. - * - * @api private - */ - -Socket.prototype.close = function () { - if ('opening' === this.readyState || 'open' === this.readyState) { - this.readyState = 'closing'; - - var self = this; - - if (this.writeBuffer.length) { - this.once('drain', function () { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - } - - function close () { - self.onClose('forced close'); - debug('socket closing - telling transport to close'); - self.transport.close(); - } - - function cleanupAndClose () { - self.removeListener('upgrade', cleanupAndClose); - self.removeListener('upgradeError', cleanupAndClose); - close(); - } - - function waitForUpgrade () { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once('upgrade', cleanupAndClose); - self.once('upgradeError', cleanupAndClose); - } - - return this; -}; - -/** - * Called upon transport error - * - * @api private - */ - -Socket.prototype.onError = function (err) { - debug('socket error %j', err); - Socket.priorWebsocketSuccess = false; - this.emit('error', err); - this.onClose('transport error', err); -}; - -/** - * Called upon transport close. - * - * @api private - */ - -Socket.prototype.onClose = function (reason, desc) { - if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) { - debug('socket close with reason: "%s"', reason); - var self = this; - - // clear timers - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); - - // stop event from firing again for transport - this.transport.removeAllListeners('close'); - - // ensure transport won't stay open - this.transport.close(); - - // ignore further transport communication - this.transport.removeAllListeners(); - - // set ready state - this.readyState = 'closed'; - - // clear session id - this.id = null; - - // emit close event - this.emit('close', reason, desc); - - // clean buffers after, so users can still - // grab the buffers on `close` event - self.writeBuffer = []; - self.prevBufferLen = 0; - } -}; - -/** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ - -Socket.prototype.filterUpgrades = function (upgrades) { - var filteredUpgrades = []; - for (var i = 0, j = upgrades.length; i < j; i++) { - if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]); - } - return filteredUpgrades; -}; - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 219 */ -/***/ (function(module, exports) { - - -/** - * Module exports. - * - * Logic borrowed from Modernizr: - * - * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js - */ - -try { - module.exports = typeof XMLHttpRequest !== 'undefined' && - 'withCredentials' in new XMLHttpRequest(); -} catch (err) { - // if XMLHttp support is disabled in IE then it will throw - // when trying to create - module.exports = false; -} - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Module requirements. - */ - -var XMLHttpRequest = __webpack_require__(84); -var Polling = __webpack_require__(124); -var Emitter = __webpack_require__(31); -var inherit = __webpack_require__(61); -var debug = __webpack_require__(15)('engine.io-client:polling-xhr'); - -/** - * Module exports. - */ - -module.exports = XHR; -module.exports.Request = Request; - -/** - * Empty function - */ - -function empty () {} - -/** - * XHR Polling constructor. - * - * @param {Object} opts - * @api public - */ - -function XHR (opts) { - Polling.call(this, opts); - this.requestTimeout = opts.requestTimeout; - this.extraHeaders = opts.extraHeaders; - - if (global.location) { - var isSSL = 'https:' === location.protocol; - var port = location.port; - - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? 443 : 80; - } - - this.xd = opts.hostname !== global.location.hostname || - port !== opts.port; - this.xs = opts.secure !== isSSL; - } -} - -/** - * Inherits from Polling. - */ - -inherit(XHR, Polling); - -/** - * XHR supports binary - */ - -XHR.prototype.supportsBinary = true; - -/** - * Creates a request. - * - * @param {String} method - * @api private - */ - -XHR.prototype.request = function (opts) { - opts = opts || {}; - opts.uri = this.uri(); - opts.xd = this.xd; - opts.xs = this.xs; - opts.agent = this.agent || false; - opts.supportsBinary = this.supportsBinary; - opts.enablesXDR = this.enablesXDR; - - // SSL options for Node.js client - opts.pfx = this.pfx; - opts.key = this.key; - opts.passphrase = this.passphrase; - opts.cert = this.cert; - opts.ca = this.ca; - opts.ciphers = this.ciphers; - opts.rejectUnauthorized = this.rejectUnauthorized; - opts.requestTimeout = this.requestTimeout; - - // other options for Node.js client - opts.extraHeaders = this.extraHeaders; - - return new Request(opts); -}; - -/** - * Sends data. - * - * @param {String} data to send. - * @param {Function} called upon flush. - * @api private - */ - -XHR.prototype.doWrite = function (data, fn) { - var isBinary = typeof data !== 'string' && data !== undefined; - var req = this.request({ method: 'POST', data: data, isBinary: isBinary }); - var self = this; - req.on('success', fn); - req.on('error', function (err) { - self.onError('xhr post error', err); - }); - this.sendXhr = req; -}; - -/** - * Starts a poll cycle. - * - * @api private - */ - -XHR.prototype.doPoll = function () { - debug('xhr poll'); - var req = this.request(); - var self = this; - req.on('data', function (data) { - self.onData(data); - }); - req.on('error', function (err) { - self.onError('xhr poll error', err); - }); - this.pollXhr = req; -}; - -/** - * Request constructor - * - * @param {Object} options - * @api public - */ - -function Request (opts) { - this.method = opts.method || 'GET'; - this.uri = opts.uri; - this.xd = !!opts.xd; - this.xs = !!opts.xs; - this.async = false !== opts.async; - this.data = undefined !== opts.data ? opts.data : null; - this.agent = opts.agent; - this.isBinary = opts.isBinary; - this.supportsBinary = opts.supportsBinary; - this.enablesXDR = opts.enablesXDR; - this.requestTimeout = opts.requestTimeout; - - // SSL options for Node.js client - this.pfx = opts.pfx; - this.key = opts.key; - this.passphrase = opts.passphrase; - this.cert = opts.cert; - this.ca = opts.ca; - this.ciphers = opts.ciphers; - this.rejectUnauthorized = opts.rejectUnauthorized; - - // other options for Node.js client - this.extraHeaders = opts.extraHeaders; - - this.create(); -} - -/** - * Mix in `Emitter`. - */ - -Emitter(Request.prototype); - -/** - * Creates the XHR object and sends the request. - * - * @api private - */ - -Request.prototype.create = function () { - var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR }; - - // SSL options for Node.js client - opts.pfx = this.pfx; - opts.key = this.key; - opts.passphrase = this.passphrase; - opts.cert = this.cert; - opts.ca = this.ca; - opts.ciphers = this.ciphers; - opts.rejectUnauthorized = this.rejectUnauthorized; - - var xhr = this.xhr = new XMLHttpRequest(opts); - var self = this; - - try { - debug('xhr open %s: %s', this.method, this.uri); - xhr.open(this.method, this.uri, this.async); - try { - if (this.extraHeaders) { - xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); - for (var i in this.extraHeaders) { - if (this.extraHeaders.hasOwnProperty(i)) { - xhr.setRequestHeader(i, this.extraHeaders[i]); - } - } - } - } catch (e) {} - - if ('POST' === this.method) { - try { - if (this.isBinary) { - xhr.setRequestHeader('Content-type', 'application/octet-stream'); - } else { - xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8'); - } - } catch (e) {} - } - - try { - xhr.setRequestHeader('Accept', '*/*'); - } catch (e) {} - - // ie6 check - if ('withCredentials' in xhr) { - xhr.withCredentials = true; - } - - if (this.requestTimeout) { - xhr.timeout = this.requestTimeout; - } - - if (this.hasXDR()) { - xhr.onload = function () { - self.onLoad(); - }; - xhr.onerror = function () { - self.onError(xhr.responseText); - }; - } else { - xhr.onreadystatechange = function () { - if (xhr.readyState === 2) { - try { - var contentType = xhr.getResponseHeader('Content-Type'); - if (self.supportsBinary && contentType === 'application/octet-stream') { - xhr.responseType = 'arraybuffer'; - } - } catch (e) {} - } - if (4 !== xhr.readyState) return; - if (200 === xhr.status || 1223 === xhr.status) { - self.onLoad(); - } else { - // make sure the `error` event handler that's user-set - // does not throw in the same tick and gets caught here - setTimeout(function () { - self.onError(xhr.status); - }, 0); - } - }; - } - - debug('xhr data %s', this.data); - xhr.send(this.data); - } catch (e) { - // Need to defer since .create() is called directly fhrom the constructor - // and thus the 'error' event can only be only bound *after* this exception - // occurs. Therefore, also, we cannot throw here at all. - setTimeout(function () { - self.onError(e); - }, 0); - return; - } - - if (global.document) { - this.index = Request.requestsCount++; - Request.requests[this.index] = this; - } -}; - -/** - * Called upon successful response. - * - * @api private - */ - -Request.prototype.onSuccess = function () { - this.emit('success'); - this.cleanup(); -}; - -/** - * Called if we have data. - * - * @api private - */ - -Request.prototype.onData = function (data) { - this.emit('data', data); - this.onSuccess(); -}; - -/** - * Called upon error. - * - * @api private - */ - -Request.prototype.onError = function (err) { - this.emit('error', err); - this.cleanup(true); -}; - -/** - * Cleans up house. - * - * @api private - */ - -Request.prototype.cleanup = function (fromError) { - if ('undefined' === typeof this.xhr || null === this.xhr) { - return; - } - // xmlhttprequest - if (this.hasXDR()) { - this.xhr.onload = this.xhr.onerror = empty; - } else { - this.xhr.onreadystatechange = empty; - } - - if (fromError) { - try { - this.xhr.abort(); - } catch (e) {} - } - - if (global.document) { - delete Request.requests[this.index]; - } - - this.xhr = null; -}; - -/** - * Called upon load. - * - * @api private - */ - -Request.prototype.onLoad = function () { - var data; - try { - var contentType; - try { - contentType = this.xhr.getResponseHeader('Content-Type'); - } catch (e) {} - if (contentType === 'application/octet-stream') { - data = this.xhr.response || this.xhr.responseText; - } else { - data = this.xhr.responseText; - } - } catch (e) { - this.onError(e); - } - if (null != data) { - this.onData(data); - } -}; - -/** - * Check if it has XDomainRequest. - * - * @api private - */ - -Request.prototype.hasXDR = function () { - return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR; -}; - -/** - * Aborts the request. - * - * @api public - */ - -Request.prototype.abort = function () { - this.cleanup(); -}; - -/** - * Aborts pending requests when unloading the window. This is needed to prevent - * memory leaks (e.g. when using IE) and to ensure that no spurious error is - * emitted. - */ - -Request.requestsCount = 0; -Request.requests = {}; - -if (global.document) { - if (global.attachEvent) { - global.attachEvent('onunload', unloadHandler); - } else if (global.addEventListener) { - global.addEventListener('beforeunload', unloadHandler, false); - } -} - -function unloadHandler () { - for (var i in Request.requests) { - if (Request.requests.hasOwnProperty(i)) { - Request.requests[i].abort(); - } - } -} - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 221 */ -/***/ (function(module, exports) { - - -/** - * Gets the keys for an object. - * - * @return {Array} keys - * @api private - */ - -module.exports = Object.keys || function keys (obj){ - var arr = []; - var has = Object.prototype.hasOwnProperty; - - for (var i in obj) { - if (has.call(obj, i)) { - arr.push(i); - } - } - return arr; -}; - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 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 - - for (var 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('') -} - - -/***/ }), -/* 223 */ -/***/ (function(module, exports) { - -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 -} - - -/***/ }), -/* 224 */ -/***/ (function(module, exports) { - -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - - -/***/ }), -/* 225 */ -/***/ (function(module, exports) { - -/** - * An abstraction for slicing an arraybuffer even when - * ArrayBuffer.prototype.slice is not supported - * - * @api public - */ - -module.exports = function(arraybuffer, start, end) { - var bytes = arraybuffer.byteLength; - start = start || 0; - end = end || bytes; - - if (arraybuffer.slice) { return arraybuffer.slice(start, end); } - - if (start < 0) { start += bytes; } - if (end < 0) { end += bytes; } - if (end > bytes) { end = bytes; } - - if (start >= bytes || start >= end || bytes === 0) { - return new ArrayBuffer(0); - } - - var abv = new Uint8Array(arraybuffer); - var result = new Uint8Array(end - start); - for (var i = start, ii = 0; i < end; i++, ii++) { - result[ii] = abv[i]; - } - return result.buffer; -}; - - -/***/ }), -/* 226 */ -/***/ (function(module, exports) { - -module.exports = after - -function after(count, callback, err_cb) { - var bail = false - err_cb = err_cb || noop - proxy.count = count - - return (count === 0) ? callback() : proxy - - function proxy(err, result) { - if (proxy.count <= 0) { - throw new Error('after called too many times') - } - --proxy.count - - // after first error, rest are passed to err_cb - if (err) { - bail = true - callback(err) - // future error callbacks will go to error handler - callback = err_cb - } else if (proxy.count === 0 && !bail) { - callback(null, result) - } - } -} - -function noop() {} - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/utf8js v2.1.2 by @mathias */ -;(function(root) { - - // Detect free variables `exports` - var freeExports = typeof exports == 'object' && exports; - - // Detect free variable `module` - var freeModule = typeof module == 'object' && module && - module.exports == freeExports && module; - - // Detect free variable `global`, from Node.js or Browserified code, - // and use it as `root` - var freeGlobal = typeof global == 'object' && global; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - var stringFromCharCode = String.fromCharCode; - - // Taken from https://mths.be/punycode - function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - var value; - var extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - // Taken from https://mths.be/punycode - function ucs2encode(array) { - var length = array.length; - var index = -1; - var value; - var output = ''; - while (++index < length) { - value = array[index]; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - } - return output; - } - - function checkScalarValue(codePoint, strict) { - if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { - if (strict) { - throw Error( - 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() + - ' is not a scalar value' - ); - } - return false; - } - return true; - } - /*--------------------------------------------------------------------------*/ - - function createByte(codePoint, shift) { - return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); - } - - function encodeCodePoint(codePoint, strict) { - if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence - return stringFromCharCode(codePoint); - } - var symbol = ''; - if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence - symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0); - } - else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence - if (!checkScalarValue(codePoint, strict)) { - codePoint = 0xFFFD; - } - symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0); - symbol += createByte(codePoint, 6); - } - else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence - symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0); - symbol += createByte(codePoint, 12); - symbol += createByte(codePoint, 6); - } - symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); - return symbol; - } - - function utf8encode(string, opts) { - opts = opts || {}; - var strict = false !== opts.strict; - - var codePoints = ucs2decode(string); - var length = codePoints.length; - var index = -1; - var codePoint; - var byteString = ''; - while (++index < length) { - codePoint = codePoints[index]; - byteString += encodeCodePoint(codePoint, strict); - } - return byteString; - } - - /*--------------------------------------------------------------------------*/ - - function readContinuationByte() { - if (byteIndex >= byteCount) { - throw Error('Invalid byte index'); - } - - var continuationByte = byteArray[byteIndex] & 0xFF; - byteIndex++; - - if ((continuationByte & 0xC0) == 0x80) { - return continuationByte & 0x3F; - } - - // If we end up here, it’s not a continuation byte - throw Error('Invalid continuation byte'); - } - - function decodeSymbol(strict) { - var byte1; - var byte2; - var byte3; - var byte4; - var codePoint; - - if (byteIndex > byteCount) { - throw Error('Invalid byte index'); - } - - if (byteIndex == byteCount) { - return false; - } - - // Read first byte - byte1 = byteArray[byteIndex] & 0xFF; - byteIndex++; - - // 1-byte sequence (no continuation bytes) - if ((byte1 & 0x80) == 0) { - return byte1; - } - - // 2-byte sequence - if ((byte1 & 0xE0) == 0xC0) { - byte2 = readContinuationByte(); - codePoint = ((byte1 & 0x1F) << 6) | byte2; - if (codePoint >= 0x80) { - return codePoint; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 3-byte sequence (may include unpaired surrogates) - if ((byte1 & 0xF0) == 0xE0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3; - if (codePoint >= 0x0800) { - return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD; - } else { - throw Error('Invalid continuation byte'); - } - } - - // 4-byte sequence - if ((byte1 & 0xF8) == 0xF0) { - byte2 = readContinuationByte(); - byte3 = readContinuationByte(); - byte4 = readContinuationByte(); - codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | - (byte3 << 0x06) | byte4; - if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { - return codePoint; - } - } - - throw Error('Invalid UTF-8 detected'); - } - - var byteArray; - var byteCount; - var byteIndex; - function utf8decode(byteString, opts) { - opts = opts || {}; - var strict = false !== opts.strict; - - byteArray = ucs2decode(byteString); - byteCount = byteArray.length; - byteIndex = 0; - var codePoints = []; - var tmp; - while ((tmp = decodeSymbol(strict)) !== false) { - codePoints.push(tmp); - } - return ucs2encode(codePoints); - } - - /*--------------------------------------------------------------------------*/ - - var utf8 = { - 'version': '2.1.2', - 'encode': utf8encode, - 'decode': utf8decode - }; - - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - true - ) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return utf8; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (freeExports && !freeExports.nodeType) { - if (freeModule) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = utf8; - } else { // in Narwhal or RingoJS v0.7.0- - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - for (var key in utf8) { - hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]); - } - } - } else { // in Rhino or a web browser - root.utf8 = utf8; - } - -}(this)); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(59)(module), __webpack_require__(3))) - -/***/ }), -/* 228 */ -/***/ (function(module, exports) { - -/* - * base64-arraybuffer - * https://github.com/niklasvh/base64-arraybuffer - * - * Copyright (c) 2012 Niklas von Hertzen - * Licensed under the MIT license. - */ -(function(){ - "use strict"; - - var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - // Use a lookup table to find the index. - var lookup = new Uint8Array(256); - for (var i = 0; i < chars.length; i++) { - lookup[chars.charCodeAt(i)] = i; - } - - exports.encode = function(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), - i, len = bytes.length, base64 = ""; - - for (i = 0; i < len; i+=3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += chars[bytes[i + 2] & 63]; - } - - if ((len % 3) === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } - - return base64; - }; - - exports.decode = function(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, i, p = 0, - encoded1, encoded2, encoded3, encoded4; - - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; - } - } - - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); - - for (i = 0; i < len; i+=4) { - encoded1 = lookup[base64.charCodeAt(i)]; - encoded2 = lookup[base64.charCodeAt(i+1)]; - encoded3 = lookup[base64.charCodeAt(i+2)]; - encoded4 = lookup[base64.charCodeAt(i+3)]; - - bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); - bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); - bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); - } - - return arraybuffer; - }; -})(); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) {/** - * Create a blob builder even when vendor prefixes exist - */ - -var BlobBuilder = global.BlobBuilder - || global.WebKitBlobBuilder - || global.MSBlobBuilder - || global.MozBlobBuilder; - -/** - * Check if Blob constructor is supported - */ - -var blobSupported = (function() { - try { - var a = new Blob(['hi']); - return a.size === 2; - } catch(e) { - return false; - } -})(); - -/** - * Check if Blob constructor supports ArrayBufferViews - * Fails in Safari 6, so we need to map to ArrayBuffers there. - */ - -var blobSupportsArrayBufferView = blobSupported && (function() { - try { - var b = new Blob([new Uint8Array([1,2])]); - return b.size === 2; - } catch(e) { - return false; - } -})(); - -/** - * Check if BlobBuilder is supported - */ - -var blobBuilderSupported = BlobBuilder - && BlobBuilder.prototype.append - && BlobBuilder.prototype.getBlob; - -/** - * Helper function that maps ArrayBufferViews to ArrayBuffers - * Used by BlobBuilder constructor and old browsers that didn't - * support it in the Blob constructor. - */ - -function mapArrayBufferViews(ary) { - for (var i = 0; i < ary.length; i++) { - var chunk = ary[i]; - if (chunk.buffer instanceof ArrayBuffer) { - var buf = chunk.buffer; - - // if this is a subarray, make a copy so we only - // include the subarray region from the underlying buffer - if (chunk.byteLength !== buf.byteLength) { - var copy = new Uint8Array(chunk.byteLength); - copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); - buf = copy.buffer; - } - - ary[i] = buf; - } - } -} - -function BlobBuilderConstructor(ary, options) { - options = options || {}; - - var bb = new BlobBuilder(); - mapArrayBufferViews(ary); - - for (var i = 0; i < ary.length; i++) { - bb.append(ary[i]); - } - - return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); -}; - -function BlobConstructor(ary, options) { - mapArrayBufferViews(ary); - return new Blob(ary, options || {}); -}; - -module.exports = (function() { - if (blobSupported) { - return blobSupportsArrayBufferView ? global.Blob : BlobConstructor; - } else if (blobBuilderSupported) { - return BlobBuilderConstructor; - } else { - return undefined; - } -})(); - -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - -/* WEBPACK VAR INJECTION */(function(global) { -/** - * Module requirements. - */ - -var Polling = __webpack_require__(124); -var inherit = __webpack_require__(61); - -/** - * Module exports. - */ - -module.exports = JSONPPolling; - -/** - * Cached regular expressions. - */ - -var rNewline = /\n/g; -var rEscapedNewline = /\\n/g; - -/** - * Global JSONP callbacks. - */ - -var callbacks; - -/** - * Noop. - */ - -function empty () { } - -/** - * JSONP Polling constructor. - * - * @param {Object} opts. - * @api public - */ - -function JSONPPolling (opts) { - Polling.call(this, opts); - - this.query = this.query || {}; - - // define global callbacks array if not present - // we do this here (lazily) to avoid unneeded global pollution - if (!callbacks) { - // we need to consider multiple engines in the same page - if (!global.___eio) global.___eio = []; - callbacks = global.___eio; - } - - // callback identifier - this.index = callbacks.length; - - // add callback to jsonp global - var self = this; - callbacks.push(function (msg) { - self.onData(msg); - }); - - // append to query string - this.query.j = this.index; - - // prevent spurious errors from being emitted when the window is unloaded - if (global.document && global.addEventListener) { - global.addEventListener('beforeunload', function () { - if (self.script) self.script.onerror = empty; - }, false); - } -} - -/** - * Inherits from Polling. - */ - -inherit(JSONPPolling, Polling); - -/* - * JSONP only supports binary as base64 encoded strings - */ - -JSONPPolling.prototype.supportsBinary = false; - -/** - * Closes the socket. - * - * @api private - */ - -JSONPPolling.prototype.doClose = function () { - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; - } - - if (this.form) { - this.form.parentNode.removeChild(this.form); - this.form = null; - this.iframe = null; - } - - Polling.prototype.doClose.call(this); -}; - -/** - * Starts a poll cycle. - * - * @api private - */ - -JSONPPolling.prototype.doPoll = function () { - var self = this; - var script = document.createElement('script'); - - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; - } - - script.async = true; - script.src = this.uri(); - script.onerror = function (e) { - self.onError('jsonp poll error', e); - }; - - var insertAt = document.getElementsByTagName('script')[0]; - if (insertAt) { - insertAt.parentNode.insertBefore(script, insertAt); - } else { - (document.head || document.body).appendChild(script); - } - this.script = script; - - var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent); - - if (isUAgecko) { - setTimeout(function () { - var iframe = document.createElement('iframe'); - document.body.appendChild(iframe); - document.body.removeChild(iframe); - }, 100); - } -}; - -/** - * Writes with a hidden iframe. - * - * @param {String} data to send - * @param {Function} called upon flush. - * @api private - */ - -JSONPPolling.prototype.doWrite = function (data, fn) { - var self = this; - - if (!this.form) { - var form = document.createElement('form'); - var area = document.createElement('textarea'); - var id = this.iframeId = 'eio_iframe_' + this.index; - var iframe; - - form.className = 'socketio'; - form.style.position = 'absolute'; - form.style.top = '-1000px'; - form.style.left = '-1000px'; - form.target = id; - form.method = 'POST'; - form.setAttribute('accept-charset', 'utf-8'); - area.name = 'd'; - form.appendChild(area); - document.body.appendChild(form); - - this.form = form; - this.area = area; - } - - this.form.action = this.uri(); - - function complete () { - initIframe(); - fn(); - } - - function initIframe () { - if (self.iframe) { - try { - self.form.removeChild(self.iframe); - } catch (e) { - self.onError('jsonp polling iframe removal error', e); - } - } - - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - var html = '