From 9a09e206ae1da36f19c692f545791ab0ee958f7f Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 12:02:07 -0400 Subject: [PATCH 001/257] refactor contract build method --- lib/contracts.js | 255 ++++++++++++++++++++++++++--------------------- lib/index.js | 7 +- 2 files changed, 142 insertions(+), 120 deletions(-) diff --git a/lib/contracts.js b/lib/contracts.js index c8f5c245..66215cfc 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -1,5 +1,6 @@ var Compiler = require('./compiler.js'); var toposort = require('toposort'); +var async = require('async'); // TODO: create a contract object @@ -17,129 +18,155 @@ ContractsManager.prototype.compileContracts = function() { return compiler.compile_solidity(this.contractFiles); }; -ContractsManager.prototype.build = function() { - this.compiledContracts = this.compileContracts(); - var className; - var contract; - - // go through config file first - for(className in this.contractsConfig.contracts) { - contract = this.contractsConfig.contracts[className]; - - contract.className = className; - contract.args = contract.args || []; - - this.contracts[className] = contract; - } - - // compile contracts - for(className in this.compiledContracts) { - var compiledContract = this.compiledContracts[className]; - var contractConfig = this.contractsConfig.contracts[className]; - - contract = this.contracts[className] || {className: className, args: []}; - - contract.code = compiledContract.code; - contract.runtimeBytecode = compiledContract.runtimeBytecode; - contract.gasEstimates = compiledContract.gasEstimates; - contract.functionHashes = compiledContract.functionHashes; - contract.abiDefinition = compiledContract.abiDefinition; - contract.gas = (contractConfig && contractConfig.gas) || this.contractsConfig.gas; - - if (contract.deploy === undefined) { - contract.deploy = true; - } - - if (contract.gas === 'auto') { - var maxGas; - if (contract.deploy) { - maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000); - } else { - maxGas = 500000; +ContractsManager.prototype.build = function(done) { + var self = this; + async.waterfall([ + function compileContracts(callback) { + var compiler = new Compiler(); + try { + self.compiledContracts = compiler.compile_solidity(self.contractFiles); + callback(); + } catch(err) { + callback(new Error(err.message)); } - // TODO: put a check so it doesn't go over the block limit - var adjustedGas = Math.round(maxGas * 1.40); - contract.gas = adjustedGas; - } - contract.gasPrice = contract.gasPrice || this.contractsConfig.gasPrice; - contract.type = 'file'; - contract.className = className; + }, + function prepareContractsFromConfig(callback) { + var className, contract; + for(className in self.contractsConfig.contracts) { + contract = self.contractsConfig.contracts[className]; - this.contracts[className] = contract; - } + contract.className = className; + contract.args = contract.args || []; - // deal with special configs - for(className in this.contracts) { - contract = this.contracts[className]; - - // if deploy intention is not specified default is true - if (contract.deploy === undefined) { - contract.deploy = true; - } - - if (contract.instanceOf !== undefined) { - var parentContractName = contract.instanceOf; - var parentContract = this.contracts[parentContractName]; - - if (parentContract === className) { - this.logger.error(className + ": instanceOf is set to itself"); - continue; + self.contracts[className] = contract; } + callback(); + }, + function prepareContractsFromCompilation(callback) { + var className, compiledContract, contractConfig, contract; + var maxGas, adjustedGas; + for(className in self.compiledContracts) { + compiledContract = self.compiledContracts[className]; + contractConfig = self.contractsConfig.contracts[className]; - if (parentContract === undefined) { - this.logger.error(className + ": couldn't find instanceOf contract " + parentContractName); - continue; - } + contract = self.contracts[className] || {className: className, args: []}; - if (parentContract.args && parentContract.args.length > 0 && contract.args === []) { - contract.args = parentContract.args; - } + contract.code = compiledContract.code; + contract.runtimeBytecode = compiledContract.runtimeBytecode; + contract.gasEstimates = compiledContract.gasEstimates; + contract.functionHashes = compiledContract.functionHashes; + contract.abiDefinition = compiledContract.abiDefinition; + contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas; - if (contract.code !== undefined) { - this.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName); - } - - contract.code = parentContract.code; - contract.runtimeBytecode = parentContract.runtimeBytecode; - contract.gasEstimates = parentContract.gasEstimates; - contract.functionHashes = parentContract.functionHashes; - contract.abiDefinition = parentContract.abiDefinition; - - contract.gas = contract.gas || parentContract.gas; - contract.gasPrice = contract.gasPrice || parentContract.gasPrice; - } - } - - // remove contracts that don't have code - for(className in this.contracts) { - contract = this.contracts[className]; - - if (contract.code === undefined) { - this.logger.error(className + " has no code associated"); - delete this.contracts[className]; - } - } - - this.logger.trace(this.contracts); - - // determine dependencies - for(className in this.contracts) { - contract = this.contracts[className]; - - if (contract.args === []) continue; - - var ref = contract.args; - for (var j = 0; j < ref.length; j++) { - var arg = ref[j]; - if (arg[0] === "$") { - if (this.contractDependencies[className] === void 0) { - this.contractDependencies[className] = []; + if (contract.deploy === undefined) { + contract.deploy = true; } - this.contractDependencies[className].push(arg.substr(1)); - } - } - } + if (contract.gas === 'auto') { + if (contract.deploy) { + maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000); + } else { + maxGas = 500000; + } + // TODO: put a check so it doesn't go over the block limit + adjustedGas = Math.round(maxGas * 1.40); + contract.gas = adjustedGas; + } + contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice; + contract.type = 'file'; + contract.className = className; + + self.contracts[className] = contract; + } + callback(); + }, + function dealWithSpecialConfigs(callback) { + var className, contract, parentContractName, parentContract; + + for(className in self.contracts) { + contract = self.contracts[className]; + + // if deploy intention is not specified default is true + if (contract.deploy === undefined) { + contract.deploy = true; + } + + if (contract.instanceOf !== undefined) { + parentContractName = contract.instanceOf; + parentContract = self.contracts[parentContractName]; + + if (parentContract === className) { + self.logger.error(className + ": instanceOf is set to itself"); + continue; + } + + if (parentContract === undefined) { + slef.logger.error(className + ": couldn't find instanceOf contract " + parentContractName); + continue; + } + + if (parentContract.args && parentContract.args.length > 0 && contract.args === []) { + contract.args = parentContract.args; + } + + if (contract.code !== undefined) { + self.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName); + } + + contract.code = parentContract.code; + contract.runtimeBytecode = parentContract.runtimeBytecode; + contract.gasEstimates = parentContract.gasEstimates; + contract.functionHashes = parentContract.functionHashes; + contract.abiDefinition = parentContract.abiDefinition; + + contract.gas = contract.gas || parentContract.gas; + contract.gasPrice = contract.gasPrice || parentContract.gasPrice; + } + } + callback(); + }, + function removeContractsWithNoCode(callback) { + var className, contract; + for(className in self.contracts) { + contract = self.contracts[className]; + + if (contract.code === undefined) { + self.logger.error(className + " has no code associated"); + delete self.contracts[className]; + } + } + self.logger.trace(self.contracts); + callback(); + }, + function determineDependencies(callback) { + var className, contract; + for(className in self.contracts) { + contract = self.contracts[className]; + + if (contract.args === []) continue; + + var ref = contract.args; + for (var j = 0; j < ref.length; j++) { + var arg = ref[j]; + if (arg[0] === "$") { + if (self.contractDependencies[className] === void 0) { + self.contractDependencies[className] = []; + } + self.contractDependencies[className].push(arg.substr(1)); + } + } + } + callback(); + } + ], function(err, result) { + self.logger.trace("finished".underline); + if (err) { + //self.logger.debug(err.stack); + done(err); + } else { + done(null, self); + } + }); }; ContractsManager.prototype.getContract = function(className) { diff --git a/lib/index.js b/lib/index.js index 74c7150f..1358794d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -143,12 +143,7 @@ var Embark = { contractsConfig: self.config.contractsConfig, logger: Embark.logger }); - try { - contractsManager.build(); - callback(null, contractsManager); - } catch(err) { - callback(new Error(err.message)); - } + contractsManager.build(callback); }, function deployContracts(contractsManager, callback) { From 814c2bc4a43b2379de26aca79b3081dec5de5f61 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 12:15:50 -0400 Subject: [PATCH 002/257] return callbacks --- lib/contracts.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/contracts.js b/lib/contracts.js index 66215cfc..2aa12f57 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -25,9 +25,9 @@ ContractsManager.prototype.build = function(done) { var compiler = new Compiler(); try { self.compiledContracts = compiler.compile_solidity(self.contractFiles); - callback(); + return callback(); } catch(err) { - callback(new Error(err.message)); + return callback(new Error(err.message)); } }, function prepareContractsFromConfig(callback) { From bd3b05bb00701e56327ef46d431d47df5c88aafb Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 12:24:13 -0400 Subject: [PATCH 003/257] refactor condition to avoid checking for void 0 --- lib/contracts.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/contracts.js b/lib/contracts.js index 2aa12f57..0c648571 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -149,9 +149,7 @@ ContractsManager.prototype.build = function(done) { for (var j = 0; j < ref.length; j++) { var arg = ref[j]; if (arg[0] === "$") { - if (self.contractDependencies[className] === void 0) { - self.contractDependencies[className] = []; - } + self.contractDependencies[className] = self.contractDependencies[className] || []; self.contractDependencies[className].push(arg.substr(1)); } } From 60f487da380cba2623c61223f9ef9c4d730f4fb9 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 12:35:16 -0400 Subject: [PATCH 004/257] use path join --- lib/blockchain.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/blockchain.js b/lib/blockchain.js index 32fe06e5..7e060ce5 100644 --- a/lib/blockchain.js +++ b/lib/blockchain.js @@ -2,6 +2,7 @@ var mkdirp = require('mkdirp'); var wrench = require('wrench'); var colors = require('colors'); var GethCommands = require('./geth_commands.js'); +var path = require('path'); var Blockchain = function(blockchainConfig, Client) { this.blockchainConfig = blockchainConfig; @@ -54,7 +55,7 @@ Blockchain.prototype.initChainAndGetAddress = function() { mkdirp.sync(this.datadir); // copy mining script - wrench.copyDirSyncRecursive(__dirname + "/../js", ".embark/development/js", {forceDelete: true}); + wrench.copyDirSyncRecursive(path.join(__dirname, "/../js"), ".embark/development/js", {forceDelete: true}); // check if an account already exists, create one if not, return address result = this.runCommand(this.client.listAccountsCommand()); From 549e33317bbb3d400294e6355b8a168d15762ad2 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 13:50:54 -0400 Subject: [PATCH 005/257] use path join --- lib/config.js | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/config.js b/lib/config.js index bb06a942..f7aafb6d 100644 --- a/lib/config.js +++ b/lib/config.js @@ -1,6 +1,7 @@ var fs = require('fs'); var grunt = require('grunt'); var merge = require('merge'); +var path = require('path'); // TODO: add wrapper for fs so it can also work in the browser // can work with both read and save @@ -81,11 +82,9 @@ Config.prototype.loadFiles = function(files) { return file.indexOf('.') >= 0; }).filter(function(file) { if (file === 'embark.js') { - //readFiles.push({filename: 'bluebird.js', content: fs.readFileSync("../js/bluebird.js").toString()}); - readFiles.push({filename: 'web3.js', content: fs.readFileSync(__dirname + "/../js/web3.js").toString()}); - //readFiles.push({filename: 'embark.js', content: fs.readFileSync("../js/ipfs.js").toString()+ fs.readFileSync("../js/build/embark.bundle.js").toString()}); - readFiles.push({filename: 'ipfs.js', content: fs.readFileSync(__dirname + "/../js/ipfs.js").toString()}); - readFiles.push({filename: 'embark.js', content: fs.readFileSync(__dirname + "/../js/build/embark.bundle.js").toString()}); + readFiles.push({filename: 'web3.js', content: fs.readFileSync(path.join(__dirname, "/../js/web3.js")).toString()}); + readFiles.push({filename: 'ipfs.js', content: fs.readFileSync(path.join(__dirname, "/../js/ipfs.js")).toString()}); + readFiles.push({filename: 'embark.js', content: fs.readFileSync(path.join(__dirname, "/../js/build/embark.bundle.js")).toString()}); } else { readFiles.push({filename: file, content: fs.readFileSync(file).toString()}); } From 06879ccdd62edc18137cb64ef007e41c7872cd32 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 13:55:06 -0400 Subject: [PATCH 006/257] return callback --- lib/deploy.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/deploy.js b/lib/deploy.js index 8c73e565..8e43994e 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -60,7 +60,7 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { self.logger.info(contract.className + " already deployed " + trackedContract.address); contract.deployedAddress = trackedContract.address; self.logger.contractsState(self.contractsManager.contractsState()); - callback(); + return callback(); } else { // determine arguments From 41273a451751112a64fabaed25bba74993ecc644 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 14:07:42 -0400 Subject: [PATCH 007/257] remove trailing commas --- lib/monitor.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/monitor.js b/lib/monitor.js index 94e94aaf..2ef7c569 100644 --- a/lib/monitor.js +++ b/lib/monitor.js @@ -272,13 +272,13 @@ Dashboard.prototype.layoutStatus = function() { label: "Available Services", tags: true, padding: this.minimal ? { - left: 1, + left: 1 } : 1, width: "100%", height: "60%", valign: "top", border: { - type: "line", + type: "line" }, style: { fg: -1, From caaf3acde530b943a4d53de9c64275532b39b91b Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 14:13:06 -0400 Subject: [PATCH 008/257] use path join --- lib/template_generator.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/template_generator.js b/lib/template_generator.js index f140b104..3cee1ee7 100644 --- a/lib/template_generator.js +++ b/lib/template_generator.js @@ -14,7 +14,7 @@ var TemplateGenerator = function(templateName) { }; TemplateGenerator.prototype.generate = function(destinationFolder, name) { - var templatePath = path.join(__dirname + '/../' + this.templateName); + var templatePath = path.join(__dirname, '/../', this.templateName); wrench.copyDirSyncRecursive(templatePath, destinationFolder + name); From 60285ea1c050c3a75a653d7d49a57f35e4166c3a Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 21:41:50 -0400 Subject: [PATCH 009/257] support specifying web server hostname through -b option --- lib/cmd.js | 9 +++++++-- lib/index.js | 7 ++++++- lib/server.js | 5 +++-- lib/services.js | 3 ++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/cmd.js b/lib/cmd.js index 78173758..f9dac0b7 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -62,13 +62,18 @@ Cmd.prototype.run = function() { var self = this; program .command('run [environment]') - .option('-p, --port [port]', 'port to run the dev webserver') + .option('-p, --port [port]', 'port to run the dev webserver (default: 8000)') + .option('-b, --host [host]', 'host to run the dev webserver (default: localhost)') .description('run dapp (default: development)') .action(function(env, options) { self.Embark.initConfig(env || 'development', { embarkConfig: 'embark.json' }); - self.Embark.run({env: env || 'development', serverPort: options.port}); + self.Embark.run({ + env: env || 'development', + serverPort: options.port, + serverHost: options.host + }); }); }; diff --git a/lib/index.js b/lib/index.js index 1358794d..a6de53f7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -80,6 +80,7 @@ var Embark = { Embark.servicesMonitor = new ServicesMonitor({ logger: Embark.logger, config: Embark.config, + serverHost: options.serverHost, serverPort: options.serverPort }); Embark.servicesMonitor.startMonitor(); @@ -88,7 +89,11 @@ var Embark = { self.buildDeployGenerate.bind(self), function startAssetServer(callback) { Embark.monitor.setStatus("Starting Server"); - var server = new Server({logger: self.logger, port: options.serverPort}); + var server = new Server({ + logger: self.logger, + host: options.serverHost, + port: options.serverPort + }); server.start(callback); }, function watchFilesForChanges(callback) { diff --git a/lib/server.js b/lib/server.js index 4af23bb6..fd32c4c5 100644 --- a/lib/server.js +++ b/lib/server.js @@ -5,6 +5,7 @@ var serveStatic = require('serve-static'); var Server = function(options) { this.dist = options.dist || 'dist/'; this.port = options.port || 8000; + this.hostname = options.host || 'localhost'; this.logger = options.logger; }; @@ -15,8 +16,8 @@ Server.prototype.start = function(callback) { serve(req, res, finalhandler(req, res)); }); - this.logger.info(("listening on port " + this.port).underline.green); - server.listen(this.port) ; + this.logger.info(("webserver available at http://" + this.hostname + ":" + this.port).underline.green); + server.listen(this.port, this.hostname) ; callback(); }; diff --git a/lib/services.js b/lib/services.js index 5e4f2f50..2fbec303 100644 --- a/lib/services.js +++ b/lib/services.js @@ -6,6 +6,7 @@ var ServicesMonitor = function(options) { this.logger = options.logger; this.interval = options.interval || 5000; this.config = options.config; + this.serverHost = options.serverHost || 'localhost'; this.serverPort = options.serverPort || 8000; }; @@ -64,7 +65,7 @@ ServicesMonitor.prototype.check = function() { }, function checkDevServer(result, callback) { self.logger.trace('checkDevServer'); - result.push(('dev server (http://localhost:' + self.serverPort + ')').green); + result.push(('dev server (http://' + self.serverHost + ':' + self.serverPort + ')').green); callback(null, result); } ], function(err, result) { From 655f56f893a94e4d4c1271e4e02768b14c13a432 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 22:00:54 -0400 Subject: [PATCH 010/257] support --noserver option --- lib/cmd.js | 4 +++- lib/index.js | 6 +++++- lib/services.js | 5 ++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/cmd.js b/lib/cmd.js index f9dac0b7..3dde287c 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -64,6 +64,7 @@ Cmd.prototype.run = function() { .command('run [environment]') .option('-p, --port [port]', 'port to run the dev webserver (default: 8000)') .option('-b, --host [host]', 'host to run the dev webserver (default: localhost)') + .option('--noserver', 'disable the development webserver') .description('run dapp (default: development)') .action(function(env, options) { self.Embark.initConfig(env || 'development', { @@ -72,7 +73,8 @@ Cmd.prototype.run = function() { self.Embark.run({ env: env || 'development', serverPort: options.port, - serverHost: options.host + serverHost: options.host, + runWebserver: !options.noserver }); }); }; diff --git a/lib/index.js b/lib/index.js index a6de53f7..82334d8e 100644 --- a/lib/index.js +++ b/lib/index.js @@ -81,13 +81,17 @@ var Embark = { logger: Embark.logger, config: Embark.config, serverHost: options.serverHost, - serverPort: options.serverPort + serverPort: options.serverPort, + runWebserver: options.runWebserver }); Embark.servicesMonitor.startMonitor(); callback(); }, self.buildDeployGenerate.bind(self), function startAssetServer(callback) { + if (!options.runWebserver) { + return callback(); + } Embark.monitor.setStatus("Starting Server"); var server = new Server({ logger: self.logger, diff --git a/lib/services.js b/lib/services.js index 2fbec303..e59f685e 100644 --- a/lib/services.js +++ b/lib/services.js @@ -8,6 +8,7 @@ var ServicesMonitor = function(options) { this.config = options.config; this.serverHost = options.serverHost || 'localhost'; this.serverPort = options.serverPort || 8000; + this.runWebserver = options.runWebserver; }; ServicesMonitor.prototype.startMonitor = function() { @@ -65,7 +66,9 @@ ServicesMonitor.prototype.check = function() { }, function checkDevServer(result, callback) { self.logger.trace('checkDevServer'); - result.push(('dev server (http://' + self.serverHost + ':' + self.serverPort + ')').green); + var devServer = 'dev server (http://' + self.serverHost + ':' + self.serverPort + ')'; + devServer = (self.runWebserver) ? devServer.green : devServer.red; + result.push(devServer); callback(null, result); } ], function(err, result) { From 7bccb73f01af9376db5ffc149283f699bf98550b Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 22:30:41 -0400 Subject: [PATCH 011/257] support --dashboard option --- lib/cmd.js | 4 +++- lib/index.js | 30 ++++++++++++++++++++++-------- lib/logger.js | 5 +++-- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/lib/cmd.js b/lib/cmd.js index 3dde287c..50419d53 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -65,6 +65,7 @@ Cmd.prototype.run = function() { .option('-p, --port [port]', 'port to run the dev webserver (default: 8000)') .option('-b, --host [host]', 'host to run the dev webserver (default: localhost)') .option('--noserver', 'disable the development webserver') + .option('--nodashboard', 'simple mode, disables the dashboard') .description('run dapp (default: development)') .action(function(env, options) { self.Embark.initConfig(env || 'development', { @@ -74,7 +75,8 @@ Cmd.prototype.run = function() { env: env || 'development', serverPort: options.port, serverHost: options.host, - runWebserver: !options.noserver + runWebserver: !options.noserver, + useDashboard: !options.nodashboard }); }); }; diff --git a/lib/index.js b/lib/index.js index 82334d8e..0671fbb6 100644 --- a/lib/index.js +++ b/lib/index.js @@ -63,20 +63,34 @@ var Embark = { var self = this; var env = options.env; async.waterfall([ + function welcome(callback) { + if (!options.useDashboard) { + console.log('========================'.bold.green); + console.log('Welcome to Embark 2.1.2'.yellow.bold); + console.log('========================'.bold.green); + } + callback(); + }, function startConsole(callback) { Embark.console = new Console(); callback(); }, function startMonitor(callback) { + if (!options.useDashboard) { + return callback(); + } Embark.monitor = new Monitor({env: env, console: Embark.console}); - Embark.monitor.setStatus("Starting"); self.logger.logFunction = Embark.monitor.logEntry; self.logger.contractsState = Embark.monitor.setContracts; self.logger.availableServices = Embark.monitor.availableServices; + self.logger.setStatus = Embark.monitor.setStatus.bind(Embark.monitor); // TODO: do this after monitor is rendered callback(); }, function monitorServices(callback) { + if (!options.useDashboard) { + return callback(); + } Embark.servicesMonitor = new ServicesMonitor({ logger: Embark.logger, config: Embark.config, @@ -92,7 +106,7 @@ var Embark = { if (!options.runWebserver) { return callback(); } - Embark.monitor.setStatus("Starting Server"); + self.logger.setStatus("Starting Server"); var server = new Server({ logger: self.logger, host: options.serverHost, @@ -101,7 +115,7 @@ var Embark = { server.start(callback); }, function watchFilesForChanges(callback) { - Embark.monitor.setStatus("Watching for changes"); + self.logger.setStatus("Watching for changes"); var watch = new Watch({logger: self.logger}); watch.start(); watch.on('redeploy', function() { @@ -116,7 +130,7 @@ var Embark = { callback(); } ], function(err, result) { - Embark.monitor.setStatus("Ready".green); + self.logger.setStatus("Ready".green); self.logger.trace("finished".underline); }); }, @@ -215,7 +229,7 @@ var Embark = { buildDeployGenerate: function(done) { var self = this; - Embark.monitor.setStatus("Deploying...".magenta.underline); + self.logger.setStatus("Deploying...".magenta.underline); async.waterfall([ function deployAndBuildContractsManager(callback) { Embark.buildAndDeploy(function(err, contractsManager) { @@ -237,7 +251,7 @@ var Embark = { callback(null, abiGenerator.generateABI({useEmbarkJS: true})); }, function buildPipeline(abi, callback) { - Embark.monitor.setStatus("Building Assets"); + self.logger.setStatus("Building Assets"); var pipeline = new Pipeline({ buildDir: self.config.buildDir, contractsFiles: self.config.contractsFiles, @@ -251,9 +265,9 @@ var Embark = { if (err) { self.logger.error("error deploying"); self.logger.error(err.message); - Embark.monitor.setStatus("Deployment Error".red); + self.logger.setStatus("Deployment Error".red); } else { - Embark.monitor.setStatus("Ready".green); + self.logger.setStatus("Ready".green); } done(result); }); diff --git a/lib/logger.js b/lib/logger.js index b93f005a..5007977c 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -4,8 +4,9 @@ var Logger = function(options) { this.logLevels = ['error', 'warn', 'info', 'debug', 'trace']; this.logLevel = options.logLevel || 'info'; this.logFunction = options.logFunction || console.log; - this.contractsState = options.contractsState || console.log; - this.availableServices = options.availableServices || console.log; + this.contractsState = options.contractsState || function() {}; + this.availableServices = options.availableServices || function() {}; + this.setStatus = options.setStatus || console.log; }; Logger.prototype.error = function(txt) { From a9fbd5f6a5e5500e62d9c734a68b82ee590b881c Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 29 Oct 2016 22:35:22 -0400 Subject: [PATCH 012/257] make --no-color option available --- lib/cmd.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/cmd.js b/lib/cmd.js index 50419d53..f68afc81 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -66,6 +66,7 @@ Cmd.prototype.run = function() { .option('-b, --host [host]', 'host to run the dev webserver (default: localhost)') .option('--noserver', 'disable the development webserver') .option('--nodashboard', 'simple mode, disables the dashboard') + .option('--no-color', 'no colors in case it\'s needed for compatbility purposes') .description('run dapp (default: development)') .action(function(env, options) { self.Embark.initConfig(env || 'development', { From 0524b17309a94e4bab8661ecfc7e45535ee515e8 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 08:49:43 -0400 Subject: [PATCH 013/257] update to 2.1.3 --- boilerplate/package.json | 2 +- demo/package.json | 2 +- lib/cmd.js | 2 +- lib/services.js | 2 +- package.json | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/boilerplate/package.json b/boilerplate/package.json index 7fd1f3dc..0636ae3a 100644 --- a/boilerplate/package.json +++ b/boilerplate/package.json @@ -10,7 +10,7 @@ "license": "ISC", "homepage": "", "devDependencies": { - "embark": "^2.1.2", + "embark": "^2.1.3", "mocha": "^2.2.5" } } diff --git a/demo/package.json b/demo/package.json index 7fd1f3dc..0636ae3a 100644 --- a/demo/package.json +++ b/demo/package.json @@ -10,7 +10,7 @@ "license": "ISC", "homepage": "", "devDependencies": { - "embark": "^2.1.2", + "embark": "^2.1.3", "mocha": "^2.2.5" } } diff --git a/lib/cmd.js b/lib/cmd.js index f68afc81..f2a21bf6 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -3,7 +3,7 @@ var colors = require('colors'); var Cmd = function(Embark) { this.Embark = Embark; - program.version('2.1.2'); + program.version('2.1.3'); }; Cmd.prototype.process = function(args) { diff --git a/lib/services.js b/lib/services.js index e59f685e..fb0de723 100644 --- a/lib/services.js +++ b/lib/services.js @@ -30,7 +30,7 @@ ServicesMonitor.prototype.check = function() { }, function addEmbarkVersion(web3, result, callback) { self.logger.trace('addEmbarkVersion'); - result.push('Embark 2.1.2'.green); + result.push('Embark 2.1.3'.green); callback(null, web3, result); }, function checkEthereum(web3, result, callback) { diff --git a/package.json b/package.json index b2057932..ce8f1309 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "embark", - "version": "2.1.2", + "version": "2.1.3", "description": "Embark is a framework that allows you to easily develop and deploy DApps", "scripts": { "test": "grunt jshint && mocha test/ --no-timeouts" From 67074ee60fd608f6cc9d660b8aa671e5d61be19f Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 08:57:44 -0400 Subject: [PATCH 014/257] update to 2.1.3 --- lib/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index 0671fbb6..bc79cc29 100644 --- a/lib/index.js +++ b/lib/index.js @@ -66,7 +66,7 @@ var Embark = { function welcome(callback) { if (!options.useDashboard) { console.log('========================'.bold.green); - console.log('Welcome to Embark 2.1.2'.yellow.bold); + console.log('Welcome to Embark 2.1.3'.yellow.bold); console.log('========================'.bold.green); } callback(); From a7d6d36506f068b959fca7d05432cd255143be2b Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:08:20 -0400 Subject: [PATCH 015/257] disable guard-in check in eslint (for now) --- .codeclimate.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.codeclimate.yml b/.codeclimate.yml index 1f42030a..307aa3db 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -8,6 +8,8 @@ engines: enabled: false global-require: enabled: false + guard-for-in: + enabled: false ratings: paths: - "lib/**/*" From c30a289945a727230da6754657d59ef93ca56d42 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:14:38 -0400 Subject: [PATCH 016/257] handle error if no accounts are found --- lib/deploy.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/deploy.js b/lib/deploy.js index 8e43994e..2f34bea7 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -109,7 +109,9 @@ Deploy.prototype.deployContract = function(contract, params, callback) { var contractParams = (params || contract.args).slice(); this.web3.eth.getAccounts(function(err, accounts) { - //console.log("using address" + this.web3.eth.accounts[0]); + if (err) { + return callback(new Error(err)); + } // TODO: probably needs to be defaultAccount // TODO: it wouldn't necessary be the first address From ac67c80576e484034ce696a41ae3b4f1b0eadf3d Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:17:31 -0400 Subject: [PATCH 017/257] return callbacks --- lib/deploy.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/deploy.js b/lib/deploy.js index 2f34bea7..5700f0a1 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -136,12 +136,12 @@ Deploy.prototype.deployContract = function(contract, params, callback) { } self.logger.error(errMsg); contract.error = errMsg; - callback(new Error(err)); + return callback(new Error(err)); } else if (transaction.address !== undefined) { self.logger.info(contract.className + " deployed at " + transaction.address); contract.deployedAddress = transaction.address; contract.transactionHash = transaction.transactionHash; - callback(null, transaction.address); + return callback(null, transaction.address); } }); From e44bd3a22ee3a76b7692b4775bce5d63f5f8778c Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:22:09 -0400 Subject: [PATCH 018/257] handle error on contract deplyoment --- lib/deploy.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/deploy.js b/lib/deploy.js index 5700f0a1..f048217c 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -79,6 +79,9 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { } this.deployContract(contract, realArgs, function(err, address) { + if (err) { + return callback(new Error(err)); + } self.deployTracker.trackContract(contract.className, contract.code, realArgs, address); self.deployTracker.save(); self.logger.contractsState(self.contractsManager.contractsState()); From df7ff3916f70c204ed8ea631893feb6453c48ddf Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:28:45 -0400 Subject: [PATCH 019/257] handle error on deploy all --- lib/deploy.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/deploy.js b/lib/deploy.js index f048217c..4b43bcd6 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -162,6 +162,11 @@ Deploy.prototype.deployAll = function(done) { self.checkAndDeployContract(contract, null, callback); }, function(err, results) { + if (err) { + self.logger.error("error deploying contracts"); + self.logger.error(err.message); + self.logger.debug(err.stack); + } self.logger.info("finished"); self.logger.trace(arguments); done(); From 88bdd662dec2c9bedc021db7be11d8fad6d0b825 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:38:40 -0400 Subject: [PATCH 020/257] refactor determining method arguments --- lib/deploy.js | 45 +++++++++++++++++---------------------------- 1 file changed, 17 insertions(+), 28 deletions(-) diff --git a/lib/deploy.js b/lib/deploy.js index 4b43bcd6..cfbba629 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -15,6 +15,21 @@ var Deploy = function(options) { }); }; +Deploy.prototype.determineArguments = function(suppliedArgs) { + var realArgs = [], l, arg, contractName, referedContract; + + for (l = 0; l < suppliedArgs.length; l++) { + arg = suppliedArgs[l]; + if (arg[0] === "$") { + contractName = arg.substr(1); + referedContract = this.contractsManager.getContract(contractName); + realArgs.push(referedContract.deployedAddress); + } else { + realArgs.push(arg); + } + } +}; + Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { var self = this; var suppliedArgs; @@ -32,20 +47,7 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { if (contract.address !== undefined) { - // determine arguments - suppliedArgs = (params || contract.args); - realArgs = []; - - for (l = 0; l < suppliedArgs.length; l++) { - arg = suppliedArgs[l]; - if (arg[0] === "$") { - contractName = arg.substr(1); - referedContract = this.contractsManager.getContract(contractName); - realArgs.push(referedContract.deployedAddress); - } else { - realArgs.push(arg); - } - } + realArgs = self.determineArguments(params || contract.args); contract.deployedAddress = contract.address; self.deployTracker.trackContract(contract.className, contract.code, realArgs, contract.address); @@ -63,20 +65,7 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { return callback(); } else { - // determine arguments - suppliedArgs = (params || contract.args); - realArgs = []; - - for (l = 0; l < suppliedArgs.length; l++) { - arg = suppliedArgs[l]; - if (arg[0] === "$") { - contractName = arg.substr(1); - referedContract = this.contractsManager.getContract(contractName); - realArgs.push(referedContract.deployedAddress); - } else { - realArgs.push(arg); - } - } + realArgs = self.determineArguments(params || contract.args); this.deployContract(contract, realArgs, function(err, address) { if (err) { From 5c05b7f8d9600a46bbebbebe8aea0d59465f61bc Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 19:53:23 -0400 Subject: [PATCH 021/257] simplify whisper config condition --- lib/blockchain.js | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/lib/blockchain.js b/lib/blockchain.js index 7e060ce5..c8e60f58 100644 --- a/lib/blockchain.js +++ b/lib/blockchain.js @@ -19,15 +19,10 @@ var Blockchain = function(blockchainConfig, Client) { port: this.blockchainConfig.port || 30303, nodiscover: this.blockchainConfig.nodiscover || false, mine: this.blockchainConfig.mine || false, - account: this.blockchainConfig.account || {} + account: this.blockchainConfig.account || {}, + whisper: (this.blockchainConfig.whisper === undefined) || this.blockchainConfig.whisper }; - if (this.blockchainConfig.whisper === false) { - this.config.whisper = false; - } else { - this.config.whisper = (this.blockchainConfig.whisper || true); - } - this.client = new Client({config: this.config}); }; From 0a2a26fd2916e850053598ba312d3dddca387523 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:01:25 -0400 Subject: [PATCH 022/257] fix network config type --- lib/geth_commands.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/geth_commands.js b/lib/geth_commands.js index 9b81fd7b..fdb7cef3 100644 --- a/lib/geth_commands.js +++ b/lib/geth_commands.js @@ -54,6 +54,8 @@ GethCommands.prototype.listAccountsCommand = function() { cmd += "--testnet "; } else if (config.networkType === 'olympic') { cmd += "--olympic "; + } else if (config.networkType === 'custom') { + cmd += "--networkid " + config.networkId + " "; } if (config.datadir) { @@ -80,9 +82,7 @@ GethCommands.prototype.mainCommand = function(address) { cmd += "--testnet "; } else if (config.networkType === 'olympic') { cmd += "--olympic "; - } - - if (config.networkType === 'custom') { + } else if (config.networkType === 'custom') { cmd += "--networkid " + config.networkId + " "; } From e58671e74248fcaa576f6d6c4460ed49861da70f Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:08:45 -0400 Subject: [PATCH 023/257] refactor common geth command options into the a common method --- lib/geth_commands.js | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/lib/geth_commands.js b/lib/geth_commands.js index fdb7cef3..73de5333 100644 --- a/lib/geth_commands.js +++ b/lib/geth_commands.js @@ -46,9 +46,9 @@ GethCommands.prototype.newAccountCommand = function() { return cmd + "account new "; }; -GethCommands.prototype.listAccountsCommand = function() { +GethCommands.prototype.commonOptions = function() { var config = this.config; - var cmd = "geth "; + var cmd = ""; if (config.networkType === 'testnet') { cmd += "--testnet "; @@ -66,7 +66,11 @@ GethCommands.prototype.listAccountsCommand = function() { cmd += "--password " + config.account.password + " "; } - return cmd + "account list "; + return cmd; +}; + +GethCommands.prototype.listAccountsCommand = function() { + return "geth " + this.commonOptions() + "account list "; }; GethCommands.prototype.mainCommand = function(address) { @@ -74,21 +78,7 @@ GethCommands.prototype.mainCommand = function(address) { var cmd = "geth "; var rpc_api = ['eth', 'web3']; - if (config.datadir) { - cmd += "--datadir=\"" + config.datadir + "\" "; - } - - if (config.networkType === 'testnet') { - cmd += "--testnet "; - } else if (config.networkType === 'olympic') { - cmd += "--olympic "; - } else if (config.networkType === 'custom') { - cmd += "--networkid " + config.networkId + " "; - } - - if (config.account && config.account.password) { - cmd += "--password " + config.account.password + " "; - } + cmd += this.commonOptions(); cmd += "--port " + "30303" + " "; cmd += "--rpc "; From a5bc17f0de917be960679feccb31373aaf814c72 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:15:57 -0400 Subject: [PATCH 024/257] use config port when calling geth --- lib/geth_commands.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/geth_commands.js b/lib/geth_commands.js index 73de5333..46e0e1ad 100644 --- a/lib/geth_commands.js +++ b/lib/geth_commands.js @@ -80,7 +80,7 @@ GethCommands.prototype.mainCommand = function(address) { cmd += this.commonOptions(); - cmd += "--port " + "30303" + " "; + cmd += "--port " + config.port + " "; cmd += "--rpc "; cmd += "--rpcport " + config.rpcPort + " "; cmd += "--rpcaddr " + config.rpcHost + " "; From 6920ae94815e25a80d07025d62e9ac25b7f63a0d Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:21:28 -0400 Subject: [PATCH 025/257] refactor to use commonOptions method --- lib/geth_commands.js | 57 ++++++++++++-------------------------------- 1 file changed, 15 insertions(+), 42 deletions(-) diff --git a/lib/geth_commands.js b/lib/geth_commands.js index 46e0e1ad..88369d35 100644 --- a/lib/geth_commands.js +++ b/lib/geth_commands.js @@ -4,48 +4,6 @@ var GethCommands = function(options) { this.name = "Go-Ethereum (https://github.com/ethereum/go-ethereum)"; }; -GethCommands.prototype.initGenesisCommmand = function() { - var config = this.config; - var cmd = "geth "; - - if (config.networkType === 'testnet') { - cmd += "--testnet "; - } else if (config.networkType === 'olympic') { - cmd += "--olympic "; - } - - if (config.datadir) { - cmd += "--datadir=\"" + config.datadir + "\" "; - } - - if (config.genesisBlock) { - cmd += "init \"" + config.genesisBlock + "\" "; - } - - return cmd; -}; - -GethCommands.prototype.newAccountCommand = function() { - var config = this.config; - var cmd = "geth "; - - if (config.networkType === 'testnet') { - cmd += "--testnet "; - } else if (config.networkType === 'olympic') { - cmd += "--olympic "; - } - - if (config.datadir) { - cmd += "--datadir=\"" + config.datadir + "\" "; - } - - if (config.account && config.account.password) { - cmd += "--password " + config.account.password + " "; - } - - return cmd + "account new "; -}; - GethCommands.prototype.commonOptions = function() { var config = this.config; var cmd = ""; @@ -69,6 +27,21 @@ GethCommands.prototype.commonOptions = function() { return cmd; }; +GethCommands.prototype.initGenesisCommmand = function() { + var config = this.config; + var cmd = "geth " + this.commonOptions(); + + if (config.genesisBlock) { + cmd += "init \"" + config.genesisBlock + "\" "; + } + + return cmd; +}; + +GethCommands.prototype.newAccountCommand = function() { + return "geth " + this.commonOptions() + "account new "; +}; + GethCommands.prototype.listAccountsCommand = function() { return "geth " + this.commonOptions() + "account list "; }; From 5c283b523269bf8864717e413e0e03355ee732f5 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:35:11 -0400 Subject: [PATCH 026/257] support maxpeers option --- boilerplate/config/blockchain.json | 1 + demo/config/blockchain.json | 1 + lib/blockchain.js | 3 ++- lib/geth_commands.js | 2 ++ test/blockchain.js | 2 ++ 5 files changed, 8 insertions(+), 1 deletion(-) diff --git a/boilerplate/config/blockchain.json b/boilerplate/config/blockchain.json index 335e6e49..fcecfbbe 100644 --- a/boilerplate/config/blockchain.json +++ b/boilerplate/config/blockchain.json @@ -5,6 +5,7 @@ "datadir": ".embark/development/datadir", "mineWhenNeeded": true, "nodiscover": true, + "maxpeers": 0, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", diff --git a/demo/config/blockchain.json b/demo/config/blockchain.json index 335e6e49..fcecfbbe 100644 --- a/demo/config/blockchain.json +++ b/demo/config/blockchain.json @@ -5,6 +5,7 @@ "datadir": ".embark/development/datadir", "mineWhenNeeded": true, "nodiscover": true, + "maxpeers": 0, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", diff --git a/lib/blockchain.js b/lib/blockchain.js index c8e60f58..4ddbc5a9 100644 --- a/lib/blockchain.js +++ b/lib/blockchain.js @@ -20,7 +20,8 @@ var Blockchain = function(blockchainConfig, Client) { nodiscover: this.blockchainConfig.nodiscover || false, mine: this.blockchainConfig.mine || false, account: this.blockchainConfig.account || {}, - whisper: (this.blockchainConfig.whisper === undefined) || this.blockchainConfig.whisper + whisper: (this.blockchainConfig.whisper === undefined) || this.blockchainConfig.whisper, + maxpeers: this.blockchainConfig.maxpeers || 25 }; this.client = new Client({config: this.config}); diff --git a/lib/geth_commands.js b/lib/geth_commands.js index 88369d35..575a1c9f 100644 --- a/lib/geth_commands.js +++ b/lib/geth_commands.js @@ -74,6 +74,8 @@ GethCommands.prototype.mainCommand = function(address) { cmd += "--nodiscover "; } + cmd += "--maxpeers " + config.maxpeers + " "; + if (config.mineWhenNeeded || config.mine) { cmd += "--mine "; } diff --git a/test/blockchain.js b/test/blockchain.js index 45f1e3d9..5d17d28f 100644 --- a/test/blockchain.js +++ b/test/blockchain.js @@ -22,6 +22,7 @@ describe('embark.Blockchain', function() { networkId: 12301, port: 30303, nodiscover: false, + maxpeers: 25, mine: false, whisper: true, account: {} @@ -45,6 +46,7 @@ describe('embark.Blockchain', function() { networkId: 1, port: 123456, nodiscover: true, + maxpeers: 25, mine: true, whisper: false, account: {} From 99c528c23061689b5ec106e3896c1f6d34496d4f Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 20:48:16 -0400 Subject: [PATCH 027/257] simplify method dealing with instanceOf --- lib/contracts.js | 69 +++++++++++++++++++++++++----------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/lib/contracts.js b/lib/contracts.js index 0c648571..c97d43c1 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -80,48 +80,51 @@ ContractsManager.prototype.build = function(done) { } callback(); }, + function setDeployIntention(callback) { + var className, contract; + for(className in self.contracts) { + contract = self.contracts[className]; + contract.deploy = (contract.deploy === undefined) || contract.deploy; + } + }, function dealWithSpecialConfigs(callback) { var className, contract, parentContractName, parentContract; for(className in self.contracts) { contract = self.contracts[className]; - // if deploy intention is not specified default is true - if (contract.deploy === undefined) { - contract.deploy = true; + if (contract.instanceOf === undefined) { continue; } + + parentContractName = contract.instanceOf; + parentContract = self.contracts[parentContractName]; + + if (parentContract === className) { + self.logger.error(className + ": instanceOf is set to itself"); + continue; } - if (contract.instanceOf !== undefined) { - parentContractName = contract.instanceOf; - parentContract = self.contracts[parentContractName]; - - if (parentContract === className) { - self.logger.error(className + ": instanceOf is set to itself"); - continue; - } - - if (parentContract === undefined) { - slef.logger.error(className + ": couldn't find instanceOf contract " + parentContractName); - continue; - } - - if (parentContract.args && parentContract.args.length > 0 && contract.args === []) { - contract.args = parentContract.args; - } - - if (contract.code !== undefined) { - self.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName); - } - - contract.code = parentContract.code; - contract.runtimeBytecode = parentContract.runtimeBytecode; - contract.gasEstimates = parentContract.gasEstimates; - contract.functionHashes = parentContract.functionHashes; - contract.abiDefinition = parentContract.abiDefinition; - - contract.gas = contract.gas || parentContract.gas; - contract.gasPrice = contract.gasPrice || parentContract.gasPrice; + if (parentContract === undefined) { + self.logger.error(className + ": couldn't find instanceOf contract " + parentContractName); + continue; } + + if (parentContract.args && parentContract.args.length > 0 && contract.args === []) { + contract.args = parentContract.args; + } + + if (contract.code !== undefined) { + self.logger.error(className + " has code associated to it but it's configured as an instanceOf " + parentContractName); + } + + contract.code = parentContract.code; + contract.runtimeBytecode = parentContract.runtimeBytecode; + contract.gasEstimates = parentContract.gasEstimates; + contract.functionHashes = parentContract.functionHashes; + contract.abiDefinition = parentContract.abiDefinition; + + contract.gas = contract.gas || parentContract.gas; + contract.gasPrice = contract.gasPrice || parentContract.gasPrice; + } callback(); }, From 52244cca8e790d5dfc186f03403db2aa89cd16a4 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 21:31:29 -0400 Subject: [PATCH 028/257] move gas adjust to its own method --- lib/contracts.js | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/lib/contracts.js b/lib/contracts.js index c97d43c1..8122eec2 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -4,6 +4,20 @@ var async = require('async'); // TODO: create a contract object +var adjustGas = function(contract) { + var maxGas, adjustedGas; + if (contract.gas === 'auto') { + if (contract.deploy) { + maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000); + } else { + maxGas = 500000; + } + // TODO: put a check so it doesn't go over the block limit + adjustedGas = Math.round(maxGas * 1.40); + contract.gas = adjustedGas; + } +}; + var ContractsManager = function(options) { this.contractFiles = options.contractFiles; this.contractsConfig = options.contractsConfig; @@ -42,9 +56,16 @@ ContractsManager.prototype.build = function(done) { } callback(); }, + function setDeployIntention(callback) { + var className, contract; + for(className in self.contracts) { + contract = self.contracts[className]; + contract.deploy = (contract.deploy === undefined) || contract.deploy; + } + callback(); + }, function prepareContractsFromCompilation(callback) { var className, compiledContract, contractConfig, contract; - var maxGas, adjustedGas; for(className in self.compiledContracts) { compiledContract = self.compiledContracts[className]; contractConfig = self.contractsConfig.contracts[className]; @@ -56,22 +77,10 @@ ContractsManager.prototype.build = function(done) { contract.gasEstimates = compiledContract.gasEstimates; contract.functionHashes = compiledContract.functionHashes; contract.abiDefinition = compiledContract.abiDefinition; - contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas; - if (contract.deploy === undefined) { - contract.deploy = true; - } + contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas; + contract.gas = adjustGas(contract); - if (contract.gas === 'auto') { - if (contract.deploy) { - maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000); - } else { - maxGas = 500000; - } - // TODO: put a check so it doesn't go over the block limit - adjustedGas = Math.round(maxGas * 1.40); - contract.gas = adjustedGas; - } contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice; contract.type = 'file'; contract.className = className; @@ -80,13 +89,6 @@ ContractsManager.prototype.build = function(done) { } callback(); }, - function setDeployIntention(callback) { - var className, contract; - for(className in self.contracts) { - contract = self.contracts[className]; - contract.deploy = (contract.deploy === undefined) || contract.deploy; - } - }, function dealWithSpecialConfigs(callback) { var className, contract, parentContractName, parentContract; From c893c34fd2da9e775ce336a69fe24a3294037b56 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 21:35:08 -0400 Subject: [PATCH 029/257] add errors in test --- lib/test.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/test.js b/lib/test.js index 9667ae07..87d8a0b6 100644 --- a/lib/test.js +++ b/lib/test.js @@ -59,7 +59,13 @@ Test.prototype.deployAll = function(contractsConfig, cb) { callback(null, ABI); } ], function(err, result) { + if (err) { + throw new Error(err); + } self.web3.eth.getAccounts(function(err, accounts) { + if (err) { + throw new Error(err); + } var web3 = self.web3; web3.eth.defaultAccount = accounts[0]; // TODO: replace evals with separate process so it's isolated and with From eb7c89045ef0a179e34fabfbc9e49ad0d7e5a4c8 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 21:47:21 -0400 Subject: [PATCH 030/257] log any error with the services --- lib/services.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/services.js b/lib/services.js index fb0de723..b5f5fb14 100644 --- a/lib/services.js +++ b/lib/services.js @@ -72,7 +72,11 @@ ServicesMonitor.prototype.check = function() { callback(null, result); } ], function(err, result) { - self.logger.availableServices(result); + if (err) { + self.logger.error(err.message); + } else { + self.logger.availableServices(result); + } }); }; From b01f18916e2f37cb3db623f45fe47c609d619818 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 21:52:58 -0400 Subject: [PATCH 031/257] return callback --- lib/index.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/index.js b/lib/index.js index bc79cc29..617d8786 100644 --- a/lib/index.js +++ b/lib/index.js @@ -234,10 +234,9 @@ var Embark = { function deployAndBuildContractsManager(callback) { Embark.buildAndDeploy(function(err, contractsManager) { if (err) { - callback(err); - } else { - callback(null, contractsManager); + return callback(err); } + return callback(null, contractsManager); }); }, function generateConsoleABI(contractsManager, callback) { From c7bd478dde0484d7887508fa8733fc033cfaaad8 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 21:56:19 -0400 Subject: [PATCH 032/257] handle error if no accounts are found --- lib/index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/index.js b/lib/index.js index 617d8786..2580803d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -184,6 +184,9 @@ var Embark = { } web3.eth.getAccounts(function(err, accounts) { + if (err) { + return callback(new Error(err)); + } web3.eth.defaultAccount = accounts[0]; var deploy = new Deploy({ From 59f9d9fdf02e63c68b9e26709c830c56d2fb8ba0 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 22:04:25 -0400 Subject: [PATCH 033/257] handle errors --- lib/index.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/index.js b/lib/index.js index 2580803d..936fec6f 100644 --- a/lib/index.js +++ b/lib/index.js @@ -40,10 +40,6 @@ var Embark = { this.config = new Config({env: env}); this.config.loadConfigFiles(options); this.logger = new Logger({logLevel: 'debug'}); - - //this.contractsManager = new ContractsManager(configDir, files, env); - //this.contractsManager.init(); - //return this.contractsManager; }, redeploy: function(env) { @@ -55,7 +51,11 @@ var Embark = { }, self.buildDeployGenerate.bind(self) ], function(err, result) { - self.logger.trace("finished".underline); + if (err) { + self.logger.error(err.message); + } else { + self.logger.trace("finished".underline); + } }); }, @@ -130,12 +130,17 @@ var Embark = { callback(); } ], function(err, result) { - self.logger.setStatus("Ready".green); - self.logger.trace("finished".underline); + if (err) { + self.logger.error(err.message); + } else { + self.logger.setStatus("Ready".green); + self.logger.trace("finished".underline); + } }); }, build: function(env) { + var self = this; async.waterfall([ function deployAndGenerateABI(callback) { Embark.deploy(function(abi) { @@ -148,7 +153,11 @@ var Embark = { callback(); } ], function(err, result) { - self.logger.trace("finished".underline); + if (err) { + self.logger.error(err.message); + } else { + self.logger.trace("finished".underline); + } }); }, @@ -224,6 +233,9 @@ var Embark = { callback(null, abiGenerator.generateABI({useEmbarkJS: true})); } ], function(err, result) { + if (err) { + self.logger.error(err.message); + } done(result); }); }, From 0a26fa98ce7e754258428c4a3134f00f711e8609 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 30 Oct 2016 22:37:06 -0400 Subject: [PATCH 034/257] define version in the main object --- lib/cmd.js | 2 +- lib/index.js | 7 +++++-- lib/services.js | 3 ++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/cmd.js b/lib/cmd.js index f2a21bf6..b314b714 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -3,7 +3,7 @@ var colors = require('colors'); var Cmd = function(Embark) { this.Embark = Embark; - program.version('2.1.3'); + program.version(Embark.version); }; Cmd.prototype.process = function(args) { diff --git a/lib/index.js b/lib/index.js index 936fec6f..b99b5a54 100644 --- a/lib/index.js +++ b/lib/index.js @@ -26,6 +26,8 @@ var IPFS = require('./ipfs.js'); var Embark = { + version: '2.1.3', + process: function(args) { var cmd = new Cmd(Embark); cmd.process(args); @@ -66,7 +68,7 @@ var Embark = { function welcome(callback) { if (!options.useDashboard) { console.log('========================'.bold.green); - console.log('Welcome to Embark 2.1.3'.yellow.bold); + console.log(('Welcome to Embark ' + Embark.version).yellow.bold); console.log('========================'.bold.green); } callback(); @@ -96,7 +98,8 @@ var Embark = { config: Embark.config, serverHost: options.serverHost, serverPort: options.serverPort, - runWebserver: options.runWebserver + runWebserver: options.runWebserver, + version: Embark.version }); Embark.servicesMonitor.startMonitor(); callback(); diff --git a/lib/services.js b/lib/services.js index b5f5fb14..c56b69cf 100644 --- a/lib/services.js +++ b/lib/services.js @@ -9,6 +9,7 @@ var ServicesMonitor = function(options) { this.serverHost = options.serverHost || 'localhost'; this.serverPort = options.serverPort || 8000; this.runWebserver = options.runWebserver; + this.version = options.version; }; ServicesMonitor.prototype.startMonitor = function() { @@ -30,7 +31,7 @@ ServicesMonitor.prototype.check = function() { }, function addEmbarkVersion(web3, result, callback) { self.logger.trace('addEmbarkVersion'); - result.push('Embark 2.1.3'.green); + result.push(('Embark ' + self.version).green); callback(null, web3, result); }, function checkEthereum(web3, result, callback) { From 06d8c3fbd9f00eb2076e2abe4348bca468e8d21b Mon Sep 17 00:00:00 2001 From: Jonathan Brown Date: Thu, 3 Nov 2016 17:31:12 +0700 Subject: [PATCH 035/257] require('embark-framework') => require('embark') --- README.md | 2 +- boilerplate/test/contract_spec.js | 2 +- demo/test/simple_storage_spec.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e1e0e014..0bef07fd 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ Embark includes a testing lib to fastly run & test your contracts in a EVM. # test/simple_storage_spec.js var assert = require('assert'); -var Embark = require('embark-framework'); +var Embark = require('embark'); var EmbarkSpec = Embark.initTests(); var web3 = EmbarkSpec.web3; diff --git a/boilerplate/test/contract_spec.js b/boilerplate/test/contract_spec.js index d17d31bd..ec1b8738 100644 --- a/boilerplate/test/contract_spec.js +++ b/boilerplate/test/contract_spec.js @@ -1,5 +1,5 @@ var assert = require('assert'); -var Embark = require('embark-framework'); +var Embark = require('embark'); var EmbarkSpec = Embark.initTests(); var web3 = EmbarkSpec.web3; diff --git a/demo/test/simple_storage_spec.js b/demo/test/simple_storage_spec.js index c887fe78..83ad1610 100644 --- a/demo/test/simple_storage_spec.js +++ b/demo/test/simple_storage_spec.js @@ -1,5 +1,5 @@ var assert = require('assert'); -var Embark = require('embark-framework'); +var Embark = require('embark'); var EmbarkSpec = Embark.initTests(); var web3 = EmbarkSpec.web3; From 64f390e829927ded572ca12af281e736f0c682d6 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Thu, 3 Nov 2016 07:04:07 -0400 Subject: [PATCH 036/257] update readme to reflect promises --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0bef07fd..3079799c 100644 --- a/README.md +++ b/README.md @@ -169,8 +169,8 @@ Will automatically be available in Javascript as: ```Javascript # app/js/index.js SimpleStorage.set(100); -SimpleStorage.get(); -SimpleStorage.storedData(); +SimpleStorage.get().then(function(value) { console.log(value.toNumber()) }); +SimpleStorage.storedData().then(function(value) { console.log(value.toNumber()) }); ``` You can specify for each contract and environment its gas costs and arguments: From 668e0be0c340cbabcdf169c43ee95d121f3a7078 Mon Sep 17 00:00:00 2001 From: ed0wolf Date: Tue, 8 Nov 2016 09:31:02 +0000 Subject: [PATCH 037/257] Setting web3 on Embark Test constructor so it can be used before deploying contracts --- lib/test.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/test.js b/lib/test.js index 87d8a0b6..651b3151 100644 --- a/lib/test.js +++ b/lib/test.js @@ -19,12 +19,13 @@ var Test = function(options) { console.log('For more information see https://github.com/ethereumjs/testrpc'); exit(); } + + this.web3 = new Web3(); + this.web3.setProvider(this.sim.provider()); }; Test.prototype.deployAll = function(contractsConfig, cb) { var self = this; - this.web3 = new Web3(); - this.web3.setProvider(this.sim.provider()); var logger = new TestLogger({logLevel: 'debug'}); async.waterfall([ From a100d307ff0be8521f13cd108f91da170eefaae6 Mon Sep 17 00:00:00 2001 From: Nicolas Iglesias Date: Sun, 27 Nov 2016 13:59:54 -0300 Subject: [PATCH 038/257] Add missing argument --- lib/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index b99b5a54..9cbc2e90 100644 --- a/lib/index.js +++ b/lib/index.js @@ -227,8 +227,8 @@ var Embark = { var self = this; async.waterfall([ function buildAndDeploy(callback) { - Embark.buildAndDeploy(function(contractsManager) { - callback(null, contractsManager); + Embark.buildAndDeploy(function(err, contractsManager) { + callback(err, contractsManager); }); }, function generateABI(contractsManager, callback) { From cae39d85be1088915d4ba93beafe4ee12209a846 Mon Sep 17 00:00:00 2001 From: Nicolas Iglesias Date: Mon, 28 Nov 2016 17:14:39 -0300 Subject: [PATCH 039/257] embark build wasn't deploying assets --- lib/index.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/index.js b/lib/index.js index b99b5a54..59bf0ce7 100644 --- a/lib/index.js +++ b/lib/index.js @@ -151,7 +151,13 @@ var Embark = { }); }, function buildPipeline(abi, callback) { - var pipeline = new Pipeline({}); + self.logger.trace("Building Assets"); + var pipeline = new Pipeline({ + buildDir: self.config.buildDir, + contractsFiles: self.config.contractsFiles, + assetFiles: self.config.assetFiles, + logger: self.logger + }); pipeline.build(abi); callback(); } From 5ac4c0f3275b0f5a70e9db9fc05ca7c6cd99677c Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Fri, 2 Dec 2016 06:48:02 -0500 Subject: [PATCH 040/257] automatically connect to ipfs when attempting to use a storage functionality --- js/build/embark.bundle.js | 19 ++++++++++++++++--- js/embark.js | 19 ++++++++++++++++--- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index 321bfd24..120b40b6 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -156,13 +156,16 @@ var EmbarkJS = EmbarkJS.Storage = { }; - // EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) - //{server: ‘localhost’, port: ‘5001’}; + // EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) EmbarkJS.Storage.setProvider = function(provider, options) { if (provider === 'ipfs') { this.currentStorage = EmbarkJS.Storage.IPFS; - this.ipfsConnection = IpfsApi(options.server, options.port); + if (options === undefined) { + this.ipfsConnection = IpfsApi('localhost', '5001'); + } else { + this.ipfsConnection = IpfsApi(options.server, options.port); + } } else { throw Error('unknown provider'); } @@ -170,6 +173,9 @@ var EmbarkJS = EmbarkJS.Storage.saveText = function(text) { var self = this; + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } var promise = new Promise(function(resolve, reject) { self.ipfsConnection.add((new self.ipfsConnection.Buffer(text)), function(err, result) { if (err) { @@ -191,6 +197,10 @@ var EmbarkJS = throw new Error('no file found'); } + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } + var promise = new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onloadend = function() { @@ -214,6 +224,9 @@ var EmbarkJS = var self = this; // TODO: detect type, then convert if needed //var ipfsHash = web3.toAscii(hash); + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } var promise = new Promise(function(resolve, reject) { self.ipfsConnection.object.get([hash]).then(function(node) { diff --git a/js/embark.js b/js/embark.js index 903e35b7..be6831c0 100644 --- a/js/embark.js +++ b/js/embark.js @@ -109,13 +109,16 @@ EmbarkJS.IPFS = 'ipfs'; EmbarkJS.Storage = { }; -// EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) -//{server: ‘localhost’, port: ‘5001’}; +// EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) EmbarkJS.Storage.setProvider = function(provider, options) { if (provider === 'ipfs') { this.currentStorage = EmbarkJS.Storage.IPFS; - this.ipfsConnection = IpfsApi(options.server, options.port); + if (options === undefined) { + this.ipfsConnection = IpfsApi('localhost', '5001'); + } else { + this.ipfsConnection = IpfsApi(options.server, options.port); + } } else { throw Error('unknown provider'); } @@ -123,6 +126,9 @@ EmbarkJS.Storage.setProvider = function(provider, options) { EmbarkJS.Storage.saveText = function(text) { var self = this; + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } var promise = new Promise(function(resolve, reject) { self.ipfsConnection.add((new self.ipfsConnection.Buffer(text)), function(err, result) { if (err) { @@ -144,6 +150,10 @@ EmbarkJS.Storage.uploadFile = function(inputSelector) { throw new Error('no file found'); } + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } + var promise = new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onloadend = function() { @@ -167,6 +177,9 @@ EmbarkJS.Storage.get = function(hash) { var self = this; // TODO: detect type, then convert if needed //var ipfsHash = web3.toAscii(hash); + if (!this.ipfsConnection) { + this.setProvider('ipfs'); + } var promise = new Promise(function(resolve, reject) { self.ipfsConnection.object.get([hash]).then(function(node) { From 004d1eecf469f4987530b3c6276f95e1c336895d Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Fri, 2 Dec 2016 06:48:32 -0500 Subject: [PATCH 041/257] add missing return to determineArguments method --- lib/deploy.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/deploy.js b/lib/deploy.js index cfbba629..df7f8edd 100644 --- a/lib/deploy.js +++ b/lib/deploy.js @@ -28,6 +28,8 @@ Deploy.prototype.determineArguments = function(suppliedArgs) { realArgs.push(arg); } } + + return realArgs; }; Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { From 4002856f89c466ef8648c8b6df0f7f71199ac846 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Fri, 2 Dec 2016 07:06:04 -0500 Subject: [PATCH 042/257] update to solc 0.4.6 --- demo/app/contracts/simple_storage.sol | 2 +- package.json | 2 +- test/compiler.js | 5 +++-- test/contracts/simple_storage.sol | 2 +- test/contracts/token.sol | 2 +- 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/demo/app/contracts/simple_storage.sol b/demo/app/contracts/simple_storage.sol index 53494ce5..6e027a0f 100644 --- a/demo/app/contracts/simple_storage.sol +++ b/demo/app/contracts/simple_storage.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.2; +pragma solidity ^0.4.6; contract SimpleStorage { uint public storedData; diff --git a/package.json b/package.json index ce8f1309..bfe9aa7d 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "merge": "^1.2.0", "meteor-build-client": "^0.1.6", "mkdirp": "^0.5.1", - "solc": "^0.4.0", + "solc": "^0.4.6", "read-yaml": "^1.0.0", "request": "^2.75.0", "serve-static": "^1.11.1", diff --git a/test/compiler.js b/test/compiler.js index c86e1916..ec0db9a6 100644 --- a/test/compiler.js +++ b/test/compiler.js @@ -17,9 +17,10 @@ describe('embark.Compiler', function() { ]); var expectedObject = {}; - expectedObject["SimpleStorage"] = {"code":"6060604052604051602080608983395060806040525160008190555060628060276000396000f3606060405260e060020a60003504632a1afcd98114603057806360fe47b114603c5780636d4ce63c146048575b6002565b34600257605060005481565b34600257600435600055005b346002576000545b60408051918252519081900360200190f3","runtimeBytecode":"606060405260e060020a60003504632a1afcd98114603057806360fe47b114603c5780636d4ce63c146048575b6002565b34600257605060005481565b34600257600435600055005b346002576000545b60408051918252519081900360200190f3","gasEstimates":{"creation":[20100,19600],"external":{"get()":236,"set(uint256)":20124,"storedData()":206},"internal":{}},"functionHashes":{"get()":"6d4ce63c","set(uint256)":"60fe47b1","storedData()":"2a1afcd9"},"abiDefinition":[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}]}; - expectedObject["Token"] = {"code":"60606040526040516020806103a1833950608060405251600160a060020a033316600090815260208190526040902081905560028190555061035c806100456000396000f3606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd146100d457806323b872dd146100ef57806370a0823114610126578063a9059cbb1461014b578063dd62ed3e1461017f575b610002565b34610002576101b8600435602435600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b34610002576002545b60408051918252519081900360200190f35b34610002576101b8600435602435604435600160a060020a038316600090815260208190526040812054829010156101cc57610002565b3461000257600160a060020a03600435166000908152602081905260409020546100dd565b34610002576101b8600435602435600160a060020a033316600090815260208190526040812054829010156102c157610002565b34610002576100dd600435602435600160a060020a038083166000908152600160209081526040808320938516835292905220546100ce565b604080519115158252519081900360200190f35b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020057610002565b600160a060020a03831660009081526020819052604090205461022b90835b808201829010156100ce565b151561023657610002565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060019392505050565b600160a060020a0383166000908152602081905260409020546102e4908361021f565b15156102ef57610002565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060016100ce56","runtimeBytecode":"606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd146100d457806323b872dd146100ef57806370a0823114610126578063a9059cbb1461014b578063dd62ed3e1461017f575b610002565b34610002576101b8600435602435600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b34610002576002545b60408051918252519081900360200190f35b34610002576101b8600435602435604435600160a060020a038316600090815260208190526040812054829010156101cc57610002565b3461000257600160a060020a03600435166000908152602081905260409020546100dd565b34610002576101b8600435602435600160a060020a033316600090815260208190526040812054829010156102c157610002565b34610002576100dd600435602435600160a060020a038083166000908152600160209081526040808320938516835292905220546100ce565b604080519115158252519081900360200190f35b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020057610002565b600160a060020a03831660009081526020819052604090205461022b90835b808201829010156100ce565b151561023657610002565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060019392505050565b600160a060020a0383166000908152602081905260409020546102e4908361021f565b15156102ef57610002565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060016100ce56","gasEstimates":{"creation":[40354,172000],"external":{"allowance(address,address)":547,"approve(address,uint256)":22220,"balanceOf(address)":397,"totalSupply()":232,"transfer(address,uint256)":null,"transferFrom(address,address,uint256)":63271},"internal":{"safeToAdd(uint256,uint256)":52}},"functionHashes":{"allowance(address,address)":"dd62ed3e","approve(address,uint256)":"095ea7b3","balanceOf(address)":"70a08231","totalSupply()":"18160ddd","transfer(address,uint256)":"a9059cbb","transferFrom(address,address,uint256)":"23b872dd"},"abiDefinition":[{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"supply","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"value","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"_allowance","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initial_balance","type":"uint256"}],"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]}; + expectedObject["SimpleStorage"] = {"code":"606060405234610000576040516020806100bd83398101604052515b60008190555b505b608d806100306000396000f3606060405260e060020a60003504632a1afcd98114603057806360fe47b114604c5780636d4ce63c14605b575b6000565b34600057603a6077565b60408051918252519081900360200190f35b346000576059600435607d565b005b34600057603a6086565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b9056","runtimeBytecode":"606060405260e060020a60003504632a1afcd98114603057806360fe47b114604c5780636d4ce63c14605b575b6000565b34600057603a6077565b60408051918252519081900360200190f35b346000576059600435607d565b005b34600057603a6086565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b9056","gasEstimates":{"creation":[20125,28200],"external":{"get()":263,"set(uint256)":20157,"storedData()":218},"internal":{}},"functionHashes":{"get()":"6d4ce63c","set(uint256)":"60fe47b1","storedData()":"2a1afcd9"},"abiDefinition":[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"payable":false,"type":"constructor"}]}; + + expectedObject["Token"] = {"code":"6060604052346100005760405160208061042883398101604052515b600160a060020a033316600090815260208190526040902081905560028190555b505b6103dc8061004c6000396000f3606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd1461008257806323b872dd146100a157806370a08231146100cb578063a9059cbb146100ed578063dd62ed3e14610114575b610000565b346100005761006e600435602435610139565b604080519115158252519081900360200190f35b346100005761008f6101a4565b60408051918252519081900360200190f35b346100005761006e6004356024356044356101ab565b604080519115158252519081900360200190f35b346100005761008f6004356102bf565b60408051918252519081900360200190f35b346100005761006e6004356024356102de565b604080519115158252519081900360200190f35b346100005761008f6004356024356103a1565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a038316600090815260208190526040812054829010156101d157610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020557610000565b600160a060020a03831660009081526020819052604090205461022890836103ce565b151561023357610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561030457610000565b600160a060020a03831660009081526020819052604090205461032790836103ce565b151561033257610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b9291505056","runtimeBytecode":"606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd1461008257806323b872dd146100a157806370a08231146100cb578063a9059cbb146100ed578063dd62ed3e14610114575b610000565b346100005761006e600435602435610139565b604080519115158252519081900360200190f35b346100005761008f6101a4565b60408051918252519081900360200190f35b346100005761006e6004356024356044356101ab565b604080519115158252519081900360200190f35b346100005761008f6004356102bf565b60408051918252519081900360200190f35b346100005761006e6004356024356102de565b604080519115158252519081900360200190f35b346100005761008f6004356024356103a1565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a038316600090815260208190526040812054829010156101d157610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020557610000565b600160a060020a03831660009081526020819052604090205461022890836103ce565b151561023357610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561030457610000565b600160a060020a03831660009081526020819052604090205461032790836103ce565b151561033257610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b9291505056","gasEstimates":{"creation":[40397,197600],"external":{"allowance(address,address)":548,"approve(address,uint256)":22232,"balanceOf(address)":421,"totalSupply()":259,"transfer(address,uint256)":42853,"transferFrom(address,address,uint256)":63284},"internal":{"safeToAdd(uint256,uint256)":41}},"functionHashes":{"allowance(address,address)":"dd62ed3e","approve(address,uint256)":"095ea7b3","balanceOf(address)":"70a08231","totalSupply()":"18160ddd","transfer(address,uint256)":"a9059cbb","transferFrom(address,address,uint256)":"23b872dd"},"abiDefinition":[{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"supply","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"value","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"_allowance","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initial_balance","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]} it('should generate compiled code and abi', function() { assert.deepEqual(compiledContracts, expectedObject); diff --git a/test/contracts/simple_storage.sol b/test/contracts/simple_storage.sol index 46e047eb..5ff67f7a 100644 --- a/test/contracts/simple_storage.sol +++ b/test/contracts/simple_storage.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.2; +pragma solidity ^0.4.6; contract SimpleStorage { uint public storedData; diff --git a/test/contracts/token.sol b/test/contracts/token.sol index 58d182ad..3ce811df 100644 --- a/test/contracts/token.sol +++ b/test/contracts/token.sol @@ -1,6 +1,6 @@ // https://github.com/nexusdev/erc20/blob/master/contracts/base.sol -pragma solidity ^0.4.2; +pragma solidity ^0.4.6; contract Token { event Transfer(address indexed from, address indexed to, uint value); From 30b03383ee5e747ea750ed8069ef6a1cfa169b9b Mon Sep 17 00:00:00 2001 From: Steven Ireland Date: Mon, 26 Dec 2016 11:47:57 -0500 Subject: [PATCH 043/257] fix bug with adjusting gas --- lib/contracts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/contracts.js b/lib/contracts.js index 8122eec2..73252b84 100644 --- a/lib/contracts.js +++ b/lib/contracts.js @@ -79,7 +79,7 @@ ContractsManager.prototype.build = function(done) { contract.abiDefinition = compiledContract.abiDefinition; contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas; - contract.gas = adjustGas(contract); + adjustGas(contract); contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice; contract.type = 'file'; From 6d369cd45202cbef2eeafe6f22ea942fd06c9e7a Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Fri, 6 Jan 2017 21:48:38 -0500 Subject: [PATCH 044/257] update solc + specs --- demo/app/contracts/simple_storage.sol | 2 +- package.json | 2 +- test/compiler.js | 4 ++-- test/contracts/simple_storage.sol | 2 +- test/contracts/token.sol | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/demo/app/contracts/simple_storage.sol b/demo/app/contracts/simple_storage.sol index 6e027a0f..13957b2d 100644 --- a/demo/app/contracts/simple_storage.sol +++ b/demo/app/contracts/simple_storage.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.6; +pragma solidity ^0.4.7; contract SimpleStorage { uint public storedData; diff --git a/package.json b/package.json index bfe9aa7d..03b868b0 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "merge": "^1.2.0", "meteor-build-client": "^0.1.6", "mkdirp": "^0.5.1", - "solc": "^0.4.6", + "solc": "^0.4.7", "read-yaml": "^1.0.0", "request": "^2.75.0", "serve-static": "^1.11.1", diff --git a/test/compiler.js b/test/compiler.js index ec0db9a6..eafe093c 100644 --- a/test/compiler.js +++ b/test/compiler.js @@ -18,9 +18,9 @@ describe('embark.Compiler', function() { var expectedObject = {}; - expectedObject["SimpleStorage"] = {"code":"606060405234610000576040516020806100bd83398101604052515b60008190555b505b608d806100306000396000f3606060405260e060020a60003504632a1afcd98114603057806360fe47b114604c5780636d4ce63c14605b575b6000565b34600057603a6077565b60408051918252519081900360200190f35b346000576059600435607d565b005b34600057603a6086565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b9056","runtimeBytecode":"606060405260e060020a60003504632a1afcd98114603057806360fe47b114604c5780636d4ce63c14605b575b6000565b34600057603a6077565b60408051918252519081900360200190f35b346000576059600435607d565b005b34600057603a6086565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b9056","gasEstimates":{"creation":[20125,28200],"external":{"get()":263,"set(uint256)":20157,"storedData()":218},"internal":{}},"functionHashes":{"get()":"6d4ce63c","set(uint256)":"60fe47b1","storedData()":"2a1afcd9"},"abiDefinition":[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"payable":false,"type":"constructor"}]}; + expectedObject["SimpleStorage"] = {"code":"606060405234610000576040516020806100f083398101604052515b60008190555b505b60bf806100316000396000f300606060405263ffffffff60e060020a6000350416632a1afcd98114603657806360fe47b11460525780636d4ce63c146061575b6000565b346000576040607d565b60408051918252519081900360200190f35b34600057605f6004356083565b005b346000576040608c565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b905600a165627a7a7230582030b122c3c126c89fee6e495f59a06aa040cdc51e4c20e81f5b6184a33f2802000029","runtimeBytecode":"606060405263ffffffff60e060020a6000350416632a1afcd98114603657806360fe47b11460525780636d4ce63c146061575b6000565b346000576040607d565b60408051918252519081900360200190f35b34600057605f6004356083565b005b346000576040608c565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b905600a165627a7a7230582030b122c3c126c89fee6e495f59a06aa040cdc51e4c20e81f5b6184a33f2802000029","gasEstimates":{"creation":[20131,38200],"external":{"get()":269,"set(uint256)":20163,"storedData()":224},"internal":{}},"functionHashes":{"get()":"6d4ce63c","set(uint256)":"60fe47b1","storedData()":"2a1afcd9"},"abiDefinition":[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"payable":false,"type":"constructor"}]}; - expectedObject["Token"] = {"code":"6060604052346100005760405160208061042883398101604052515b600160a060020a033316600090815260208190526040902081905560028190555b505b6103dc8061004c6000396000f3606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd1461008257806323b872dd146100a157806370a08231146100cb578063a9059cbb146100ed578063dd62ed3e14610114575b610000565b346100005761006e600435602435610139565b604080519115158252519081900360200190f35b346100005761008f6101a4565b60408051918252519081900360200190f35b346100005761006e6004356024356044356101ab565b604080519115158252519081900360200190f35b346100005761008f6004356102bf565b60408051918252519081900360200190f35b346100005761006e6004356024356102de565b604080519115158252519081900360200190f35b346100005761008f6004356024356103a1565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a038316600090815260208190526040812054829010156101d157610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020557610000565b600160a060020a03831660009081526020819052604090205461022890836103ce565b151561023357610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561030457610000565b600160a060020a03831660009081526020819052604090205461032790836103ce565b151561033257610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b9291505056","runtimeBytecode":"606060405236156100565760e060020a6000350463095ea7b3811461005b57806318160ddd1461008257806323b872dd146100a157806370a08231146100cb578063a9059cbb146100ed578063dd62ed3e14610114575b610000565b346100005761006e600435602435610139565b604080519115158252519081900360200190f35b346100005761008f6101a4565b60408051918252519081900360200190f35b346100005761006e6004356024356044356101ab565b604080519115158252519081900360200190f35b346100005761008f6004356102bf565b60408051918252519081900360200190f35b346100005761006e6004356024356102de565b604080519115158252519081900360200190f35b346100005761008f6004356024356103a1565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a038316600090815260208190526040812054829010156101d157610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561020557610000565b600160a060020a03831660009081526020819052604090205461022890836103ce565b151561023357610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561030457610000565b600160a060020a03831660009081526020819052604090205461032790836103ce565b151561033257610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b9291505056","gasEstimates":{"creation":[40397,197600],"external":{"allowance(address,address)":548,"approve(address,uint256)":22232,"balanceOf(address)":421,"totalSupply()":259,"transfer(address,uint256)":42853,"transferFrom(address,address,uint256)":63284},"internal":{"safeToAdd(uint256,uint256)":41}},"functionHashes":{"allowance(address,address)":"dd62ed3e","approve(address,uint256)":"095ea7b3","balanceOf(address)":"70a08231","totalSupply()":"18160ddd","transfer(address,uint256)":"a9059cbb","transferFrom(address,address,uint256)":"23b872dd"},"abiDefinition":[{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"supply","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"value","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"_allowance","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initial_balance","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]} + expectedObject["Token"] = {"code":"6060604052346100005760405160208061048e83398101604052515b600160a060020a033316600090815260208190526040902081905560028190555b505b6104418061004d6000396000f3006060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461006157806318160ddd1461009157806323b872dd146100b057806370a08231146100e6578063a9059cbb14610111578063dd62ed3e14610141575b610000565b346100005761007d600160a060020a0360043516602435610172565b604080519115158252519081900360200190f35b346100005761009e6101dd565b60408051918252519081900360200190f35b346100005761007d600160a060020a03600435811690602435166044356101e4565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435166102f8565b60408051918252519081900360200190f35b346100005761007d600160a060020a0360043516602435610317565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435811690602435166103da565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a0383166000908152602081905260408120548290101561020a57610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561023e57610000565b600160a060020a0383166000908152602081905260409020546102619083610407565b151561026c57610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561033d57610000565b600160a060020a0383166000908152602081905260409020546103609083610407565b151561036b57610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b929150505600a165627a7a723058205734a3d0fff7050beb59577eb83ef9ffbd3e57a1705d22701727b61c9d8cb37b0029","runtimeBytecode":"6060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461006157806318160ddd1461009157806323b872dd146100b057806370a08231146100e6578063a9059cbb14610111578063dd62ed3e14610141575b610000565b346100005761007d600160a060020a0360043516602435610172565b604080519115158252519081900360200190f35b346100005761009e6101dd565b60408051918252519081900360200190f35b346100005761007d600160a060020a03600435811690602435166044356101e4565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435166102f8565b60408051918252519081900360200190f35b346100005761007d600160a060020a0360043516602435610317565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435811690602435166103da565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a0383166000908152602081905260408120548290101561020a57610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561023e57610000565b600160a060020a0383166000908152602081905260409020546102619083610407565b151561026c57610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561033d57610000565b600160a060020a0383166000908152602081905260409020546103609083610407565b151561036b57610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b929150505600a165627a7a723058205734a3d0fff7050beb59577eb83ef9ffbd3e57a1705d22701727b61c9d8cb37b0029","gasEstimates":{"creation":[40422,217800],"external":{"allowance(address,address)":598,"approve(address,uint256)":22273,"balanceOf(address)":462,"totalSupply()":265,"transfer(address,uint256)":42894,"transferFrom(address,address,uint256)":63334},"internal":{"safeToAdd(uint256,uint256)":41}},"functionHashes":{"allowance(address,address)":"dd62ed3e","approve(address,uint256)":"095ea7b3","balanceOf(address)":"70a08231","totalSupply()":"18160ddd","transfer(address,uint256)":"a9059cbb","transferFrom(address,address,uint256)":"23b872dd"},"abiDefinition":[{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"value","type":"uint256"}],"name":"approve","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"supply","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"who","type":"address"}],"name":"balanceOf","outputs":[{"name":"value","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"value","type":"uint256"}],"name":"transfer","outputs":[{"name":"ok","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"_allowance","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initial_balance","type":"uint256"}],"payable":false,"type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"}]} it('should generate compiled code and abi', function() { assert.deepEqual(compiledContracts, expectedObject); diff --git a/test/contracts/simple_storage.sol b/test/contracts/simple_storage.sol index 5ff67f7a..4b24a2fa 100644 --- a/test/contracts/simple_storage.sol +++ b/test/contracts/simple_storage.sol @@ -1,4 +1,4 @@ -pragma solidity ^0.4.6; +pragma solidity ^0.4.7; contract SimpleStorage { uint public storedData; diff --git a/test/contracts/token.sol b/test/contracts/token.sol index 3ce811df..2f005ee3 100644 --- a/test/contracts/token.sol +++ b/test/contracts/token.sol @@ -1,6 +1,6 @@ // https://github.com/nexusdev/erc20/blob/master/contracts/base.sol -pragma solidity ^0.4.6; +pragma solidity ^0.4.7; contract Token { event Transfer(address indexed from, address indexed to, uint value); From 13cf92a4f554b6ff9c83d804b19effc23934d4c4 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 00:03:03 -0500 Subject: [PATCH 045/257] add orbit to embarkjs --- README.md | 4 +- js/build/embark.bundle.js | 84 +++++++++++++++++++++++++++++++++++++-- js/embark.js | 84 +++++++++++++++++++++++++++++++++++++-- js/ipfs-api.min.js | 61 ++++++++++++++++++++++++++++ js/orbit.min.js | 60 ++++++++++++++++++++++++++++ lib/config.js | 3 ++ 6 files changed, 288 insertions(+), 8 deletions(-) create mode 100644 js/ipfs-api.min.js create mode 100644 js/orbit.min.js diff --git a/README.md b/README.md index 3079799c..0fd69483 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Table of Contents * [Using and Configuring Contracts](#dapp-structure) * [EmbarkJS](#embarkjs) * [EmbarkJS - Storage (IPFS)](#embarkjs---storage) -* [EmbarkJS - Communication (Whisper)](#embarkjs---communication) +* [EmbarkJS - Communication (Whisper/Orbit)](#embarkjs---communication) * [Testing Contracts](#tests) * [Working with different chains](#working-with-different-chains) * [Custom Application Structure](#structuring-application) @@ -351,7 +351,7 @@ EmbarkJS - Communication **initialization** -The current available communication is Whisper. +The current available communications are Whisper and Orbit. Whisper is supported in go-ethereum. To run Orbit ```ipfs daemon --enable-pubsub-experiment```. **listening to messages** diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index 120b40b6..f1d5f92b 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -246,20 +246,30 @@ var EmbarkJS = EmbarkJS.Messages = { }; - EmbarkJS.Messages.setProvider = function(provider) { + EmbarkJS.Messages.setProvider = function(provider, options) { + var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + } else if (provider === 'orbit') { + this.currentMessages = EmbarkJS.Messages.Orbit; + if (options === undefined) { + ipfs = HaadIpfsApi('localhost', '5001'); + } else { + ipfs = HaadIpfsApi(options.server, options.port); + } + this.currentMessages.orbit = new Orbit(ipfs); + this.currentMessages.orbit.connect(web3.eth.accounts[0]); } else { throw Error('unknown provider'); } }; EmbarkJS.Messages.sendMessage = function(options) { - return EmbarkJS.Messages.Whisper.sendMessage(options); + return this.currentMessages.sendMessage(options); }; EmbarkJS.Messages.listenTo = function(options) { - return EmbarkJS.Messages.Whisper.listenTo(options); + return this.currentMessages.listenTo(options); }; EmbarkJS.Messages.Whisper = { @@ -349,6 +359,74 @@ var EmbarkJS = return promise; }; + EmbarkJS.Messages.Orbit = { + }; + + EmbarkJS.Messages.Orbit.sendMessage = function(options) { + var topics = options.topic || options.topics; + var data = options.data || options.payload; + + if (topics === undefined) { + throw new Error("missing option: topic"); + } + + if (data === undefined) { + throw new Error("missing option: data"); + } + + // do fromAscii to each topics unless it's already a string + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + // TODO: if it's array then join and send ot several + // keep list of channels joined + this.orbit.join(topics); + + var payload = JSON.stringify(data); + + this.orbit.send(topics, data); + }; + + EmbarkJS.Messages.Orbit.listenTo = function(options) { + var self = this; + var topics = options.topic || options.topics; + + // do fromAscii to each topics unless it's already a string + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + var messageEvents = function() { + this.cb = function() {}; + }; + + messageEvents.prototype.then = function(cb) { + this.cb = cb; + }; + + messageEvents.prototype.error = function(err) { + return err; + }; + + var promise = new messageEvents(); + + this.orbit.events.on('message', (topics, message) => { + // Get the actual content of the message + self.orbit.getPost(message.payload.value, true).then((post) => { + promise.cb(post); + }); + }); + + return promise; + }; + module.exports = EmbarkJS; diff --git a/js/embark.js b/js/embark.js index be6831c0..aabfbba5 100644 --- a/js/embark.js +++ b/js/embark.js @@ -199,20 +199,30 @@ EmbarkJS.Storage.getUrl = function(hash) { EmbarkJS.Messages = { }; -EmbarkJS.Messages.setProvider = function(provider) { +EmbarkJS.Messages.setProvider = function(provider, options) { + var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + } else if (provider === 'orbit') { + this.currentMessages = EmbarkJS.Messages.Orbit; + if (options === undefined) { + ipfs = HaadIpfsApi('localhost', '5001'); + } else { + ipfs = HaadIpfsApi(options.server, options.port); + } + this.currentMessages.orbit = new Orbit(ipfs); + this.currentMessages.orbit.connect(web3.eth.accounts[0]); } else { throw Error('unknown provider'); } }; EmbarkJS.Messages.sendMessage = function(options) { - return EmbarkJS.Messages.Whisper.sendMessage(options); + return this.currentMessages.sendMessage(options); }; EmbarkJS.Messages.listenTo = function(options) { - return EmbarkJS.Messages.Whisper.listenTo(options); + return this.currentMessages.listenTo(options); }; EmbarkJS.Messages.Whisper = { @@ -302,4 +312,72 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { return promise; }; +EmbarkJS.Messages.Orbit = { +}; + +EmbarkJS.Messages.Orbit.sendMessage = function(options) { + var topics = options.topic || options.topics; + var data = options.data || options.payload; + + if (topics === undefined) { + throw new Error("missing option: topic"); + } + + if (data === undefined) { + throw new Error("missing option: data"); + } + + // do fromAscii to each topics unless it's already a string + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + // TODO: if it's array then join and send ot several + // keep list of channels joined + this.orbit.join(topics); + + var payload = JSON.stringify(data); + + this.orbit.send(topics, data); +}; + +EmbarkJS.Messages.Orbit.listenTo = function(options) { + var self = this; + var topics = options.topic || options.topics; + + // do fromAscii to each topics unless it's already a string + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + var messageEvents = function() { + this.cb = function() {}; + }; + + messageEvents.prototype.then = function(cb) { + this.cb = cb; + }; + + messageEvents.prototype.error = function(err) { + return err; + }; + + var promise = new messageEvents(); + + this.orbit.events.on('message', (topics, message) => { + // Get the actual content of the message + self.orbit.getPost(message.payload.value, true).then((post) => { + promise.cb(post); + }); + }); + + return promise; +}; + module.exports = EmbarkJS; diff --git a/js/ipfs-api.min.js b/js/ipfs-api.min.js new file mode 100644 index 00000000..70c3846a --- /dev/null +++ b/js/ipfs-api.min.js @@ -0,0 +1,61 @@ +var HaadIpfsApi=function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module.default}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=356)}([function(module,exports,__webpack_require__){"use strict";(function(Buffer,global){function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=__webpack_require__(145),ieee754=__webpack_require__(168),isArray=__webpack_require__(21);exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len,start<0&&(start=0)):start>len&&(start=len),end<0?(end+=len,end<0&&(end=0)):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?(255-this[offset]+1)*-1:this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i1)for(var i=1;i{return function(){const args=Array.prototype.slice.call(arguments),lastIndex=args.length-1,lastArg=args&&args.length>0?args[lastIndex]:null,cb="function"==typeof lastArg?lastArg:null;return cb?method.apply(context,args):new Promise((resolve,reject)=>{args.push((err,val)=>{return err?reject(err):void resolve(val)}),method.apply(context,args)})}};module.exports=((methods,options)=>{options=options||{};const type=Object.prototype.toString.call(methods);if("[object Object]"===type||"[object Array]"===type){const obj=options.replace?methods:{};for(let key in methods)methods.hasOwnProperty(key)&&(obj[key]=createCallback(methods[key]));return obj}return createCallback(methods,options.context||methods)})},function(module,exports,__webpack_require__){function Stream(){EE.call(this)}module.exports=Stream;var EE=__webpack_require__(6).EventEmitter,inherits=__webpack_require__(1);inherits(Stream,EE),Stream.Readable=__webpack_require__(289),Stream.Writable=__webpack_require__(291),Stream.Duplex=__webpack_require__(286),Stream.Transform=__webpack_require__(290),Stream.PassThrough=__webpack_require__(288),Stream.Stream=Stream,Stream.prototype.pipe=function(dest,options){function ondata(chunk){dest.writable&&!1===dest.write(chunk)&&source.pause&&source.pause()}function ondrain(){source.readable&&source.resume&&source.resume()}function onend(){didOnEnd||(didOnEnd=!0,dest.end())}function onclose(){didOnEnd||(didOnEnd=!0,"function"==typeof dest.destroy&&dest.destroy())}function onerror(er){if(cleanup(),0===EE.listenerCount(this,"error"))throw er}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)}var source=this;source.on("data",ondata),dest.on("drain",ondrain),dest._isStdio||options&&options.end===!1||(source.on("end",onend),source.on("close",onclose));var didOnEnd=!1;return source.on("error",onerror),dest.on("error",onerror),source.on("end",cleanup),source.on("close",cleanup),dest.on("close",cleanup),dest.emit("pipe",source),dest}},function(module,exports){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length)){if(er=arguments[1],er instanceof Error)throw er;var err=new Error('Uncaught, unspecified "error" event. ('+er+")");throw err.context=er,err}if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:args=Array.prototype.slice.call(arguments,1),handler.apply(this,args)}else if(isObject(handler))for(args=Array.prototype.slice.call(arguments,1),listeners=handler.slice(),len=listeners.length,i=0;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},function(module,exports,__webpack_require__){function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding))throw new Error("Unknown encoding: "+encoding)}function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2,this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3,this.charLength=this.charReceived?3:0}var Buffer=__webpack_require__(0).Buffer,isBufferEncoding=Buffer.isEncoding||function(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!0;default:return!1}},StringDecoder=exports.StringDecoder=function(encoding){switch(this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,""),assertEncoding(encoding),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=base64DetectIncompleteChar;break;default:return void(this.write=passThroughWrite)}this.charBuffer=new Buffer(6),this.charReceived=0,this.charLength=0};StringDecoder.prototype.write=function(buffer){for(var charStr="";this.charLength;){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},function(module,exports){var g;g=function(){return this}();try{g=g||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(g=window)}module.exports=g},function(module,exports,__webpack_require__){"use strict";(function(process){function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;iMAX_LEN)throw new RangeError("size is too large");var enc=encoding,_fill=fill;void 0===_fill&&(enc=void 0,_fill=0);var buf=new Buffer(size);if("string"==typeof _fill)for(var fillBuf=new Buffer(_fill,enc),flen=fillBuf.length,i=-1;++iMAX_LEN)throw new RangeError("size is too large");return new Buffer(size)},exports.from=function(value,encodingOrOffset,length){if("function"==typeof Buffer.from&&(!global.Uint8Array||Uint8Array.from!==Buffer.from))return Buffer.from(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('"value" argument must not be a number');if("string"==typeof value)return new Buffer(value,encodingOrOffset);if("undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(1===arguments.length)return new Buffer(value);"undefined"==typeof offset&&(offset=0);var len=length;if("undefined"==typeof len&&(len=value.byteLength-offset),offset>=value.byteLength)throw new RangeError("'offset' is out of bounds");if(len>value.byteLength-offset)throw new RangeError("'length' is out of bounds");return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);return value.copy(out,0,0,value.length),out}if(value){if(Array.isArray(value)||"undefined"!=typeof ArrayBuffer&&value.buffer instanceof ArrayBuffer||"length"in value)return new Buffer(value);if("Buffer"===value.type&&Array.isArray(value.data))return new Buffer(value.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},exports.allocUnsafeSlow=function(size){if("function"==typeof Buffer.allocUnsafeSlow)return Buffer.allocUnsafeSlow(size);if("number"!=typeof size)throw new TypeError("size must be a number");if(size>=MAX_LEN)throw new RangeError("size is too large");return new SlowBuffer(size)}}).call(exports,__webpack_require__(8))},function(module,exports,__webpack_require__){(function(global,process){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){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)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}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")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;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}}),x=args[i];i=0&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(exports,__webpack_require__(13).setImmediate,__webpack_require__(13).clearImmediate)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){var bs58=__webpack_require__(10),cs=__webpack_require__(240);exports.toHexString=function(m){if(!Buffer.isBuffer(m))throw new Error("must be passed a buffer");return m.toString("hex")},exports.fromHexString=function(s){return new Buffer(s,"hex")},exports.toB58String=function(m){if(!Buffer.isBuffer(m))throw new Error("must be passed a buffer");return bs58.encode(m)},exports.fromB58String=function(s){var encoded=s;return Buffer.isBuffer(s)&&(encoded=s.toString()),new Buffer(bs58.decode(encoded))},exports.decode=function(buf){exports.validate(buf);var code=buf[0];return{code:code,name:cs.codes[code],length:buf[1],digest:buf.slice(2)}},exports.encode=function(digest,code,length){if(!digest||!code)throw new Error("multihash encode requires at least two args: digest, code");var hashfn=exports.coerceCode(code);if(!Buffer.isBuffer(digest))throw new Error("digest should be a Buffer");if(null==length&&(length=digest.length),length&&digest.length!==length)throw new Error("digest length should be equal to specified length.");if(length>127)throw new Error("multihash does not yet support digest lengths greater than 127 bytes.");return Buffer.concat([new Buffer([hashfn,length]),digest])},exports.coerceCode=function(name){var code=name;if("string"==typeof name){if(!cs.names[name])throw new Error("Unrecognized hash function named: "+name);code=cs.names[name]}if("number"!=typeof code)throw new Error("Hash function code should be a number. Got: "+code);if(!cs.codes[code]&&!exports.isAppCode(code))throw new Error("Unrecognized function code: "+code);return code},exports.isAppCode=function(code){return code>0&&code<16},exports.isValidCode=function(code){return!!exports.isAppCode(code)||!!cs.codes[code]},exports.validate=function(multihash){if(!Buffer.isBuffer(multihash))throw new Error("multihash must be a Buffer");if(multihash.length<3)throw new Error("multihash too short. must be > 3 bytes.");if(multihash.length>129)throw new Error("multihash too long. must be < 129 bytes.");var code=multihash[0];if(!exports.isValidCode(code))throw new Error("multihash unknown function code: 0x"+code.toString(16));if(multihash.slice(2).length!==multihash[1])throw new Error("multihash length inconsistent: 0x"+multihash.toString("hex"))}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=__webpack_require__(9),util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Readable=__webpack_require__(105),Writable=__webpack_require__(60);util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;vcallback(null,data)))}const concat=__webpack_require__(157);module.exports=streamToValue},function(module,exports,__webpack_require__){var asn1=exports;asn1.bignum=__webpack_require__(149),asn1.define=__webpack_require__(124).define,asn1.base=__webpack_require__(25),asn1.constants=__webpack_require__(64),asn1.decoders=__webpack_require__(128),asn1.encoders=__webpack_require__(130)},function(module,exports,__webpack_require__){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=__webpack_require__(9),util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Readable=__webpack_require__(77),Writable=__webpack_require__(79);util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v`}toJSON(){return{name:this.name,size:this.size,multihash:mh.toB58String(this._multihash)}}get name(){return this._name}set name(name){throw new Error("Can't set property: 'name' is immutable")}get size(){return this._size}set size(size){throw new Error("Can't set property: 'size' is immutable")}get multihash(){return this._multihash}set multihash(multihash){throw new Error("Can't set property: 'multihash' is immutable")}}exports=module.exports=DAGLink,exports.create=__webpack_require__(172)}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},function(module,exports,__webpack_require__){(function(process){function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;iuint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x}function scrub_vec(v){for(var i=0;i>>8^255&sx^99,this.SBOX[x]=sx,this.INV_SBOX[sx]=x,x2=d[x],x4=d[x2],x8=d[x4],t=257*d[sx]^16843008*sx,this.SUB_MIX[0][x]=t<<24|t>>>8,this.SUB_MIX[1][x]=t<<16|t>>>16,this.SUB_MIX[2][x]=t<<8|t>>>24,this.SUB_MIX[3][x]=t,t=16843009*x8^65537*x4^257*x2^16843008*x,this.INV_SUB_MIX[0][sx]=t<<24|t>>>8,this.INV_SUB_MIX[1][sx]=t<<16|t>>>16,this.INV_SUB_MIX[2][sx]=t<<8|t>>>24,this.INV_SUB_MIX[3][sx]=t,0===x?x=xi=1:(x=x2^d[d[d[x8^x2]]],xi^=d[d[xi]]);return!0};var G=new Global;AES.blockSize=16,AES.prototype.blockSize=AES.blockSize,AES.keySize=32,AES.prototype.keySize=AES.keySize,AES.prototype._doReset=function(){var invKsRow,keySize,keyWords,ksRow,ksRows,t;for(keyWords=this._key,keySize=keyWords.length,this._nRounds=keySize+6,ksRows=4*(this._nRounds+1),this._keySchedule=[],ksRow=0;ksRow>>24,t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[255&t],t^=G.RCON[ksRow/keySize|0]<<24):keySize>6&&ksRow%keySize===4?t=G.SBOX[t>>>24]<<24|G.SBOX[t>>>16&255]<<16|G.SBOX[t>>>8&255]<<8|G.SBOX[255&t]:void 0,this._keySchedule[ksRow-keySize]^t);for(this._invKeySchedule=[],invKsRow=0;invKsRow>>24]]^G.INV_SUB_MIX[1][G.SBOX[t>>>16&255]]^G.INV_SUB_MIX[2][G.SBOX[t>>>8&255]]^G.INV_SUB_MIX[3][G.SBOX[255&t]];return!0},AES.prototype.encryptBlock=function(M){M=bufferToArray(new Buffer(M));var out=this._doCryptBlock(M,this._keySchedule,G.SUB_MIX,G.SBOX),buf=new Buffer(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[1],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[3],12),buf},AES.prototype.decryptBlock=function(M){M=bufferToArray(new Buffer(M));var temp=[M[3],M[1]];M[1]=temp[0],M[3]=temp[1];var out=this._doCryptBlock(M,this._invKeySchedule,G.INV_SUB_MIX,G.INV_SBOX),buf=new Buffer(16);return buf.writeUInt32BE(out[0],0),buf.writeUInt32BE(out[3],4),buf.writeUInt32BE(out[2],8),buf.writeUInt32BE(out[1],12),buf},AES.prototype.scrub=function(){scrub_vec(this._keySchedule),scrub_vec(this._invKeySchedule),scrub_vec(this._key)},AES.prototype._doCryptBlock=function(M,keySchedule,SUB_MIX,SBOX){var ksRow,s0,s1,s2,s3,t0,t1,t2,t3;s0=M[0]^keySchedule[0],s1=M[1]^keySchedule[1],s2=M[2]^keySchedule[2],s3=M[3]^keySchedule[3],ksRow=4;for(var round=1;round>>24]^SUB_MIX[1][s1>>>16&255]^SUB_MIX[2][s2>>>8&255]^SUB_MIX[3][255&s3]^keySchedule[ksRow++],t1=SUB_MIX[0][s1>>>24]^SUB_MIX[1][s2>>>16&255]^SUB_MIX[2][s3>>>8&255]^SUB_MIX[3][255&s0]^keySchedule[ksRow++],t2=SUB_MIX[0][s2>>>24]^SUB_MIX[1][s3>>>16&255]^SUB_MIX[2][s0>>>8&255]^SUB_MIX[3][255&s1]^keySchedule[ksRow++],t3=SUB_MIX[0][s3>>>24]^SUB_MIX[1][s0>>>16&255]^SUB_MIX[2][s1>>>8&255]^SUB_MIX[3][255&s2]^keySchedule[ksRow++],s0=t0,s1=t1,s2=t2,s3=t3;return t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&255]<<16|SBOX[s2>>>8&255]<<8|SBOX[255&s3])^keySchedule[ksRow++],t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&255]<<16|SBOX[s3>>>8&255]<<8|SBOX[255&s0])^keySchedule[ksRow++],t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&255]<<16|SBOX[s0>>>8&255]<<8|SBOX[255&s1])^keySchedule[ksRow++],t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&255]<<16|SBOX[s1>>>8&255]<<8|SBOX[255&s2])^keySchedule[ksRow++],[fixup_uint32(t0),fixup_uint32(t1),fixup_uint32(t2),fixup_uint32(t3)]},exports.AES=AES}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(Buffer){function incr32(iv){for(var item,len=iv.length;len--;){if(item=iv.readUInt8(len),255!==item){item++,iv.writeUInt8(item,len);break}iv.writeUInt8(0,len)}}function getBlock(self){var out=self._cipher.encryptBlock(self._prev);return incr32(self._prev),out}var xor=__webpack_require__(27);exports.encrypt=function(self,chunk){for(;self._cache.length{return l.constructor&&"DAGLink"===l.constructor.name?l:new DAGLink(l.name?l.name:l.Name,l.size?l.size:l.Size,l.hash||l.Hash||l.multihash)}),sortedLinks=sort(links,linkSort);serialize({data:data,links:sortedLinks},(err,serialized)=>{return err?callback(err):void multihashing(serialized,hashAlg,(err,multihash)=>{if(err)return callback(err);const dagNode=new DAGNode(data,sortedLinks,serialized,multihash);callback(null,dagNode)})})}const multihashing=__webpack_require__(91),sort=__webpack_require__(285),dagPBUtil=__webpack_require__(51),serialize=dagPBUtil.serialize,dagNodeUtil=__webpack_require__(38),linkSort=dagNodeUtil.linkSort,DAGNode=__webpack_require__(50),DAGLink=__webpack_require__(20);module.exports=create},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function cloneData(dagNode){let data;return dagNode.data&&dagNode.data.length>0?(data=new Buffer(dagNode.data.length),dagNode.data.copy(data)):data=new Buffer(0),data}function cloneLinks(dagNode){return dagNode.links.slice()}function linkSort(a,b){const aBuf=new Buffer(a.name||"","ascii"),bBuf=new Buffer(b.name||"","ascii");return aBuf.compare(bBuf)}function toDAGLink(node){return new DAGLink("",node.size,node.multihash)}const DAGLink=__webpack_require__(20);exports=module.exports,exports.cloneData=cloneData,exports.cloneLinks=cloneLinks,exports.linkSort=linkSort,exports.toDAGLink=toDAGLink}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";exports.webcrypto=__webpack_require__(40)(),exports.hmac=__webpack_require__(194),exports.ecdh=__webpack_require__(193),exports.aes=__webpack_require__(191),exports.rsa=__webpack_require__(196)},function(module,exports,__webpack_require__){"use strict";module.exports=function(){if("undefined"!=typeof window&&(__webpack_require__(311)(window),window.crypto))return window.crypto;throw new Error("Please use an environment with crypto support")}},function(module,exports,__webpack_require__){function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}var isFunction=__webpack_require__(222),isLength=__webpack_require__(90);module.exports=isArrayLike},function(module,exports,__webpack_require__){(function(process){exports=module.exports=__webpack_require__(100),exports.Stream=__webpack_require__(5),exports.Readable=exports,exports.Writable=__webpack_require__(102),exports.Duplex=__webpack_require__(22),exports.Transform=__webpack_require__(101),exports.PassThrough=__webpack_require__(270),process.browser||"disable"!==process.env.READABLE_STREAM||(module.exports=__webpack_require__(5))}).call(exports,__webpack_require__(2))},function(module,exports,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(5)}catch(_){}}();exports=module.exports=__webpack_require__(113),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=__webpack_require__(115),exports.Duplex=__webpack_require__(24),exports.Transform=__webpack_require__(114),exports.PassThrough=__webpack_require__(299),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(exports,__webpack_require__(2))},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const isStream=__webpack_require__(181),promisify=__webpack_require__(4),DAGNodeStream=__webpack_require__(62);module.exports=(send=>{return promisify((files,callback)=>{const ok=Buffer.isBuffer(files)||isStream.isReadable(files)||Array.isArray(files);if(!ok)return callback(new Error('"files" must be a buffer, readable stream, or array of objects'));const request={path:"add",files:files},transform=(res,callback)=>DAGNodeStream.streamToValue(send,res,callback);send.andTransform(request,transform,callback)})})}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(global){function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&expected.call({},actual)===!0}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=__webpack_require__(12),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(exports,__webpack_require__(8))},function(module,exports){"use strict";function once(fn){return function(){if(null!==fn){var callFn=fn;fn=null,callFn.apply(this,arguments)}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=once,module.exports=exports.default},function(module,exports,__webpack_require__){(function(Buffer){function BufferList(callback){if(!(this instanceof BufferList))return new BufferList(callback);if(this._bufs=[],this.length=0,"function"==typeof callback){this._callback=callback;var piper=function(err){this._callback&&(this._callback(err),this._callback=null)}.bind(this);this.on("pipe",function(src){src.on("error",piper)}),this.on("unpipe",function(src){src.removeListener("error",piper)})}else this.append(callback);DuplexStream.call(this)}var DuplexStream=__webpack_require__(146),util=__webpack_require__(12);util.inherits(BufferList,DuplexStream),BufferList.prototype._offset=function(offset){for(var _t,tot=0,i=0;ithis.length)&&(srcEnd=this.length),srcStart>=this.length)return dst||new Buffer(0);if(srcEnd<=0)return dst||new Buffer(0);var l,i,copy=!!dst,off=this._offset(srcStart),len=srcEnd-srcStart,bytes=len,bufoff=copy&&dstStart||0,start=off[1];if(0===srcStart&&srcEnd==this.length){if(!copy)return Buffer.concat(this._bufs);for(i=0;il)){this._bufs[i].copy(dst,bufoff,start,start+bytes);break}this._bufs[i].copy(dst,bufoff,start),bufoff+=l,bytes-=l,start&&(start=0)}return dst},BufferList.prototype.toString=function(encoding,start,end){return this.slice(start,end).toString(encoding)},BufferList.prototype.consume=function(bytes){for(;this._bufs.length;){if(!(bytes>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(bytes),this.length-=bytes;break}bytes-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},BufferList.prototype.duplicate=function(){for(var i=0,copy=new BufferList;isum+l.size,this.serialized.length),this._json={data:this.data,links:this.links.map(l=>l.toJSON()),multihash:mh.toB58String(this.multihash),size:this.size}}toJSON(){return this._json}toString(){const mhStr=mh.toB58String(this.multihash);return`DAGNode <${mhStr} - data: "${this.data.toString()}", links: ${this.links.length}, size: ${this.size}>`}get data(){return this._data}set data(data){throw new Error("Can't set property: 'data' is immutable")}get links(){return this._links}set links(links){throw new Error("Can't set property: 'links' is immutable")}get serialized(){return this._serialized}set serialized(serialized){throw new Error("Can't set property: 'serialized' is immutable")}get size(){return this._size}set size(size){throw new Error("Can't set property: 'size' is immutable")}get multihash(){return this._multihash}set multihash(multihash){throw new Error("Can't set property: 'multihash' is immutable")}}exports=module.exports=DAGNode,exports.create=__webpack_require__(37),exports.clone=__webpack_require__(174),exports.addLink=__webpack_require__(173),exports.rmLink=__webpack_require__(175)}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function cid(node,callback){callback(null,new CID(node.multihash))}function serialize(node,callback){let serialized;try{const pb=toProtoBuf(node);serialized=proto.PBNode.encode(pb)}catch(err){return callback(err)}callback(null,serialized)}function deserialize(data,callback){const pbn=proto.PBNode.decode(data),links=pbn.Links.map(link=>{return new DAGLink(link.Name,link.Tsize,link.Hash)}),buf=pbn.Data||new Buffer(0);DAGNode.create(buf,links,callback)}function toProtoBuf(node){const pbn={};return node.data&&node.data.length>0?pbn.Data=node.data:pbn.Data=null,node.links.length>0?pbn.Links=node.links.map(link=>{return{Hash:link.multihash,Name:link.name,Tsize:link.size}}):pbn.Links=null,pbn}const CID=__webpack_require__(76),protobuf=__webpack_require__(58),proto=protobuf(__webpack_require__(176)),DAGLink=__webpack_require__(20),DAGNode=__webpack_require__(50);exports=module.exports,exports.serialize=serialize,exports.deserialize=deserialize,exports.cid=cid}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(global,module){function arrayMap(array,iteratee){for(var index=-1,length=array?array.length:0,result=Array(length);++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toString(value){return null==value?"":baseToString(value)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function identity(value){return value}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}var LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reEscapeChar=/\\(\\)?/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,nativeKeys=overArg(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor(),getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set)!=setTag||WeakMap&&getTag(new WeakMap)!=weakMapTag)&&(getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):void 0;if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var stringToPath=memoize(function(string){string=toString(string);var result=[];return reLeadingDot.test(string)&&result.push(""),string.replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result});memoize.Cache=MapCache;var isArray=Array.isArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=map}).call(exports,__webpack_require__(8),__webpack_require__(16)(module))},function(module,exports,__webpack_require__){function baseGetTag(value){return null==value?void 0===value?undefinedTag:nullTag:(value=Object(value),symToStringTag&&symToStringTag in value?getRawTag(value):objectToString(value))}var Symbol=__webpack_require__(86),getRawTag=__webpack_require__(211),objectToString=__webpack_require__(216),nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol?Symbol.toStringTag:void 0;module.exports=baseGetTag},function(module,exports){function isObjectLike(value){return null!=value&&"object"==typeof value}module.exports=isObjectLike},function(module,exports,__webpack_require__){module.exports={encode:__webpack_require__(231),decode:__webpack_require__(230),encodingLength:__webpack_require__(232)}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function Multiaddr(addr){if(!(this instanceof Multiaddr))return new Multiaddr(addr);if(addr||(addr=""),addr instanceof Buffer)this.buffer=codec.fromBuffer(addr);else if("string"==typeof addr||addr instanceof String)this.buffer=codec.fromString(addr);else{if(!(addr.buffer&&addr.protos&&addr.protoCodes))throw new Error("addr must be a string, Buffer, or another Multiaddr");this.buffer=codec.fromBuffer(addr.buffer)}}var map=__webpack_require__(52),extend=__webpack_require__(31),codec=__webpack_require__(233),protocols=__webpack_require__(57),NotImplemented=new Error("Sorry, Not Implemented Yet."),varint=__webpack_require__(55);exports=module.exports=Multiaddr,Multiaddr.prototype.toString=function(){return codec.bufferToString(this.buffer)},Multiaddr.prototype.toOptions=function(){var opts={},parsed=this.toString().split("/");return opts.family="ip4"===parsed[1]?"ipv4":"ipv6",opts.host=parsed[2],opts.transport=parsed[3],opts.port=parsed[4],opts},Multiaddr.prototype.inspect=function(){return""},Multiaddr.prototype.protos=function(){return map(this.protoCodes(),function(code){return extend(protocols(code))})},Multiaddr.prototype.protoCodes=function(){const codes=[],buf=this.buffer;let i=0;for(;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Stream,internalUtil={deprecate:__webpack_require__(30)};!function(){try{Stream=__webpack_require__(5)}catch(_){}finally{Stream||(Stream=__webpack_require__(6).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer,bufferShim=__webpack_require__(11);util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},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;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(2),__webpack_require__(13).setImmediate)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const bs58=__webpack_require__(10),isIPFS=__webpack_require__(178);module.exports=function(multihash){if(!isIPFS.multihash(multihash))throw new Error("not valid multihash");return Buffer.isBuffer(multihash)?bs58.encode(multihash):multihash}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const TransformStream=__webpack_require__(42).Transform,streamToValue=__webpack_require__(17),getDagNode=__webpack_require__(338);class DAGNodeStream extends TransformStream{constructor(options){const opts=Object.assign(options||{},{objectMode:!0});super(opts),this._send=opts.send}static streamToValue(send,inputStream,callback){const outputStream=inputStream.pipe(new DAGNodeStream({send:send}));streamToValue(outputStream,callback)}_transform(obj,enc,callback){getDagNode(this._send,obj.Hash,(err,node)=>{if(err)return callback(err);const dag={path:obj.Name,hash:obj.Hash,size:node.size};this.push(dag),callback(null)})}}module.exports=DAGNodeStream},function(module,exports,__webpack_require__){function DecoderBuffer(base,options){return Reporter.call(this,options),Buffer.isBuffer(base)?(this.base=base,this.offset=0,void(this.length=base.length)):void this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return item instanceof EncoderBuffer||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if("number"==typeof value){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else{if(!Buffer.isBuffer(value))return reporter.error("Unsupported type: "+typeof value);this.value=value,this.length=value.length}}var inherits=__webpack_require__(1),Reporter=__webpack_require__(25).Reporter,Buffer=__webpack_require__(0).Buffer;inherits(DecoderBuffer,Reporter),exports.DecoderBuffer=DecoderBuffer,DecoderBuffer.prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){var res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function(bytes,fail){if(!(this.offset+bytes<=this.length))return this.error(fail||"DecoderBuffer overrun");var res=new DecoderBuffer(this.base);return res._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res},DecoderBuffer.prototype.raw=function(save){return this.base.slice(save?save.offset:this.offset,this.length)},exports.EncoderBuffer=EncoderBuffer,EncoderBuffer.prototype.join=function(out,offset){return out||(out=new Buffer(this.length)),offset||(offset=0),0===this.length?out:(Array.isArray(this.value)?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length),out)}},function(module,exports,__webpack_require__){var constants=exports;constants._reverse=function(map){var res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);var value=map[key];res[value]=key}),res},constants.der=__webpack_require__(127)},function(module,exports,__webpack_require__){function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){base.Node.call(this,"der",parent)}function derDecodeTag(buf,fail){var tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;var cls=der.tagClass[tag>>6],primitive=0===(32&tag);if(31===(31&tag)){var oct=tag;for(tag=0;128===(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag<<=7,tag|=127&oct}}else tag&=31;var tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){var len=buf.readUInt8(fail);if(buf.isError(len))return len;if(!primitive&&128===len)return null;if(0===(128&len))return len;var num=127&len;if(num>=4)return buf.error("length octect is too long");len=0;for(var i=0;i=31?reporter.error("Multi-octet tag encoding unsupported"):(primitive||(res|=32),res|=der.tagClassByName[cls||"universal"]<<6)}var inherits=__webpack_require__(1),Buffer=__webpack_require__(0).Buffer,asn1=__webpack_require__(18),base=asn1.base,der=asn1.constants.der;module.exports=DEREncoder,DEREncoder.prototype.encode=function(data,reporter){return this.tree._encode(data,reporter).join()},inherits(DERNode,base.Node),DERNode.prototype._encodeComposite=function(tag,primitive,cls,content){var encodedTag=encodeTag(tag,primitive,cls,this.reporter);if(content.length<128){var header=new Buffer(2);return header[0]=encodedTag,header[1]=content.length,this._createEncoderBuffer([header,content])}for(var lenOctets=1,i=content.length;i>=256;i>>=8)lenOctets++;var header=new Buffer(2+lenOctets);header[0]=encodedTag,header[1]=128|lenOctets;for(var i=1+lenOctets,j=content.length;j>0;i--,j>>=8)header[i]=255&j;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function(str,tag){if("bitstr"===tag)return this._createEncoderBuffer([0|str.unused,str.data]);if("bmpstr"===tag){for(var buf=new Buffer(2*str.length),i=0;i=40)return this.reporter.error("Second objid identifier OOB");id.splice(0,2,40*id[0]+id[1])}for(var size=0,i=0;i=128;ident>>=7)size++}for(var objid=new Buffer(size),offset=objid.length-1,i=id.length-1;i>=0;i--){var ident=id[i];for(objid[offset--]=127&ident;(ident>>=7)>0;)objid[offset--]=128|127&ident}return this._createEncoderBuffer(objid)},DERNode.prototype._encodeTime=function(time,tag){var str,date=new Date(time);return"gentime"===tag?str=[two(date.getFullYear()),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):"utctime"===tag?str=[two(date.getFullYear()%100),two(date.getUTCMonth()+1),two(date.getUTCDate()),two(date.getUTCHours()),two(date.getUTCMinutes()),two(date.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+tag+" time is not supported yet"),this._encodeStr(str,"octstr")},DERNode.prototype._encodeNull=function(){return this._createEncoderBuffer("")},DERNode.prototype._encodeInt=function(num,values){if("string"==typeof num){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num));num=values[num]}if("number"!=typeof num&&!Buffer.isBuffer(num)){var numArray=num.toArray();!num.sign&&128&numArray[0]&&numArray.unshift(0),num=new Buffer(numArray)}if(Buffer.isBuffer(num)){var size=num.length;0===num.length&&size++;var out=new Buffer(size);return num.copy(out),0===num.length&&(out[0]=0),this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);for(var size=1,i=num;i>=256;i>>=8)size++;for(var out=new Array(size),i=out.length-1;i>=0;i--)out[i]=255&num,num>>=8;return 128&out[0]&&out.unshift(0),this._createEncoderBuffer(new Buffer(out))},DERNode.prototype._encodeBool=function(value){return this._createEncoderBuffer(value?255:0)},DERNode.prototype._use=function(entity,obj){return"function"==typeof entity&&(entity=entity(obj)),entity._getEncoder("der").tree},DERNode.prototype._skipDefault=function(dataBuffer,reporter,parent){var i,state=this._baseState;if(null===state.default)return!1;var data=dataBuffer.join();if(void 0===state.defaultBuffer&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i>i%8,self._prev=shiftIn(self._prev,decrypt?bit:value);return out}function shiftIn(buffer,value){var len=buffer.length,i=-1,out=new Buffer(buffer.length);for(buffer=Buffer.concat([buffer,new Buffer([value])]);++i>7;return out}exports.encrypt=function(self,chunk,decrypt){for(var len=chunk.length,out=new Buffer(len),i=-1;++i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:null===n||isNaN(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):1===list.length?list[0]:Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(1!==state.pipesCount||state.pipes[0]!==dest||1!==src.listenerCount("data")||cleanedUp||(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var _i=0;_i-1?setImmediate:processNextTick,Buffer=__webpack_require__(0).Buffer;Writable.WritableState=WritableState;var util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Stream,internalUtil={deprecate:__webpack_require__(30)};!function(){try{Stream=__webpack_require__(5)}catch(_){}finally{Stream||(Stream=__webpack_require__(6).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer;util.inherits(Writable,Stream);var Duplex;WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var Duplex;Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["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},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(2),__webpack_require__(13).setImmediate)},function(module,exports,__webpack_require__){(function(Buffer){function EVP_BytesToKey(password,salt,keyLen,ivLen){Buffer.isBuffer(password)||(password=new Buffer(password,"binary")),salt&&!Buffer.isBuffer(salt)&&(salt=new Buffer(salt,"binary")),keyLen/=8,ivLen=ivLen||0;for(var md_buf,i,ki=0,ii=0,key=new Buffer(keyLen),iv=new Buffer(ivLen),addmd=0,bufs=[];;){if(addmd++>0&&bufs.push(md_buf),bufs.push(password),salt&&bufs.push(salt),md_buf=md5(Buffer.concat(bufs)),bufs=[],i=0,keyLen>0)for(;;){if(0===keyLen)break;if(i===md_buf.length)break;key[ki++]=md_buf[i],keyLen--,i++}if(ivLen>0&&i!==md_buf.length)for(;;){if(0===ivLen)break;if(i===md_buf.length)break;iv[ii++]=md_buf[i],ivLen--,i++}if(0===keyLen&&0===ivLen)break}for(i=0;i>5,this.byteCount=this.blockCount<<2,this.outputBlocks=outputBits>>5,this.extraBytes=(31&outputBits)>>3;for(var i=0;i<50;++i)this.s[i]=0}var NODE_JS="object"==typeof process&&process.versions&&process.versions.node;NODE_JS&&(root=global);for(var COMMON_JS=!root.JS_SHA3_TEST&&"object"==typeof module&&module.exports,HEX_CHARS="0123456789abcdef".split(""),SHAKE_PADDING=[31,7936,2031616,520093696],KECCAK_PADDING=[1,256,65536,16777216],PADDING=[6,1536,393216,100663296],SHIFT=[0,8,16,24],RC=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],BITS=[224,256,384,512],SHAKE_BITS=[128,256],OUTPUT_TYPES=["hex","buffer","arrayBuffer","array"],createOutputMethod=function(bits,padding,outputType){return function(message){return new Keccak(bits,padding,bits).update(message)[outputType]()}},createShakeOutputMethod=function(bits,padding,outputType){return function(message,outputBits){return new Keccak(bits,padding,outputBits).update(message)[outputType]()}},createMethod=function(bits,padding){var method=createOutputMethod(bits,padding,"hex");method.create=function(){return new Keccak(bits,padding,bits)},method.update=function(message){return method.create().update(message)};for(var i=0;i>2]|=message[index]<>2]|=code<>2]|=(192|code>>6)<>2]|=(128|63&code)<=57344?(blocks[i>>2]|=(224|code>>12)<>2]|=(128|code>>6&63)<>2]|=(128|63&code)<>2]|=(240|code>>18)<>2]|=(128|code>>12&63)<>2]|=(128|code>>6&63)<>2]|=(128|63&code)<=byteCount){for(this.start=i-byteCount,this.block=blocks[blockCount],i=0;i>2]|=this.padding[3&i],this.lastByteIndex==this.byteCount)for(blocks[0]=blocks[blockCount],i=1;i>4&15]+HEX_CHARS[15&block]+HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]+HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15]+HEX_CHARS[block>>28&15]+HEX_CHARS[block>>24&15];j%blockCount==0&&(f(s),i=0)}return extraBytes&&(block=s[i],extraBytes>0&&(hex+=HEX_CHARS[block>>4&15]+HEX_CHARS[15&block]),extraBytes>1&&(hex+=HEX_CHARS[block>>12&15]+HEX_CHARS[block>>8&15]),extraBytes>2&&(hex+=HEX_CHARS[block>>20&15]+HEX_CHARS[block>>16&15])),hex},Keccak.prototype.arrayBuffer=function(){this.finalize();var buffer,blockCount=this.blockCount,s=this.s,outputBlocks=this.outputBlocks,extraBytes=this.extraBytes,i=0,j=0,bytes=this.outputBits>>3;buffer=extraBytes?new ArrayBuffer(outputBlocks+1<<2):new ArrayBuffer(bytes);for(var array=new Uint32Array(buffer);j>8&255,array[offset+2]=block>>16&255,array[offset+3]=block>>24&255;j%blockCount==0&&f(s)}return extraBytes&&(offset=j<<2,block=s[i],extraBytes>0&&(array[offset]=255&block),extraBytes>1&&(array[offset+1]=block>>8&255),extraBytes>2&&(array[offset+2]=block>>16&255)),array};var f=function(s){var h,l,n,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b24,b25,b26,b27,b28,b29,b30,b31,b32,b33,b34,b35,b36,b37,b38,b39,b40,b41,b42,b43,b44,b45,b46,b47,b48,b49;for(n=0;n<48;n+=2)c0=s[0]^s[10]^s[20]^s[30]^s[40],c1=s[1]^s[11]^s[21]^s[31]^s[41],c2=s[2]^s[12]^s[22]^s[32]^s[42],c3=s[3]^s[13]^s[23]^s[33]^s[43],c4=s[4]^s[14]^s[24]^s[34]^s[44],c5=s[5]^s[15]^s[25]^s[35]^s[45],c6=s[6]^s[16]^s[26]^s[36]^s[46],c7=s[7]^s[17]^s[27]^s[37]^s[47],c8=s[8]^s[18]^s[28]^s[38]^s[48],c9=s[9]^s[19]^s[29]^s[39]^s[49],h=c8^(c2<<1|c3>>>31),l=c9^(c3<<1|c2>>>31),s[0]^=h,s[1]^=l,s[10]^=h,s[11]^=l,s[20]^=h,s[21]^=l,s[30]^=h,s[31]^=l,s[40]^=h,s[41]^=l,h=c0^(c4<<1|c5>>>31),l=c1^(c5<<1|c4>>>31),s[2]^=h,s[3]^=l,s[12]^=h,s[13]^=l,s[22]^=h,s[23]^=l,s[32]^=h,s[33]^=l,s[42]^=h,s[43]^=l,h=c2^(c6<<1|c7>>>31),l=c3^(c7<<1|c6>>>31),s[4]^=h,s[5]^=l,s[14]^=h,s[15]^=l,s[24]^=h,s[25]^=l,s[34]^=h,s[35]^=l,s[44]^=h,s[45]^=l,h=c4^(c8<<1|c9>>>31),l=c5^(c9<<1|c8>>>31),s[6]^=h,s[7]^=l,s[16]^=h,s[17]^=l,s[26]^=h,s[27]^=l,s[36]^=h,s[37]^=l,s[46]^=h,s[47]^=l,h=c6^(c0<<1|c1>>>31),l=c7^(c1<<1|c0>>>31),s[8]^=h,s[9]^=l,s[18]^=h,s[19]^=l,s[28]^=h,s[29]^=l,s[38]^=h,s[39]^=l,s[48]^=h,s[49]^=l,b0=s[0],b1=s[1],b32=s[11]<<4|s[10]>>>28,b33=s[10]<<4|s[11]>>>28,b14=s[20]<<3|s[21]>>>29,b15=s[21]<<3|s[20]>>>29,b46=s[31]<<9|s[30]>>>23,b47=s[30]<<9|s[31]>>>23,b28=s[40]<<18|s[41]>>>14,b29=s[41]<<18|s[40]>>>14,b20=s[2]<<1|s[3]>>>31,b21=s[3]<<1|s[2]>>>31,b2=s[13]<<12|s[12]>>>20,b3=s[12]<<12|s[13]>>>20,b34=s[22]<<10|s[23]>>>22,b35=s[23]<<10|s[22]>>>22,b16=s[33]<<13|s[32]>>>19,b17=s[32]<<13|s[33]>>>19,b48=s[42]<<2|s[43]>>>30,b49=s[43]<<2|s[42]>>>30,b40=s[5]<<30|s[4]>>>2,b41=s[4]<<30|s[5]>>>2,b22=s[14]<<6|s[15]>>>26,b23=s[15]<<6|s[14]>>>26,b4=s[25]<<11|s[24]>>>21,b5=s[24]<<11|s[25]>>>21,b36=s[34]<<15|s[35]>>>17,b37=s[35]<<15|s[34]>>>17,b18=s[45]<<29|s[44]>>>3,b19=s[44]<<29|s[45]>>>3,b10=s[6]<<28|s[7]>>>4,b11=s[7]<<28|s[6]>>>4,b42=s[17]<<23|s[16]>>>9,b43=s[16]<<23|s[17]>>>9,b24=s[26]<<25|s[27]>>>7,b25=s[27]<<25|s[26]>>>7,b6=s[36]<<21|s[37]>>>11,b7=s[37]<<21|s[36]>>>11,b38=s[47]<<24|s[46]>>>8,b39=s[46]<<24|s[47]>>>8,b30=s[8]<<27|s[9]>>>5,b31=s[9]<<27|s[8]>>>5,b12=s[18]<<20|s[19]>>>12,b13=s[19]<<20|s[18]>>>12,b44=s[29]<<7|s[28]>>>25,b45=s[28]<<7|s[29]>>>25,b26=s[38]<<8|s[39]>>>24,b27=s[39]<<8|s[38]>>>24,b8=s[48]<<14|s[49]>>>18,b9=s[49]<<14|s[48]>>>18,s[0]=b0^~b2&b4,s[1]=b1^~b3&b5,s[10]=b10^~b12&b14,s[11]=b11^~b13&b15,s[20]=b20^~b22&b24,s[21]=b21^~b23&b25,s[30]=b30^~b32&b34,s[31]=b31^~b33&b35,s[40]=b40^~b42&b44,s[41]=b41^~b43&b45,s[2]=b2^~b4&b6,s[3]=b3^~b5&b7,s[12]=b12^~b14&b16,s[13]=b13^~b15&b17,s[22]=b22^~b24&b26,s[23]=b23^~b25&b27,s[32]=b32^~b34&b36,s[33]=b33^~b35&b37,s[42]=b42^~b44&b46,s[43]=b43^~b45&b47,s[4]=b4^~b6&b8,s[5]=b5^~b7&b9,s[14]=b14^~b16&b18,s[15]=b15^~b17&b19,s[24]=b24^~b26&b28,s[25]=b25^~b27&b29,s[34]=b34^~b36&b38,s[35]=b35^~b37&b39,s[44]=b44^~b46&b48,s[45]=b45^~b47&b49,s[6]=b6^~b8&b0,s[7]=b7^~b9&b1,s[16]=b16^~b18&b10,s[17]=b17^~b19&b11,s[26]=b26^~b28&b20,s[27]=b27^~b29&b21,s[36]=b36^~b38&b30,s[37]=b37^~b39&b31,s[46]=b46^~b48&b40,s[47]=b47^~b49&b41,s[8]=b8^~b0&b2,s[9]=b9^~b1&b3,s[18]=b18^~b10&b12,s[19]=b19^~b11&b13,s[28]=b28^~b20&b22,s[29]=b29^~b21&b23,s[38]=b38^~b30&b32,s[39]=b39^~b31&b33,s[48]=b48^~b40&b42,s[49]=b49^~b41&b43,s[0]^=RC[n],s[1]^=RC[n+1]};if(COMMON_JS)module.exports=methods;else if(root)for(var key in methods)root[key]=methods[key]}(this)}).call(exports,__webpack_require__(2),__webpack_require__(8))},function(module,exports){"use strict";module.exports=`enum KeyType { + RSA = 0; +} + +message PublicKey { + required KeyType Type = 1; + required bytes Data = 2; +} + +message PrivateKey { + required KeyType Type = 1; + required bytes Data = 2; +}`},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const BN=__webpack_require__(18).bignum;exports.toBase64=function(bn){let s=bn.toBuffer("be").toString("base64");return s.replace(/(=*)$/,"").replace(/\+/g,"-").replace(/\//g,"_")},exports.toBn=function(str){return new BN(Buffer.from(str,"base64"))}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){var root=__webpack_require__(88),Symbol=root.Symbol;module.exports=Symbol},function(module,exports,__webpack_require__){(function(global){var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global;module.exports=freeGlobal}).call(exports,__webpack_require__(8))},function(module,exports,__webpack_require__){var freeGlobal=__webpack_require__(87),freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")();module.exports=root},function(module,exports){var isArray=Array.isArray;module.exports=isArray},function(module,exports){function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}var MAX_SAFE_INTEGER=9007199254740991;module.exports=isLength},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function Multihashing(buf,func,length,callback){if("function"==typeof length&&(callback=length,length=void 0),!callback)throw new Error("Missing callback");Multihashing.digest(buf,func,length,(err,digest)=>{return err?callback(err):void callback(null,multihash.encode(digest,func,length))})}const multihash=__webpack_require__(14),crypto=__webpack_require__(241);module.exports=Multihashing,Multihashing.Buffer=Buffer,Multihashing.multihash=multihash,Multihashing.digest=function(buf,func,length,callback){if("function"==typeof length&&(callback=length,length=void 0),!callback)throw new Error("Missing callback");let cb=callback;length&&(cb=((err,digest)=>{return err?callback(err):void callback(null,digest.slice(0,length))}));let hash;try{hash=Multihashing.createHash(func)}catch(err){return cb(err)}hash(buf,cb)},Multihashing.createHash=function(func){if(func=multihash.coerceCode(func),!Multihashing.functions[func])throw new Error("multihash function "+func+" not yet supported");return Multihashing.functions[func]},Multihashing.functions={17:crypto.sha1,18:crypto.sha2256,19:crypto.sha2512,20:crypto.sha3}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){function parse(opts){function parseRow(row){try{if(row)return JSON.parse(row)}catch(e){opts.strict&&this.emit("error",new Error("Could not parse row "+row.slice(0,50)+"..."))}}return opts=opts||{},opts.strict=opts.strict!==!1,split(parseRow)}function serialize(opts){return through.obj(opts,function(obj,enc,cb){cb(null,JSON.stringify(obj)+EOL)})}var through=__webpack_require__(248),split=__webpack_require__(278),EOL=__webpack_require__(95).EOL;module.exports=parse,module.exports.serialize=module.exports.stringify=serialize,module.exports.parse=parse},function(module,exports,__webpack_require__){(function(process){function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;icrypto.generateKeyPair("RSA",opts.bits,cb),(privKey,cb)=>privKey.public.hash((err,digest)=>{cb(err,digest,privKey)})],(err,digest,privKey)=>{return err?callback(err):void callback(null,new PeerId(digest,privKey))})},exports.createFromHexString=function(str){return new PeerId(mh.fromHexString(str))},exports.createFromBytes=function(buf){return new PeerId(buf)},exports.createFromB58String=function(str){return new PeerId(mh.fromB58String(str))},exports.createFromPubKey=function(key,callback){let buf=key;if("string"==typeof buf&&(buf=new Buffer(key,"base64")),"function"!=typeof callback)throw new Error("callback is required");const pubKey=crypto.unmarshalPublicKey(buf);pubKey.hash((err,digest)=>{return err?callback(err):void callback(null,new PeerId(digest,null,pubKey))})},exports.createFromPrivKey=function(key,callback){let buf=key;if("string"==typeof buf&&(buf=new Buffer(key,"base64")),"function"!=typeof callback)throw new Error("callback is required");waterfall([cb=>crypto.unmarshalPrivateKey(buf,cb),(privKey,cb)=>privKey.public.hash((err,digest)=>{cb(err,digest,privKey)})],(err,digest,privKey)=>{return err?callback(err):void callback(null,new PeerId(digest,privKey))})},exports.createFromJSON=function(obj,callback){if("function"!=typeof callback)throw new Error("callback is required");const id=mh.fromB58String(obj.id),rawPrivKey=obj.privKey&&new Buffer(obj.privKey,"base64"),rawPubKey=obj.pubKey&&new Buffer(obj.pubKey,"base64"),pub=rawPubKey&&crypto.unmarshalPublicKey(rawPubKey);rawPrivKey?waterfall([cb=>crypto.unmarshalPrivateKey(rawPrivKey,cb),(priv,cb)=>priv.public.hash((err,digest)=>{cb(err,digest,priv)}),(privDigest,priv,cb)=>{pub?pub.hash((err,pubDigest)=>{cb(err,privDigest,priv,pubDigest)}):cb(null,privDigest,priv)}],(err,privDigest,priv,pubDigest)=>{return err?callback(err):pub&&!privDigest.equals(pubDigest)?callback(new Error("Public and private key do not match")):id&&!privDigest.equals(id)?callback(new Error("Id and private key do not match")):void callback(null,new PeerId(id,priv,pub))}):callback(null,new PeerId(id,null,pub))}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){module.exports={encode:__webpack_require__(259),decode:__webpack_require__(258),encodingLength:__webpack_require__(260)}},function(module,exports){"use strict";var replace=String.prototype.replace,percentTwenties=/%20/g;module.exports={default:"RFC3986",formatters:{RFC1738:function(value){return replace.call(value,percentTwenties,"+")},RFC3986:function(value){return value}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},function(module,exports){"use strict";var has=Object.prototype.hasOwnProperty,hexTable=function(){for(var array=[],i=0;i<256;++i)array.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase());return array}();exports.arrayToObject=function(source,options){for(var obj=options&&options.plainObjects?Object.create(null):{},i=0;i=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122?out+=string.charAt(i):c<128?out+=hexTable[c]:c<2048?out+=hexTable[192|c>>6]+hexTable[128|63&c]:c<55296||c>=57344?out+=hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|63&c]:(i+=1,c=65536+((1023&c)<<10|1023&string.charCodeAt(i)),out+=hexTable[240|c>>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|63&c])}return out},exports.compact=function(obj,references){if("object"!=typeof obj||null===obj)return obj;var refs=references||[],lookup=refs.indexOf(obj);if(lookup!==-1)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),addToFront||(state.reading=!1),state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream)),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:isNaN(n)||util.isNull(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return util.isBuffer(chunk)||util.isString(chunk)||util.isNullOrUndefined(chunk)||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,util.isNull(ret)&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),util.isNull(ret)||this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i1){for(var cbs=[],c=0;c0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Stream,internalUtil={deprecate:__webpack_require__(30)};!function(){try{Stream=__webpack_require__(5)}catch(_){}finally{Stream||(Stream=__webpack_require__(6).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer,bufferShim=__webpack_require__(11);util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},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;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(2),__webpack_require__(13).setImmediate)},function(module,exports,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(5)}catch(_){}}();exports=module.exports=__webpack_require__(108),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=__webpack_require__(110),exports.Duplex=__webpack_require__(23),exports.Transform=__webpack_require__(109),exports.PassThrough=__webpack_require__(294),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(exports,__webpack_require__(2))},function(module,exports,__webpack_require__){(function(Buffer){function parse256(buf){var positive;if(128===buf[0])positive=!0;else{if(255!==buf[0])return null;positive=!1}for(var zero=!1,tuple=[],i=buf.length-1;i>0;i--){var byte=buf[i];positive?tuple.push(byte):zero&&0===byte?tuple.push(0):zero?(zero=!1,tuple.push(256-byte)):tuple.push(255-byte)}var sum=0,l=tuple.length;for(i=0;i=len?len:index>=0?index:(index+=len,index>=0?index:0))},toType=function(flag){switch(flag){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null},toTypeflag=function(flag){switch(flag){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0},alloc=function(size){var buf=new Buffer(size);return buf.fill(0),buf},indexOf=function(block,num,offset,end){for(;offsetMath.pow(10,digits)&&digits++,len+digits+str};exports.decodeLongPath=function(buf){return decodeStr(buf,0,buf.length)},exports.encodePax=function(opts){var result="";opts.name&&(result+=addLength(" path="+opts.name+"\n")),opts.linkname&&(result+=addLength(" linkpath="+opts.linkname+"\n"));var pax=opts.pax;if(pax)for(var key in pax)result+=addLength(" "+key+"="+pax[key]+"\n");return new Buffer(result)},exports.decodePax=function(buf){for(var result={};buf.length;){for(var i=0;i100;){var i=name.indexOf("/");if(i===-1)return null;prefix+=prefix?"/"+name.slice(0,i):name.slice(0,i),name=name.slice(i+1)}return Buffer.byteLength(name)>100||Buffer.byteLength(prefix)>155?null:opts.linkname&&Buffer.byteLength(opts.linkname)>100?null:(buf.write(name),buf.write(encodeOct(opts.mode&MASK,6),100),buf.write(encodeOct(opts.uid,6),108),buf.write(encodeOct(opts.gid,6),116),buf.write(encodeOct(opts.size,11),124),buf.write(encodeOct(opts.mtime.getTime()/1e3|0,11),136),buf[156]=ZERO_OFFSET+toTypeflag(opts.type),opts.linkname&&buf.write(opts.linkname,157),buf.write(USTAR,257),opts.uname&&buf.write(opts.uname,265),opts.gname&&buf.write(opts.gname,297),buf.write(encodeOct(opts.devmajor||0,6),329),buf.write(encodeOct(opts.devminor||0,6),337),prefix&&buf.write(prefix,345),buf.write(encodeOct(cksum(buf),6),148),buf)},exports.decode=function(buf){var typeflag=0===buf[156]?0:buf[156]-ZERO_OFFSET,name=decodeStr(buf,0,100),mode=decodeOct(buf,100),uid=decodeOct(buf,108),gid=decodeOct(buf,116),size=decodeOct(buf,124),mtime=decodeOct(buf,136),type=toType(typeflag),linkname=0===buf[157]?null:decodeStr(buf,157,100),uname=decodeStr(buf,265,32),gname=decodeStr(buf,297,32),devmajor=decodeOct(buf,329),devminor=decodeOct(buf,337);buf[345]&&(name=decodeStr(buf,345,155)+"/"+name),0===typeflag&&name&&"/"===name[name.length-1]&&(typeflag=5);var c=cksum(buf);if(256===c)return null;if(c!==decodeOct(buf,148))throw new Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");return{name:name,mode:mode,uid:uid,gid:gid,size:size,mtime:new Date(1e3*mtime),type:type,linkname:linkname,uname:uname,gname:gname,devmajor:devmajor,devminor:devminor}}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(process){function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(24),options=options||{},this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode);var hwm=options.highWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=__webpack_require__(7).StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){return Duplex=Duplex||__webpack_require__(24),this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,options&&"function"==typeof options.read&&(this._read=options.read),void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Stream,internalUtil={deprecate:__webpack_require__(30)};!function(){try{Stream=__webpack_require__(5)}catch(_){}finally{Stream||(Stream=__webpack_require__(6).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer,bufferShim=__webpack_require__(11);util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},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;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(2),__webpack_require__(13).setImmediate)},function(module,exports,__webpack_require__){"use strict";function Url(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&util.isObject(url)&&url instanceof Url)return url;var u=new Url;return u.parse(url,parseQueryString,slashesDenoteHost),u}function urlFormat(obj){return util.isString(obj)&&(obj=urlParse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)}function urlResolve(source,relative){return urlParse(source,!1,!0).resolve(relative)}function urlResolveObject(source,relative){return source?urlParse(source,!1,!0).resolveObject(relative):relative}var punycode=__webpack_require__(263),util=__webpack_require__(304);exports.parse=urlParse,exports.resolve=urlResolve,exports.resolveObject=urlResolveObject,exports.format=urlFormat,exports.Url=Url;var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,simplePathPattern=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,delims=["<",">",'"',"`"," ","\r","\n","\t"],unwise=["{","}","|","\\","^","`"].concat(delims),autoEscape=["'"].concat(unwise),nonHostChars=["%","/","?",";","#"].concat(autoEscape),hostEndingChars=["/","?","#"],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,unsafeProtocol={javascript:!0,"javascript:":!0},hostlessProtocol={javascript:!0,"javascript:":!0},slashedProtocol={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},querystring=__webpack_require__(269);Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!util.isString(url))throw new TypeError("Parameter 'url' must be a string, not "+typeof url);var queryIndex=url.indexOf("?"),splitter=queryIndex!==-1&&queryIndex127?"x":part[j];if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i),notHost=hostparts.slice(i+1),bit=part.match(hostnamePartStart);bit&&(validParts.push(bit[1]),notHost.unshift(bit[2])),notHost.length&&(rest="/"+notHost.join(".")+rest),this.hostname=validParts.join(".");break}}}this.hostname.length>hostnameMaxLen?this.hostname="":this.hostname=this.hostname.toLowerCase(),ipv6Hostname||(this.hostname=punycode.toASCII(this.hostname));var p=this.port?":"+this.port:"",h=this.hostname||"";this.host=h+p,this.href+=this.host,ipv6Hostname&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==rest[0]&&(rest="/"+rest))}if(!unsafeProtocol[lowerProto])for(var i=0,l=autoEscape.length;i0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative.search,result.query=relative.query,util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.href=result.format(),result}if(!srcPath.length)return result.pathname=null,result.search?result.path="/"+result.search:result.path=null,result.href=result.format(),result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&("."===last||".."===last)||""===last,up=0,i=srcPath.length;i>=0;i--)last=srcPath[i],"."===last?srcPath.splice(i,1):".."===last?(srcPath.splice(i,1),up++):up&&(srcPath.splice(i,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");!mustEndAbs||""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0)||srcPath.unshift(""),hasTrailingSlash&&"/"!==srcPath.join("/").substr(-1)&&srcPath.push("");var isAbsolute=""===srcPath[0]||srcPath[0]&&"/"===srcPath[0].charAt(0);if(psychotic){result.hostname=result.host=isAbsolute?"":srcPath.length?srcPath.shift():"";var authInHost=!!(result.host&&result.host.indexOf("@")>0)&&result.host.split("@");authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute&&srcPath.unshift(""),srcPath.length?result.pathname=srcPath.join("/"):(result.pathname=null,result.path=null),util.isNull(result.pathname)&&util.isNull(result.search)||(result.path=(result.pathname?result.pathname:"")+(result.search?result.search:"")),result.auth=relative.auth||result.auth,result.slashes=result.slashes||relative.slashes,result.href=result.format(),result},Url.prototype.parseHost=function(){var host=this.host,port=portPattern.exec(host);port&&(port=port[0],":"!==port&&(this.port=port.substr(1)),host=host.substr(0,host.length-port.length)),host&&(this.hostname=host)}},function(module,exports,__webpack_require__){module.exports={encode:__webpack_require__(308),decode:__webpack_require__(307),encodingLength:__webpack_require__(309)}},function(module,exports){function wrappy(fn,cb){function wrapper(){for(var args=new Array(arguments.length),i=0;i{return promisify((hash,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={});try{hash=cleanMultihash(hash)}catch(err){return callback(err)}send({path:"cat",args:hash,buffer:opts.buffer},callback)})})},function(module,exports,__webpack_require__){"use strict";const addCmd=__webpack_require__(44),Duplex=__webpack_require__(42).Duplex,promisify=__webpack_require__(4);module.exports=(send=>{const add=addCmd(send);return promisify(callback=>{const tuples=[],ds=new Duplex({objectMode:!0});ds._read=(n=>{}),ds._write=((file,enc,next)=>{tuples.push(file),next()}),ds.end=(()=>{add(tuples,(err,res)=>{return err?ds.emit("error",err):(res.forEach(tuple=>{ds.push(tuple)}),void ds.push(null))})}),callback(null,ds)})})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),cleanMultihash=__webpack_require__(61),TarStreamToObjects=__webpack_require__(347);module.exports=(send=>{return promisify((path,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={});try{path=cleanMultihash(path)}catch(err){return callback(err)}const request={path:"get",args:path,qs:opts};send.andTransform(request,TarStreamToObjects.from,callback)})})},function(module,exports,__webpack_require__){"use strict";const httpRequest=__webpack_require__(106).request,httpsRequest=__webpack_require__(167).request;module.exports=(protocol=>{return 0===protocol.indexOf("https")?httpsRequest:httpRequest})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function IpfsAPI(hostOrMultiaddr,port,opts){const config=getConfig();try{const maddr=multiaddr(hostOrMultiaddr).nodeAddress();config.host=maddr.address,config.port=maddr.port}catch(e){"string"==typeof hostOrMultiaddr&&(config.host=hostOrMultiaddr,config.port=port&&"object"!=typeof port?port:config.port)}let lastIndex=arguments.length;for(;!opts&&lastIndex-- >0&&!(opts=arguments[lastIndex]););if(Object.assign(config,opts),!config.host&&"undefined"!=typeof window){const split=window.location.host.split(":");config.host=split[0],config.port=split[1]}const requestAPI=getRequestAPI(config),cmds=loadCommands(requestAPI);return cmds.send=requestAPI,cmds.Buffer=Buffer,cmds}const multiaddr=__webpack_require__(56),loadCommands=__webpack_require__(340),getConfig=__webpack_require__(337),getRequestAPI=__webpack_require__(344);exports=module.exports=IpfsAPI}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}var asn1=__webpack_require__(18),inherits=__webpack_require__(1),api=exports;api.define=function(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function(base){var named;try{named=__webpack_require__(310).runInThisContext("(function "+this.name+"(entity) {\n this._initNamed(entity);\n})")}catch(e){named=function(entity){this._initNamed(entity)}}return inherits(named,base),named.prototype._initNamed=function(entity){base.call(this,entity)},new named(this)},Entity.prototype._getDecoder=function(enc){return enc=enc||"der",this.decoders.hasOwnProperty(enc)||(this.decoders[enc]=this._createNamed(asn1.decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function(enc){return enc=enc||"der",this.encoders.hasOwnProperty(enc)||(this.encoders[enc]=this._createNamed(asn1.encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},function(module,exports,__webpack_require__){function Node(enc,parent){var state={};this._baseState=state,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}var Reporter=__webpack_require__(25).Reporter,EncoderBuffer=__webpack_require__(25).EncoderBuffer,DecoderBuffer=__webpack_require__(25).DecoderBuffer,assert=__webpack_require__(229),tags=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(tags),overrided=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];module.exports=Node;var stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function(){var state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});var res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){var state=this._baseState;methods.forEach(function(method){this[method]=function(){var clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){var state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function(args){var state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),0!==children.length&&(assert(null===state.children),state.children=children,children.forEach(function(child){child._baseState.parent=this},this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map(function(arg){if("object"!=typeof arg||arg.constructor!==Object)return arg;var res={};return Object.keys(arg).forEach(function(key){key==(0|key)&&(key|=0);var value=arg[key];res[value]=key}),res}))},overrided.forEach(function(method){Node.prototype[method]=function(){var state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}}),tags.forEach(function(tag){Node.prototype[tag]=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);var state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function(){var state=this._baseState;return state.optional=!0,this},Node.prototype.def=function(val){var state=this._baseState;return assert(null===state.default),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function(newKey){var state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function(){var state=this._baseState;return state.any=!0,this},Node.prototype.choice=function(obj){var state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){var state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function(input,options){var state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));var result=state.default,present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){var tag=null;if(null!==state.explicit?tag=state.explicit:null!==state.implicit?tag=state.implicit:null!==state.tag&&(tag=state.tag),null!==tag||state.any){if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}else{var save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}}var prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){var explicit=this._decodeTag(input,state.explicit);if(input.isError(explicit))return explicit;input=explicit}var start=input.offset;if(null===state.use&&null===state.choice){ +if(state.any)var save=input.save();var body=this._decodeTag(input,null!==state.implicit?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),start,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),result=state.any?result:null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),input.isError(result))return result;if(state.any||null!==state.choice||null===state.children||state.children.forEach(function(child){child._decode(input,options)}),state.contains&&("octstr"===state.tag||"bitstr"===state.tag)){var data=new DecoderBuffer(result);result=this._getUse(state.contains,input._reporterState.obj)._decode(data,options)}}return state.obj&&present&&(result=input.leaveObject(prevObj)),null===state.key||null===result&&present!==!0?null!==prevKey&&input.exitKey(prevKey):input.leaveKey(prevKey,state.key,result),result},Node.prototype._decodeGeneric=function(tag,input,options){var state=this._baseState;return"seq"===tag||"set"===tag?null:"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null!==state.use?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error("unknown tag: "+tag)},Node.prototype._getUse=function(entity,obj){var state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){var state=this._baseState,result=null,match=!1;return Object.keys(state.choice).some(function(key){var save=input.save(),node=state.choice[key];try{var value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value:value},match=!0}catch(e){return input.restore(save),!1}return!0},this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){var state=this._baseState;if(null===state.default||state.default!==data){var result=this._encodeValue(data,reporter,parent);if(void 0!==result&&!this._skipDefault(result,reporter,parent))return result}},Node.prototype._encodeValue=function(data,reporter,parent){var state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);var result=null;if(this.reporter=reporter,state.optional&&void 0===data){if(null===state.default)return;data=state.default}var content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){if("null_"===child._baseState.tag)return child._encode(null,reporter,data);if(null===child._baseState.key)return reporter.error("Child should have a key");var prevKey=reporter.enterKey(child._baseState.key);if("object"!=typeof data)return reporter.error("Child expected, but input is not object");var res=child._encode(data[child._baseState.key],reporter,data);return reporter.leaveKey(prevKey),res},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!state.args||1!==state.args.length)return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");var child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){var state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else null!==state.use?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);var result;if(!state.any&&null===state.choice){var tag=null!==state.implicit?state.implicit:state.tag,cls=null===state.implicit?"universal":"context";null===tag?null===state.use&&reporter.error("Tag could be ommited only for .use()"):null===state.use&&(result=this._encodeComposite(tag,primitive,cls,content))}return null!==state.explicit&&(result=this._encodeComposite(state.explicit,!1,"context",result)),result},Node.prototype._encodeChoice=function(data,reporter){var state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){var state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str)}},function(module,exports,__webpack_require__){function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}var inherits=__webpack_require__(1);exports.Reporter=Reporter,Reporter.prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){var state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){var state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){var state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){var state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function(){var state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){var state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){var err,state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack),!state.options.partial)throw err;return inherited||state.errors.push(err),err},Reporter.prototype.wrapResult=function(result){var state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},inherits(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},function(module,exports,__webpack_require__){var constants=__webpack_require__(64);exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=constants._reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=constants._reverse(exports.tag)},function(module,exports,__webpack_require__){var decoders=exports;decoders.der=__webpack_require__(65),decoders.pem=__webpack_require__(129)},function(module,exports,__webpack_require__){function PEMDecoder(entity){DERDecoder.call(this,entity),this.enc="pem"}var inherits=__webpack_require__(1),Buffer=__webpack_require__(0).Buffer,DERDecoder=__webpack_require__(65);inherits(PEMDecoder,DERDecoder),module.exports=PEMDecoder,PEMDecoder.prototype.decode=function(data,options){for(var lines=data.toString().split(/[\r\n]+/g),label=options.label.toUpperCase(),re=/^-----(BEGIN|END) ([^-]+)-----$/,start=-1,end=-1,i=0;i0;)digits.push(carry%BASE),carry=carry/BASE|0}for(var string="",k=0;0===source[k]&&k=0;--q)string+=ALPHABET[digits[q]];return string}function decodeUnsafe(string){if(0===string.length)return[];for(var bytes=[0],i=0;i>=8;for(;carry>0;)bytes.push(255&carry),carry>>=8}for(var k=0;string[k]===LEADER&&k0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:null===n||isNaN(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=length)ret=stringMode?list.join(""):1===list.length?list[0]:Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&0===state.length&&endReadable(this),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata");var ret=dest.write(chunk);!1===ret&&(1!==state.pipesCount||state.pipes[0]!==dest||1!==src.listenerCount("data")||cleanedUp||(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1;return src.on("data",ondata),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var _i=0;_i-1?setImmediate:processNextTick,Buffer=__webpack_require__(0).Buffer;Writable.WritableState=WritableState;var util=__webpack_require__(3);util.inherits=__webpack_require__(1);var Stream,internalUtil={deprecate:__webpack_require__(30)};!function(){try{Stream=__webpack_require__(5)}catch(_){}finally{Stream||(Stream=__webpack_require__(6).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer;util.inherits(Writable,Stream);var Duplex;WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var Duplex;Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["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},Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))},Writable.prototype._writev=null,Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(2),__webpack_require__(13).setImmediate)},function(module,exports,__webpack_require__){(function(module){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:(this.negative=0,this.words=null,this.length=0,this.red=null,void(null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))))}function parseHex(str,start,end){for(var r=0,len=Math.min(str.length,end),i=start;i=49&&c<=54?c-49+10:c>=17&&c<=22?c-17+10:15&c}return r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}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;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=r/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){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()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){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}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),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)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer=__webpack_require__(0).Buffer}catch(e){}BN.isBN=function(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return left.cmp(right)>0?left:right},BN.min=function(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&start++,16===base?this._parseHex(number,start):this._parseBase(number,base,start),"-"===number[0]&&(this.negative=1),this.strip(),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initNumber=function(number,base,endian){number<0&&(this.negative=1,number=-number),number<67108864?(this.words=[67108863&number],this.length=1):number<4503599627370496?(this.words=[67108863&number,number/67108864&67108863],this.length=2):(assert(number<9007199254740992),this.words=[67108863&number,number/67108864&67108863,1],this.length=3),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function(number,base,endian){if(assert("number"==typeof number.length),number.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(number.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function(number,start){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=6)w=parseHex(number,i,i+6),this.words[j]|=w<>>26-off&4194303,off+=24,off>=26&&(off-=26,j++);i+6!==start&&(w=parseHex(number,start,i+6),this.words[j]|=w<>>26-off&4194303),this.strip()},BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function(){return(this.red?""};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"],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],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,off>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert("undefined"!=typeof Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(0===w)return 26;var t=w,r=0;return 0===(8191&t)&&(r+=13,t>>>=13),0===(127&t)&&(r+=7,t>>>=7),0===(15&t)&&(r+=4,t>>>=4),0===(3&t)&&(r+=2,t>>>=2),0===(1&t)&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val?this.words[off]=this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,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)+((8191&mid)<<13)|0; +c=(hi+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863,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)+((8191&mid)<<13)|0;return c=(hi+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,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,0!==c&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!==shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0!==(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0===(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0===(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0===(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0===(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return 0===(1&this.words[0])},BN.prototype.isOdd=function(){return 1===(1&this.words[0])},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function(num){var negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return 1===this.cmpn(num)},BN.prototype.gt=function(num){return 1===this.cmp(num)},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return 0===this.cmpn(num)},BN.prototype.eq=function(num){return 0===this.cmp(num)},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var rlen,r=num;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen0?r.isub(this.p):r.strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function(a,b){assert(0===(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,currentLen++,(currentLen===windowSize||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}}("undefined"==typeof module||module,this)}).call(exports,__webpack_require__(16)(module))},function(module,exports,__webpack_require__){function getCiphers(){return Object.keys(modes)}var ciphers=__webpack_require__(152);exports.createCipher=exports.Cipher=ciphers.createCipher,exports.createCipheriv=exports.Cipheriv=ciphers.createCipheriv;var deciphers=__webpack_require__(151);exports.createDecipher=exports.Decipher=deciphers.createDecipher,exports.createDecipheriv=exports.Decipheriv=deciphers.createDecipheriv; +var modes=__webpack_require__(48);exports.listCiphers=exports.getCiphers=getCiphers},function(module,exports,__webpack_require__){(function(Buffer){function Decipher(mode,key,iv){return this instanceof Decipher?(Transform.call(this),this._cache=new Splitter,this._last=void 0,this._cipher=new aes.AES(key),this._prev=new Buffer(iv.length),iv.copy(this._prev),this._mode=mode,void(this._autopadding=!0)):new Decipher(mode,key,iv)}function Splitter(){return this instanceof Splitter?void(this.cache=new Buffer("")):new Splitter}function unpad(last){for(var padded=last[15],i=-1;++i16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out}else if(this.cache.length>=16)return out=this.cache.slice(0,16),this.cache=this.cache.slice(16),out;return null},Splitter.prototype.flush=function(){if(this.cache.length)return this.cache};var modelist={ECB:__webpack_require__(73),CBC:__webpack_require__(69),CFB:__webpack_require__(70),CFB8:__webpack_require__(72),CFB1:__webpack_require__(71),OFB:__webpack_require__(74),CTR:__webpack_require__(35),GCM:__webpack_require__(35)};exports.createDecipher=createDecipher,exports.createDecipheriv=createDecipheriv}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(Buffer){function Cipher(mode,key,iv){return this instanceof Cipher?(Transform.call(this),this._cache=new Splitter,this._cipher=new aes.AES(key),this._prev=new Buffer(iv.length),iv.copy(this._prev),this._mode=mode,void(this._autopadding=!0)):new Cipher(mode,key,iv)}function Splitter(){return this instanceof Splitter?void(this.cache=new Buffer("")):new Splitter}function createCipheriv(suite,password,iv){var config=modes[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");if("string"==typeof iv&&(iv=new Buffer(iv)),"string"==typeof password&&(password=new Buffer(password)),password.length!==config.key/8)throw new TypeError("invalid key length "+password.length);if(iv.length!==config.iv)throw new TypeError("invalid iv length "+iv.length);return"stream"===config.type?new StreamCipher(modelist[config.mode],password,iv):"auth"===config.type?new AuthCipher(modelist[config.mode],password,iv):new Cipher(modelist[config.mode],password,iv)}function createCipher(suite,password){var config=modes[suite.toLowerCase()];if(!config)throw new TypeError("invalid suite type");var keys=ebtk(password,!1,config.key,config.iv);return createCipheriv(suite,keys.key,keys.iv)}var aes=__webpack_require__(34),Transform=__webpack_require__(36),inherits=__webpack_require__(1),modes=__webpack_require__(48),ebtk=__webpack_require__(80),StreamCipher=__webpack_require__(75),AuthCipher=__webpack_require__(68);inherits(Cipher,Transform),Cipher.prototype._update=function(data){this._cache.add(data);for(var chunk,thing,out=[];chunk=this._cache.get();)thing=this._mode.encrypt(this,chunk),out.push(thing);return Buffer.concat(out)},Cipher.prototype._final=function(){var chunk=this._cache.flush();if(this._autopadding)return chunk=this._mode.encrypt(this,chunk),this._cipher.scrub(),chunk;if("10101010101010101010101010101010"!==chunk.toString("hex"))throw this._cipher.scrub(),new Error("data not multiple of block length")},Cipher.prototype.setAutoPadding=function(setTo){return this._autopadding=!!setTo,this},Splitter.prototype.add=function(data){this.cache=Buffer.concat([this.cache,data])},Splitter.prototype.get=function(){if(this.cache.length>15){var out=this.cache.slice(0,16);return this.cache=this.cache.slice(16),out}return null},Splitter.prototype.flush=function(){for(var len=16-this.cache.length,padBuff=new Buffer(len),i=-1;++iuint_max||x<0?(x_pos=Math.abs(x)%uint_max,x<0?uint_max-x_pos:x_pos):x}function xor(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]}var zeros=new Buffer(16);zeros.fill(0),module.exports=GHASH,GHASH.prototype.ghash=function(block){for(var i=-1;++i0;j--)Vi[j]=Vi[j]>>>1|(1&Vi[j-1])<<31;Vi[0]=Vi[0]>>>1,lsb_Vi&&(Vi[0]=Vi[0]^225<<24)}this.state=fromArray(Zi)},GHASH.prototype.update=function(buf){this.cache=Buffer.concat([this.cache,buf]);for(var chunk;this.cache.length>=16;)chunk=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(chunk)},GHASH.prototype.final=function(abl,bl){return this.cache.length&&this.ghash(Buffer.concat([this.cache,zeros],16)),this.ghash(fromArray([0,abl,0,bl])),this.state};var uint_max=Math.pow(2,32)}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(Buffer){const Sha3=__webpack_require__(83),hashLengths=[224,256,384,512];var hash=function(bitcount){if(void 0!==bitcount&&hashLengths.indexOf(bitcount)==-1)throw new Error("Unsupported hash length");this.content=[],this.bitcount=bitcount?"keccak_"+bitcount:"keccak_512"};hash.prototype.update=function(i){if(Buffer.isBuffer(i))this.content.push(i);else{if("string"!=typeof i)throw new Error("Unsupported argument to update");this.content.push(new Buffer(i))}return this},hash.prototype.digest=function(encoding){var result=Sha3[this.bitcount](Buffer.concat(this.content));if("hex"===encoding)return result;if("binary"===encoding||void 0===encoding)return new Buffer(result,"hex").toString("binary");throw new Error("Unsupported encoding for digest: "+encoding)},module.exports={SHA3Hash:hash}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){module.exports={raw:new Buffer("00","hex"),"dag-pb":new Buffer("70","hex"),"dag-cbor":new Buffer("71","hex"),"eth-block":new Buffer("90","hex"),"eth-tx":new Buffer("91","hex")}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(Buffer){function ConcatStream(opts,cb){if(!(this instanceof ConcatStream))return new ConcatStream(opts,cb);"function"==typeof opts&&(cb=opts,opts={}),opts||(opts={});var encoding=opts.encoding,shouldInferEncoding=!1;encoding?(encoding=String(encoding).toLowerCase(),"u8"!==encoding&&"uint8"!==encoding||(encoding="uint8array")):shouldInferEncoding=!0,Writable.call(this,{objectMode:!0}),this.encoding=encoding,this.shouldInferEncoding=shouldInferEncoding,cb&&this.on("finish",function(){cb(this.getBody())}),this.body=[]}function isArrayish(arr){return/Array\]$/.test(Object.prototype.toString.call(arr))}function isBufferish(p){return"string"==typeof p||isArrayish(p)||p&&"function"==typeof p.subarray}function stringConcat(parts){for(var strings=[],i=0;i>5]|=128<>>9<<4)+14]=len;for(var a=1732584193,b=-271733879,c=-1732584194,d=271733878,i=0;i>16)+(y>>16)+(lsw>>16);return msw<<16|65535&lsw}function bit_rol(num,cnt){return num<>>32-cnt}var helpers=__webpack_require__(160);module.exports=function(buf){return helpers.hash(buf,core_md5,16)}},function(module,exports,__webpack_require__){var once=__webpack_require__(163),noop=function(){},isRequest=function(stream){return stream.setHeader&&"function"==typeof stream.abort},isChildProcess=function(stream){return stream.stdio&&Array.isArray(stream.stdio)&&3===stream.stdio.length},eos=function(stream,opts,callback){if("function"==typeof opts)return eos(stream,null,opts);opts||(opts={}),callback=once(callback||noop);var ws=stream._writableState,rs=stream._readableState,readable=opts.readable||opts.readable!==!1&&stream.readable,writable=opts.writable||opts.writable!==!1&&stream.writable,onlegacyfinish=function(){stream.writable||onfinish()},onfinish=function(){writable=!1,readable||callback()},onend=function(){readable=!1,writable||callback()},onexit=function(exitCode){callback(exitCode?new Error("exited with error code: "+exitCode):null)},onclose=function(){return(!readable||rs&&rs.ended)&&(!writable||ws&&ws.ended)?void 0:callback(new Error("premature close"))},onrequest=function(){stream.req.on("finish",onfinish)};return isRequest(stream)?(stream.on("complete",onfinish),stream.on("abort",onclose),stream.req?onrequest():stream.on("request",onrequest)):writable&&!ws&&(stream.on("end",onlegacyfinish),stream.on("close",onlegacyfinish)),isChildProcess(stream)&&stream.on("exit",onexit),stream.on("end",onend),stream.on("finish",onfinish),opts.error!==!1&&stream.on("error",callback),stream.on("close",onclose),function(){stream.removeListener("complete",onfinish),stream.removeListener("abort",onclose),stream.removeListener("request",onrequest),stream.req&&stream.req.removeListener("finish",onfinish),stream.removeListener("end",onlegacyfinish),stream.removeListener("close",onlegacyfinish),stream.removeListener("finish",onfinish),stream.removeListener("exit",onexit),stream.removeListener("end",onend),stream.removeListener("error",callback),stream.removeListener("close",onclose)}};module.exports=eos},function(module,exports,__webpack_require__){function once(fn){var f=function(){return f.called?f.value:(f.called=!0,f.value=fn.apply(this,arguments))};return f.called=!1,f}var wrappy=__webpack_require__(118);module.exports=wrappy(once),once.proto=once(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return once(this)},configurable:!0})})},function(module,exports){"use strict";module.exports=function(arr,iter,context){var results=[];return Array.isArray(arr)?(arr.forEach(function(value,index,list){var res=iter.call(context,value,index,list);Array.isArray(res)?results.push.apply(results,res):null!=res&&results.push(res)}),results):results}},function(module,exports,__webpack_require__){var util=__webpack_require__(12),INDENT_START=/[\{\[]/,INDENT_END=/[\}\]]/;module.exports=function(){var lines=[],indent=0,push=function(str){for(var spaces="";spaces.length<2*indent;)spaces+=" ";lines.push(spaces+str)},line=function(fmt){return fmt?INDENT_END.test(fmt.trim()[0])&&INDENT_START.test(fmt[fmt.length-1])?(indent--,push(util.format.apply(util,arguments)),indent++,line):INDENT_START.test(fmt[fmt.length-1])?(push(util.format.apply(util,arguments)),indent++,line):INDENT_END.test(fmt.trim()[0])?(indent--,push(util.format.apply(util,arguments)),line):(push(util.format.apply(util,arguments)),line):line};return line.toString=function(){return lines.join("\n")},line.toFunction=function(scope){var src="return ("+line.toString()+")",keys=Object.keys(scope||{}).map(function(key){return key}),vals=keys.map(function(key){return scope[key]});return Function.apply(null,keys.concat(src)).apply(null,vals)},arguments.length&&line.apply(null,arguments),line}},function(module,exports,__webpack_require__){var isProperty=__webpack_require__(179),gen=function(obj,prop){return isProperty(prop)?obj+"."+prop:obj+"["+JSON.stringify(prop)+"]"};gen.valid=isProperty,gen.property=function(prop){return isProperty(prop)?prop:JSON.stringify(prop)},module.exports=gen},function(module,exports,__webpack_require__){var http=__webpack_require__(106),https=module.exports;for(var key in http)http.hasOwnProperty(key)&&(https[key]=http[key]);https.request=function(params,cb){return params||(params={}),params.scheme="https",params.protocol="https:",http.request.call(this,params,cb)}},function(module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),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,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},function(module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i0;i--)argv.push("0");sections.splice.apply(sections,argv)}for(result=buff||new Buffer(offset+16),i=0;i>8&255,result[offset++]=255&word}}if(!result)throw Error("Invalid ip address: "+ip);return result},ip.toString=function(buff,offset,length){offset=~~offset,length=length||buff.length-offset;var result=[];if(4===length){for(var i=0;i32?"ipv6":_normalizeFamily(family);var len=4;"ipv6"===family&&(len=16);for(var buff=new Buffer(len),i=0,n=buff.length;i>bits)}return ip.toString(buff)},ip.mask=function(addr,mask){addr=ip.toBuffer(addr),mask=ip.toBuffer(mask);var result=new Buffer(Math.max(addr.length,mask.length));if(addr.length===mask.length)for(var i=0;ia.length&&(buff=b,other=a);for(var offset=buff.length-other.length,i=offset;i>>0},ip.fromLong=function(ipl){return(ipl>>>24)+"."+(ipl>>16&255)+"."+(ipl>>8&255)+"."+(255&ipl)}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function Block(data){if(!(this instanceof Block))return new Block(data);if(!data)throw new Error("Block must be constructed with data");this._cache={},data=ensureBuffer(data),Object.defineProperty(this,"data",{get(){return data},set(){throw new Error("Tried to change an immutable block")}}),this.key=((hashFunc,callback)=>{return"function"==typeof hashFunc&&(callback=hashFunc,hashFunc=null),hashFunc||(hashFunc="sha2-256"),this._cache[hashFunc]?setImmediate(()=>{callback(null,this._cache[hashFunc])}):void multihashing(this.data,hashFunc,(err,multihash)=>{return err?callback(err):(this._cache[hashFunc]=multihash,void callback(null,multihash))})})}function ensureBuffer(data){return Buffer.isBuffer(data)?data:new Buffer(data)}const multihashing=__webpack_require__(91),setImmediate=__webpack_require__(67);module.exports=Block}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";function create(name,size,multihash,callback){const link=new DAGLink(name,size,multihash);callback(null,link)}const DAGLink=__webpack_require__(20);module.exports=create},function(module,exports,__webpack_require__){"use strict";function addLink(node,link,callback){const links=cloneLinks(node),data=cloneData(node);if(link.constructor&&"DAGLink"===link.constructor.name);else if(link.constructor&&"DAGNode"===link.constructor.name)link=toDAGLink(link);else{link.multihash=link.multihash||link.hash; +try{link=new DAGLink(link.name,link.size,link.multihash)}catch(err){return callback(err)}}links.push(link),create(data,links,callback)}const dagNodeUtil=__webpack_require__(38),cloneLinks=dagNodeUtil.cloneLinks,cloneData=dagNodeUtil.cloneData,toDAGLink=dagNodeUtil.toDAGLink,DAGLink=__webpack_require__(20),create=__webpack_require__(37);module.exports=addLink},function(module,exports,__webpack_require__){"use strict";function clone(dagNode,callback){const data=cloneData(dagNode),links=cloneLinks(dagNode);create(data,links,callback)}const dagNodeUtil=__webpack_require__(38),cloneLinks=dagNodeUtil.cloneLinks,cloneData=dagNodeUtil.cloneData,create=__webpack_require__(37);module.exports=clone},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function rmLink(dagNode,nameOrMultihash,callback){const data=cloneData(dagNode);let links=cloneLinks(dagNode);if("string"==typeof nameOrMultihash)links=links.filter(link=>link.name!==nameOrMultihash);else{if(!Buffer.isBuffer(nameOrMultihash))return callback(new Error("second arg needs to be a name or multihash"),null);links=links.filter(link=>!link.multihash.equals(nameOrMultihash))}create(data,links,callback)}const dagNodeUtil=__webpack_require__(38),cloneLinks=dagNodeUtil.cloneLinks,cloneData=dagNodeUtil.cloneData,create=__webpack_require__(37);module.exports=rmLink}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";module.exports=`// An IPFS MerkleDAG Link +message PBLink { + + // multihash of the target object + optional bytes Hash = 1; + + // utf string name. should be unique per object + optional string Name = 2; + + // cumulative size of target object + optional uint64 Tsize = 3; +} + +// An IPFS MerkleDAG Node +message PBNode { + + // refs to other objects + repeated PBLink Links = 2; + + // opaque user data + optional bytes Data = 1; +}`},function(module,exports,__webpack_require__){"use strict";const util=__webpack_require__(51),bs58=__webpack_require__(10);exports=module.exports,exports.multicodec="dag-pb",exports.resolve=((block,path,callback)=>{function gotNode(err,node){if(err)return callback(err);const split=path.split("/");if("links"===split[0]){let remainderPath="";if(!split[1])return callback(null,{value:node.links.map(l=>{return l.toJSON()}),remainderPath:""});const values={};node.links.forEach((l,i)=>{const link=l.toJSON();values[i]=link.multihash,values[link.name]=link.multihash});let value=values[split[1]];split[2]&&(split.shift(),split.shift(),remainderPath=split.join("/"),value={"/":value}),callback(null,{value:value,remainderPath:remainderPath})}else"data"===split[0]?callback(null,{value:node.data,remainderPath:""}):callback(new Error("path not available"))}util.deserialize(block.data,gotNode)}),exports.tree=((block,options,callback)=>{"function"==typeof options&&(callback=options,options={}),options||(options={}),util.deserialize(block.data,(err,node)=>{if(err)return callback(err);const paths=[];node.links.forEach(link=>{paths.push({path:link.name||"",value:bs58.encode(link.multihash).toString()})}),node.data&&node.data.length>0&&paths.push({path:"data",value:node.data}),callback(null,paths)})})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function isMultihash(hash){var formatted=convertToString(hash);try{var buffer=new Buffer(base58.decode(formatted));return multihash.decode(buffer),!0}catch(e){return!1}}function isIpfs(input,pattern){var formatted=convertToString(input);if(!formatted)return!1;var match=formatted.match(pattern);if(!match)return!1;if("ipfs"!==match[1])return!1;var hash=match[4];return isMultihash(hash)}function isIpns(input,pattern){var formatted=convertToString(input);if(!formatted)return!1;var match=formatted.match(pattern);return!!match&&"ipns"===match[1]}function convertToString(input){return Buffer.isBuffer(input)?base58.encode(input):"string"==typeof input&&input}var base58=__webpack_require__(10),multihash=__webpack_require__(14),urlPattern=/^https?:\/\/[^\/]+\/(ip(f|n)s)\/((\w+).*)/,pathPattern=/^\/(ip(f|n)s)\/((\w+).*)/;module.exports={multihash:isMultihash,ipfsUrl:function(url){return isIpfs(url,urlPattern)},ipnsUrl:function(url){return isIpns(url,urlPattern)},url:function(_url){return isIpfs(_url,urlPattern)||isIpns(_url,urlPattern)},urlPattern:urlPattern,ipfsPath:function(path){return isIpfs(path,pathPattern)},ipnsPath:function(path){return isIpns(path,pathPattern)},path:function(_path){return isIpfs(_path,pathPattern)||isIpns(_path,pathPattern)},pathPattern:pathPattern,urlOrPath:function(x){return isIpfs(x,urlPattern)||isIpns(x,urlPattern)||isIpfs(x,pathPattern)||isIpns(x,pathPattern)}}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function isProperty(str){return/^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str)}module.exports=isProperty},function(module,exports){"use strict";var isStream=module.exports=function(stream){return null!==stream&&"object"==typeof stream&&"function"==typeof stream.pipe};isStream.writable=function(stream){return isStream(stream)&&stream.writable!==!1&&"function"==typeof stream._write&&"object"==typeof stream._writableState},isStream.readable=function(stream){return isStream(stream)&&stream.readable!==!1&&"function"==typeof stream._read&&"object"==typeof stream._readableState},isStream.duplex=function(stream){return isStream.writable(stream)&&isStream.readable(stream)},isStream.transform=function(stream){return isStream.duplex(stream)&&"function"==typeof stream._transform&&"object"==typeof stream._transformState}},function(module,exports,__webpack_require__){function isStream(obj){return obj instanceof stream.Stream}function isReadable(obj){return isStream(obj)&&"function"==typeof obj._read&&"object"==typeof obj._readableState}function isWritable(obj){return isStream(obj)&&"function"==typeof obj._write&&"object"==typeof obj._writableState}function isDuplex(obj){return isReadable(obj)&&isWritable(obj)}var stream=__webpack_require__(5);module.exports=isStream,module.exports.isReadable=isReadable,module.exports.isWritable=isWritable,module.exports.isDuplex=isDuplex},function(module,exports,__webpack_require__){!function(global){"use strict";var buffer,_Base64=global.Base64,version="2.1.9";if("undefined"!=typeof module&&module.exports)try{buffer=__webpack_require__(0).Buffer}catch(err){}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64tab=function(bin){for(var t={},i=0,l=bin.length;i>>6)+fromCharCode(128|63&cc):fromCharCode(224|cc>>>12&15)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|63&cc)}var cc=65536+1024*(c.charCodeAt(0)-55296)+(c.charCodeAt(1)-56320);return fromCharCode(240|cc>>>18&7)+fromCharCode(128|cc>>>12&63)+fromCharCode(128|cc>>>6&63)+fromCharCode(128|63&cc)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=function(u){return u.replace(re_utob,cb_utob)},cb_encode=function(ccc){var padlen=[0,2,1][ccc.length%3],ord=ccc.charCodeAt(0)<<16|(ccc.length>1?ccc.charCodeAt(1):0)<<8|(ccc.length>2?ccc.charCodeAt(2):0),chars=[b64chars.charAt(ord>>>18),b64chars.charAt(ord>>>12&63),padlen>=2?"=":b64chars.charAt(ord>>>6&63),padlen>=1?"=":b64chars.charAt(63&ord)];return chars.join("")},btoa=global.btoa?function(b){return global.btoa(b)}:function(b){return b.replace(/[\s\S]{1,3}/g,cb_encode)},_encode=buffer?function(u){return(u.constructor===buffer.constructor?u:new buffer(u)).toString("base64")}:function(u){return btoa(utob(u))},encode=function(u,urisafe){return urisafe?_encode(String(u)).replace(/[+\/]/g,function(m0){return"+"==m0?"-":"_"}).replace(/=/g,""):_encode(String(u))},encodeURI=function(u){return encode(u,!0)},re_btou=new RegExp(["[À-ß][€-¿]","[à-ï][€-¿]{2}","[ð-÷][€-¿]{3}"].join("|"),"g"),cb_btou=function(cccc){switch(cccc.length){case 4:var cp=(7&cccc.charCodeAt(0))<<18|(63&cccc.charCodeAt(1))<<12|(63&cccc.charCodeAt(2))<<6|63&cccc.charCodeAt(3),offset=cp-65536;return fromCharCode((offset>>>10)+55296)+fromCharCode((1023&offset)+56320);case 3:return fromCharCode((15&cccc.charCodeAt(0))<<12|(63&cccc.charCodeAt(1))<<6|63&cccc.charCodeAt(2));default:return fromCharCode((31&cccc.charCodeAt(0))<<6|63&cccc.charCodeAt(1))}},btou=function(b){return b.replace(re_btou,cb_btou)},cb_decode=function(cccc){var len=cccc.length,padlen=len%4,n=(len>0?b64tab[cccc.charAt(0)]<<18:0)|(len>1?b64tab[cccc.charAt(1)]<<12:0)|(len>2?b64tab[cccc.charAt(2)]<<6:0)|(len>3?b64tab[cccc.charAt(3)]:0),chars=[fromCharCode(n>>>16),fromCharCode(n>>>8&255),fromCharCode(255&n)];return chars.length-=[0,0,2,1][padlen],chars.join("")},atob=global.atob?function(a){return global.atob(a)}:function(a){return a.replace(/[\s\S]{1,4}/g,cb_decode)},_decode=buffer?function(a){return(a.constructor===buffer.constructor?a:new buffer(a,"base64")).toString()}:function(a){return btou(atob(a))},decode=function(a){return _decode(String(a).replace(/[-_]/g,function(m0){return"-"==m0?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))},noConflict=function(){var Base64=global.Base64;return global.Base64=_Base64,Base64};if(global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict},"function"==typeof Object.defineProperty){var noEnum=function(v){return{value:v,enumerable:!1,writable:!0,configurable:!0}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)})),Object.defineProperty(String.prototype,"toBase64",noEnum(function(urisafe){return encode(this,urisafe)})),Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,!0)}))}}global.Meteor&&(Base64=global.Base64)}(this)},function(module,exports){module.exports={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_SYMLINK:2097152,O_NONBLOCK:4,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGSYS:12,SSL_OP_ALL:2147486719,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:0,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:32,SSL_OP_MICROSOFT_SESS_ID_BUG:1,SSL_OP_MSIE_SSLV2_RSA_PADDING:0,SSL_OP_NETSCAPE_CA_DN_BUG:536870912,SSL_OP_NETSCAPE_CHALLENGE_BUG:2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:1073741824,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:8,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:16777216,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_SINGLE_DH_USE:1048576,SSL_OP_SINGLE_ECDH_USE:524288,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:128,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:0,SSL_OP_TLS_BLOCK_PADDING_BUG:512,SSL_OP_TLS_D5_BUG:256,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_ECDH:16,ENGINE_METHOD_ECDSA:32,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_STORE:256,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_UDP_REUSEADDR:4}},function(module,exports){module.exports={name:"@haad/ipfs-api",version:"13.0.0-beta.2",description:"A client library for the IPFS HTTP API. Follows interface-ipfs-core spec",main:"src/index.js",browser:{glob:!1,fs:!1,stream:"readable-stream",http:"stream-http"},scripts:{test:"gulp test","test:node":"gulp test:node","test:browser":"gulp test:browser",lint:"aegir-lint",build:"gulp build",release:"gulp release","release-minor":"gulp release --type minor","release-major":"gulp release --type major",coverage:"gulp coverage","coverage-publish":"aegir-coverage publish"},dependencies:{async:"^2.1.2",bl:"^1.1.2",bs58:"^3.0.0","concat-stream":"^1.5.2","detect-node":"^2.0.3",flatmap:"0.0.3",glob:"^7.1.1","ipfs-block":"^0.5.0","ipld-dag-pb":"^0.9.0","is-ipfs":"^0.2.1",isstream:"^0.1.2","js-base64":"^2.1.9","lru-cache":"^4.0.1",multiaddr:"^2.0.3","multipart-stream":"^2.0.1",ndjson:"^1.4.3",once:"^1.4.0","peer-id":"^0.8.0","peer-info":"^0.8.0","promisify-es6":"^1.0.2",qs:"^6.3.0","readable-stream":"^1.1.14","stream-http":"^2.5.0",streamifier:"^0.1.1","tar-stream":"^1.5.2"},engines:{node:">=4.0.0",npm:">=3.0.0"},repository:{type:"git",url:"https://github.com/ipfs/js-ipfs-api"},devDependencies:{aegir:"^9.1.2",chai:"^3.5.0","eslint-plugin-react":"^6.7.1",gulp:"^3.9.1",hapi:"^15.2.0","interface-ipfs-core":"^0.21.0","ipfs-daemon":"^0.3.0-beta.1","ipfsd-ctl":"^0.17.0","pre-commit":"^1.1.3","socket.io":"^1.5.1","socket.io-client":"^1.5.1","stream-equal":"^0.1.9"},"pre-commit":["lint","test"],keywords:["ipfs"],author:"Matt Bell ",contributors:["Alex Mingoia ","Connor Keenan ","David Braun ","David Dias ","Fil ","Francisco Baio Dias ","Friedel Ziegelmayer ","Gavin McDermott ","Harlan T Wood ","Harlan T Wood ","Holodisc ","Jason Carver ","Jeromy ","Jeromy ","Joe Turgeon ","Juan Batiz-Benet ","Kristoffer Ström ","Matt Bell ","Mithgol ","Richard Littauer ","Stephen Whitmore ","Travis Person ","Victor Bjelkholm ","Victor Bjelkholm ","ethers ","greenkeeperio-bot ","haad ","nginnever ","priecint ","samuli "],license:"MIT",bugs:{url:"https://github.com/ipfs/js-ipfs-api/issues"},homepage:"https://github.com/ipfs/js-ipfs-api"}},function(module,exports){"use strict";exports.names={sha1:17,"sha2-256":18,"sha2-512":19,"sha3-224":23,"sha3-256":22,"sha3-384":21,"sha3-512":20,"shake-128":24,"shake-256":25,"keccak-224":26,"keccak-256":27,"keccak-384":28,"keccak-512":29,blake2b:64,blake2s:65},exports.codes={17:"sha1",18:"sha2-256",19:"sha2-512",23:"sha3-224",22:"sha3-256",21:"sha3-384",20:"sha3-512",24:"shake-128",25:"shake-256",26:"keccak-224",27:"keccak-256",28:"keccak-384",29:"keccak-512",64:"blake2b",65:"blake2s"},exports.defaultLengths={17:20,18:32,19:64,23:28,22:32,21:48,20:64,24:32,25:64,26:28,27:32,28:48,29:64,64:64,65:32}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const bs58=__webpack_require__(10),cs=__webpack_require__(185);exports.toHexString=function(m){if(!Buffer.isBuffer(m))throw new Error("must be passed a buffer");return m.toString("hex")},exports.fromHexString=function(s){return new Buffer(s,"hex")},exports.toB58String=function(m){if(!Buffer.isBuffer(m))throw new Error("must be passed a buffer");return bs58.encode(m)},exports.fromB58String=function(s){let encoded=s;return Buffer.isBuffer(s)&&(encoded=s.toString()),new Buffer(bs58.decode(encoded))},exports.decode=function(buf){exports.validate(buf);const code=buf[0];return{code:code,name:cs.codes[code],length:buf[1],digest:buf.slice(2)}},exports.encode=function(digest,code,length){if(!digest||!code)throw new Error("multihash encode requires at least two args: digest, code");const hashfn=exports.coerceCode(code);if(!Buffer.isBuffer(digest))throw new Error("digest should be a Buffer");if(null==length&&(length=digest.length),length&&digest.length!==length)throw new Error("digest length should be equal to specified length.");if(length>127)throw new Error("multihash does not yet support digest lengths greater than 127 bytes.");return Buffer.concat([new Buffer([hashfn,length]),digest])},exports.coerceCode=function(name){let code=name;if("string"==typeof name){if(!cs.names[name])throw new Error(`Unrecognized hash function named: ${name}`);code=cs.names[name]}if("number"!=typeof code)throw new Error(`Hash function code should be a number. Got: ${code}`);if(!cs.codes[code]&&!exports.isAppCode(code))throw new Error(`Unrecognized function code: ${code}`);return code},exports.isAppCode=function(code){return code>0&&code<16},exports.isValidCode=function(code){return!!exports.isAppCode(code)||!!cs.codes[code]},exports.validate=function(multihash){if(!Buffer.isBuffer(multihash))throw new Error("multihash must be a Buffer");if(multihash.length<3)throw new Error("multihash too short. must be > 3 bytes.");if(multihash.length>129)throw new Error("multihash too long. must be < 129 bytes.");let code=multihash[0];if(!exports.isValidCode(code))throw new Error(`multihash unknown function code: 0x${code.toString(16)}`);if(multihash.slice(2).length!==multihash[1])throw new Error(`multihash length inconsistent: 0x${multihash.toString("hex")}`)}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function getWebCrypto(){if("undefined"!=typeof window){if(window.crypto)return window.crypto.subtle||window.crypto.webkitSubtle;if(window.msCrypto)return window.msCrypto.subtle}}function webCryptoHash(type){if(!webCrypto)throw new Error("Please use a browser with webcrypto support");return(data,callback)=>{const res=webCrypto.digest({name:type},data);return"function"!=typeof res.then?(res.onerror=(()=>{callback(`Error hashing data using ${type}`)}),void(res.oncomplete=(e=>{callback(null,e.target.result)}))):void nodeify(res.then(raw=>new Buffer(new Uint8Array(raw))),callback)}}function sha1(buf,callback){webCryptoHash("SHA-1")(buf,callback)}function sha2256(buf,callback){webCryptoHash("SHA-256")(buf,callback)}function sha2512(buf,callback){webCryptoHash("SHA-512")(buf,callback)}const nodeify=__webpack_require__(29),webCrypto=getWebCrypto();module.exports={sha1:sha1,sha2256:sha2256,sha2512:sha2512}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const sha3=__webpack_require__(83),toCallback=__webpack_require__(190),sha=__webpack_require__(187),toBuf=(doWork,other)=>input=>{return new Buffer(doWork(input,other),"hex")};module.exports={sha1:sha.sha1,sha2256:sha.sha2256,sha2512:sha.sha2512,sha3512:toCallback(toBuf(sha3.sha3_512)),sha3384:toCallback(toBuf(sha3.sha3_384)),sha3256:toCallback(toBuf(sha3.sha3_256)),sha3224:toCallback(toBuf(sha3.sha3_224)),shake128:toCallback(toBuf(sha3.shake_128,256)),shake256:toCallback(toBuf(sha3.shake_256,512)),keccak224:toCallback(toBuf(sha3.keccak_224)),keccak256:toCallback(toBuf(sha3.keccak_256)),keccak384:toCallback(toBuf(sha3.keccak_384)),keccak512:toCallback(toBuf(sha3.keccak_512))}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function Multihashing(buf,func,length,callback){if("function"==typeof length&&(callback=length,length=void 0),!callback)throw new Error("Missing callback");Multihashing.digest(buf,func,length,(err,digest)=>{return err?callback(err):void callback(null,multihash.encode(digest,func,length))})}const multihash=__webpack_require__(186),crypto=__webpack_require__(188);module.exports=Multihashing,Multihashing.Buffer=Buffer,Multihashing.multihash=multihash,Multihashing.digest=function(buf,func,length,callback){if("function"==typeof length&&(callback=length,length=void 0),!callback)throw new Error("Missing callback");let cb=callback;length&&(cb=((err,digest)=>{return err?callback(err):void callback(null,digest.slice(0,length))}));let hash;try{hash=Multihashing.createHash(func)}catch(err){return cb(err)}hash(buf,cb)},Multihashing.createHash=function(func){if(func=multihash.coerceCode(func),!Multihashing.functions[func])throw new Error("multihash function "+func+" not yet supported");return Multihashing.functions[func]},Multihashing.functions={17:crypto.sha1,18:crypto.sha2256,19:crypto.sha2512,20:crypto.sha3512,21:crypto.sha3384,22:crypto.sha3256,23:crypto.sha3224,24:crypto.shake128,25:crypto.shake256,26:crypto.keccak224,27:crypto.keccak256,28:crypto.keccak384,29:crypto.keccak512}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const setImmediate=__webpack_require__(67);module.exports=function(doWork){return function(input,callback){const done=(err,res)=>setImmediate(()=>{callback(err,res)});let res;try{res=doWork(input)}catch(err){return void done(err)}done(null,res)}}},function(module,exports,__webpack_require__){"use strict";const ciphers=__webpack_require__(192),CIPHER_MODES={16:"aes-128-ctr",32:"aes-256-ctr"};exports.create=function(key,iv,callback){const mode=CIPHER_MODES[key.length];if(!mode)return callback(new Error("Invalid key length"));const cipher=ciphers.createCipheriv(mode,key,iv),decipher=ciphers.createDecipheriv(mode,key,iv),res={ +encrypt(data,cb){cb(null,cipher.update(data))},decrypt(data,cb){cb(null,decipher.update(data))}};callback(null,res)}},function(module,exports,__webpack_require__){"use strict";const crypto=__webpack_require__(150);module.exports={createCipheriv:crypto.createCipheriv,createDecipheriv:crypto.createDecipheriv}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function marshalPublicKey(jwk){const byteLen=curveLengths[jwk.crv];return Buffer.concat([new Buffer([4]),toBn(jwk.x).toBuffer("be",byteLen),toBn(jwk.y).toBuffer("be",byteLen)],1+2*byteLen)}function unmarshalPublicKey(curve,key){const byteLen=curveLengths[curve];if(!key.slice(0,1).equals(new Buffer([4])))throw new Error("Invalid key format");const x=new BN(key.slice(1,byteLen+1)),y=new BN(key.slice(1+byteLen));return{kty:"EC",crv:curve,x:toBase64(x),y:toBase64(y),ext:!0}}function unmarshalPrivateKey(curve,key){const result=unmarshalPublicKey(curve,key.public);return result.d=toBase64(new BN(key.private)),result}const crypto=__webpack_require__(40)(),nodeify=__webpack_require__(29),BN=__webpack_require__(18).bignum,util=__webpack_require__(85),toBase64=util.toBase64,toBn=util.toBn,bits={"P-256":256,"P-384":384,"P-521":521};exports.generateEphmeralKeyPair=function(curve,callback){nodeify(crypto.subtle.generateKey({name:"ECDH",namedCurve:curve},!0,["deriveBits"]).then(pair=>{const genSharedKey=(theirPub,forcePrivate,cb)=>{"function"==typeof forcePrivate&&(cb=forcePrivate,forcePrivate=void 0);let privateKey;privateKey=forcePrivate?crypto.subtle.importKey("jwk",unmarshalPrivateKey(curve,forcePrivate),{name:"ECDH",namedCurve:curve},!1,["deriveBits"]):Promise.resolve(pair.privateKey);const keys=Promise.all([crypto.subtle.importKey("jwk",unmarshalPublicKey(curve,theirPub),{name:"ECDH",namedCurve:curve},!1,[]),privateKey]);nodeify(keys.then(keys=>crypto.subtle.deriveBits({name:"ECDH",namedCurve:curve,public:keys[0]},keys[1],bits[curve])).then(bits=>Buffer.from(bits)),cb)};return crypto.subtle.exportKey("jwk",pair.publicKey).then(publicKey=>{return{key:marshalPublicKey(publicKey),genSharedKey:genSharedKey}})}),callback)};const curveLengths={"P-256":32,"P-384":48,"P-521":66}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const nodeify=__webpack_require__(29),crypto=__webpack_require__(40)(),lengths=__webpack_require__(195),hashTypes={SHA1:"SHA-1",SHA256:"SHA-256",SHA512:"SHA-512"};exports.create=function(hashType,secret,callback){const hash=hashTypes[hashType];nodeify(crypto.subtle.importKey("raw",secret,{name:"HMAC",hash:{name:hash}},!1,["sign"]).then(key=>{return{digest(data,cb){nodeify(crypto.subtle.sign({name:"HMAC"},key,data).then(raw=>Buffer.from(raw)),cb)},length:lengths[hashType]}}),callback)}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";module.exports={SHA1:20,SHA256:32,SHA512:64}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function exportKey(pair){return Promise.all([crypto.subtle.exportKey("jwk",pair.privateKey),crypto.subtle.exportKey("jwk",pair.publicKey)])}function derivePublicFromPrivate(jwKey){return crypto.subtle.importKey("jwk",{kty:jwKey.kty,n:jwKey.n,e:jwKey.e,alg:jwKey.alg,kid:jwKey.kid},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}const nodeify=__webpack_require__(29),crypto=__webpack_require__(40)();exports.utils=__webpack_require__(197),exports.generateKey=function(bits,callback){nodeify(crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:bits,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(exportKey).then(keys=>({privateKey:keys[0],publicKey:keys[1]})),callback)},exports.unmarshalPrivateKey=function(key,callback){const privateKey=crypto.subtle.importKey("jwk",key,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]);nodeify(Promise.all([privateKey,derivePublicFromPrivate(key)]).then(keys=>exportKey({privateKey:keys[0],publicKey:keys[1]})).then(keys=>({privateKey:keys[0],publicKey:keys[1]})),callback)},exports.getRandomValues=function(arr){return Buffer.from(crypto.getRandomValues(arr))},exports.hashAndSign=function(key,msg,callback){nodeify(crypto.subtle.importKey("jwk",key,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]).then(privateKey=>{return crypto.subtle.sign({name:"RSASSA-PKCS1-v1_5"},privateKey,Uint8Array.from(msg))}).then(sig=>Buffer.from(sig)),callback)},exports.hashAndVerify=function(key,sig,msg,callback){nodeify(crypto.subtle.importKey("jwk",key,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]).then(publicKey=>{return crypto.subtle.verify({name:"RSASSA-PKCS1-v1_5"},publicKey,sig,msg)}),callback)}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const asn1=__webpack_require__(18),util=__webpack_require__(85),toBase64=util.toBase64,toBn=util.toBn,RSAPrivateKey=asn1.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())}),AlgorithmIdentifier=asn1.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid({"1.2.840.113549.1.1.1":"rsa"}),this.key("none").optional().null_(),this.key("curve").optional().objid(),this.key("params").optional().seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()))}),PublicKey=asn1.define("RSAPublicKey",function(){this.seq().obj(this.key("algorithm").use(AlgorithmIdentifier),this.key("subjectPublicKey").bitstr())}),RSAPublicKey=asn1.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});exports.pkcs1ToJwk=function(bytes){const asn1=RSAPrivateKey.decode(bytes,"der");return{kty:"RSA",n:toBase64(asn1.modulus),e:toBase64(asn1.publicExponent),d:toBase64(asn1.privateExponent),p:toBase64(asn1.prime1),q:toBase64(asn1.prime2),dp:toBase64(asn1.exponent1),dq:toBase64(asn1.exponent2),qi:toBase64(asn1.coefficient),alg:"RS256",kid:"2011-04-29"}},exports.jwkToPkcs1=function(jwk){return RSAPrivateKey.encode({version:0,modulus:toBn(jwk.n),publicExponent:toBn(jwk.e),privateExponent:toBn(jwk.d),prime1:toBn(jwk.p),prime2:toBn(jwk.q),exponent1:toBn(jwk.dp),exponent2:toBn(jwk.dq),coefficient:toBn(jwk.qi)},"der")},exports.pkixToJwk=function(bytes){const ndata=PublicKey.decode(bytes,"der"),asn1=RSAPublicKey.decode(ndata.subjectPublicKey.data,"der");return{kty:"RSA",n:toBase64(asn1.modulus),e:toBase64(asn1.publicExponent),alg:"RS256",kid:"2011-04-29"}},exports.jwkToPkix=function(jwk){return PublicKey.encode({algorithm:{algorithm:"rsa",none:null},subjectPublicKey:{data:RSAPublicKey.encode({modulus:toBn(jwk.n),publicExponent:toBn(jwk.e)},"der")}},"der")}},function(module,exports,__webpack_require__){"use strict";const crypto=__webpack_require__(39);module.exports=((curve,callback)=>{crypto.ecdh.generateEphmeralKeyPair(curve,callback)})},function(module,exports,__webpack_require__){"use strict";const protobuf=__webpack_require__(58),pbm=protobuf(__webpack_require__(84)),c=__webpack_require__(39);exports.hmac=c.hmac,exports.aes=c.aes,exports.webcrypto=c.webcrypto;const keys=exports.keys=__webpack_require__(201);exports.keyStretcher=__webpack_require__(200),exports.generateEphemeralKeyPair=__webpack_require__(198),exports.generateKeyPair=((type,bits,cb)=>{let key=keys[type.toLowerCase()];return key?void key.generateKeyPair(bits,cb):cb(new Error("invalid or unsupported key type"))}),exports.unmarshalPublicKey=(buf=>{const decoded=pbm.PublicKey.decode(buf);switch(decoded.Type){case pbm.KeyType.RSA:return keys.rsa.unmarshalRsaPublicKey(decoded.Data);default:throw new Error("invalid or unsupported key type")}}),exports.marshalPublicKey=((key,type)=>{if(type=(type||"rsa").toLowerCase(),"rsa"!==type)throw new Error("invalid or unsupported key type");return key.bytes}),exports.unmarshalPrivateKey=((buf,callback)=>{const decoded=pbm.PrivateKey.decode(buf);switch(decoded.Type){case pbm.KeyType.RSA:return keys.rsa.unmarshalRsaPrivateKey(decoded.Data,callback);default:callback(new Error("invalid or unsupported key type"))}}),exports.marshalPrivateKey=((key,type)=>{if(type=(type||"rsa").toLowerCase(),"rsa"!==type)throw new Error("invalid or unsupported key type");return key.bytes})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const crypto=__webpack_require__(39),whilst=__webpack_require__(143),cipherMap={"AES-128":{ivSize:16,keySize:16},"AES-256":{ivSize:16,keySize:32},Blowfish:{ivSize:8,cipherKeySize:32}};module.exports=((cipherType,hash,secret,callback)=>{const cipher=cipherMap[cipherType];if(!cipher)return callback(new Error("unkown cipherType passed"));if(!hash)return callback(new Error("unkown hashType passed"));const cipherKeySize=cipher.keySize,ivSize=cipher.ivSize,hmacKeySize=20,seed=Buffer.from("key expansion"),resultLength=2*(ivSize+cipherKeySize+hmacKeySize);crypto.hmac.create(hash,secret,(err,m)=>{return err?callback(err):void m.digest(seed,(err,a)=>{function stretch(cb){m.digest(Buffer.concat([a,seed]),(err,b)=>{if(err)return cb(err);let todo=b.length;j+todo>resultLength&&(todo=resultLength-j),result.push(b),j+=todo,m.digest(a,(err,_a)=>{return err?cb(err):(a=_a,void cb())})})}function finish(err){if(err)return callback(err);const half=resultLength/2,resultBuffer=Buffer.concat(result),r1=resultBuffer.slice(0,half),r2=resultBuffer.slice(half,resultLength),createKey=res=>({iv:res.slice(0,ivSize),cipherKey:res.slice(ivSize,ivSize+cipherKeySize),macKey:res.slice(ivSize+cipherKeySize)});callback(null,{k1:createKey(r1),k2:createKey(r2)})}if(err)return callback(err);let result=[],j=0;whilst(()=>j{return err?callback(err):void callback(null,new RsaPrivateKey(keys.privateKey,keys.publicKey))})}function unmarshalRsaPublicKey(bytes){const jwk=crypto.utils.pkixToJwk(bytes);return new RsaPublicKey(jwk)}function generateKeyPair(bits,cb){crypto.generateKey(bits,(err,keys)=>{return err?cb(err):void cb(null,new RsaPrivateKey(keys.privateKey,keys.publicKey))})}function ensure(cb){if("function"!=typeof cb)throw new Error("callback is required")}const multihashing=__webpack_require__(189),protobuf=__webpack_require__(58),crypto=__webpack_require__(39).rsa,pbm=protobuf(__webpack_require__(84));class RsaPublicKey{constructor(key){this._key=key}verify(data,sig,callback){ensure(callback),crypto.hashAndVerify(this._key,sig,data,callback)}marshal(){return crypto.utils.jwkToPkix(this._key)}get bytes(){return pbm.PublicKey.encode({Type:pbm.KeyType.RSA,Data:this.marshal()})}encrypt(bytes){return this._key.encrypt(bytes,"RSAES-PKCS1-V1_5")}equals(key){return this.bytes.equals(key.bytes)}hash(callback){ensure(callback),multihashing(this.bytes,"sha2-256",callback)}}class RsaPrivateKey{constructor(key,publicKey){this._key=key,this._publicKey=publicKey}genSecret(){return crypto.getRandomValues(new Uint8Array(16))}sign(message,callback){ensure(callback),crypto.hashAndSign(this._key,message,callback)}get public(){if(!this._publicKey)throw new Error("public key not provided");return new RsaPublicKey(this._publicKey)}decrypt(msg,callback){crypto.decrypt(this._key,msg,callback)}marshal(){return crypto.utils.jwkToPkcs1(this._key)}get bytes(){return pbm.PrivateKey.encode({Type:pbm.KeyType.RSA,Data:this.marshal()})}equals(key){return this.bytes.equals(key.bytes)}hash(callback){ensure(callback),multihashing(this.bytes,"sha2-256",callback)}}module.exports={RsaPublicKey:RsaPublicKey,RsaPrivateKey:RsaPrivateKey,unmarshalRsaPublicKey:unmarshalRsaPublicKey,unmarshalRsaPrivateKey:unmarshalRsaPrivateKey,generateKeyPair:generateKeyPair}},function(module,exports,__webpack_require__){(function(global,module){function arrayFilter(array,predicate){for(var index=-1,length=array?array.length:0,resIndex=0,result=[];++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==typeof value}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toString(value){return null==value?"":baseToString(value)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function identity(value){return value}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}var LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reEscapeChar=/\\(\\)?/g,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||""); +return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,nativeKeys=overArg(Object.keys,Object),DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=Symbol?Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var baseEach=createBaseEach(baseForOwn),baseFor=createBaseFor(),getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set)!=setTag||WeakMap&&getTag(new WeakMap)!=weakMapTag)&&(getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):void 0;if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var stringToPath=memoize(function(string){string=toString(string);var result=[];return reLeadingDot.test(string)&&result.push(""),string.replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result});memoize.Cache=MapCache;var isArray=Array.isArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=filter}).call(exports,__webpack_require__(8),__webpack_require__(16)(module))},function(module,exports){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}module.exports=apply},function(module,exports,__webpack_require__){function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)!inherited&&!hasOwnProperty.call(value,key)||skipIndexes&&("length"==key||isBuff&&("offset"==key||"parent"==key)||isType&&("buffer"==key||"byteLength"==key||"byteOffset"==key)||isIndex(key,length))||result.push(key);return result}var baseTimes=__webpack_require__(209),isArguments=__webpack_require__(220),isArray=__webpack_require__(89),isBuffer=__webpack_require__(221),isIndex=__webpack_require__(212),isTypedArray=__webpack_require__(224),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;module.exports=arrayLikeKeys},function(module,exports,__webpack_require__){function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag}var baseGetTag=__webpack_require__(53),isObjectLike=__webpack_require__(54),argsTag="[object Arguments]";module.exports=baseIsArguments},function(module,exports,__webpack_require__){function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}var baseGetTag=__webpack_require__(53),isLength=__webpack_require__(90),isObjectLike=__webpack_require__(54),argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1,module.exports=baseIsTypedArray},function(module,exports,__webpack_require__){function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty.call(object,key)&&"constructor"!=key&&result.push(key);return result}var isPrototype=__webpack_require__(213),nativeKeys=__webpack_require__(214),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;module.exports=baseKeys},function(module,exports){function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index-1&&value%1==0&&value-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=null==array?0:array.length;++index-1;);return index}function charsEndIndex(strSymbols,chrSymbols){for(var index=strSymbols.length;index--&&baseIndexOf(chrSymbols,strSymbols[index],0)>-1;);return index}function countHolders(array,placeholder){for(var length=array.length,result=0;length--;)array[length]===placeholder&&++result;return result}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function getValue(object,key){return null==object?undefined:object[key]}function hasUnicode(string){return reHasUnicode.test(string)}function hasUnicodeWord(string){return reHasUnicodeWord.test(string)}function iteratorToArray(iterator){for(var data,result=[];!(data=iterator.next()).done;)result.push(data.value);return result}function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}function overArg(func,transform){return function(arg){return func(transform(arg))}}function replaceHolders(array,placeholder){for(var index=-1,length=array.length,resIndex=0,result=[];++index>>1,wrapFlags=[["ary",WRAP_ARY_FLAG],["bind",WRAP_BIND_FLAG],["bindKey",WRAP_BIND_KEY_FLAG],["curry",WRAP_CURRY_FLAG],["curryRight",WRAP_CURRY_RIGHT_FLAG],["flip",WRAP_FLIP_FLAG],["partial",WRAP_PARTIAL_FLAG],["partialRight",WRAP_PARTIAL_RIGHT_FLAG],["rearg",WRAP_REARG_FLAG]],argsTag="[object Arguments]",arrayTag="[object Array]",asyncTag="[object AsyncFunction]",boolTag="[object Boolean]",dateTag="[object Date]",domExcTag="[object DOMException]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",nullTag="[object Null]",objectTag="[object Object]",promiseTag="[object Promise]",proxyTag="[object Proxy]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",undefinedTag="[object Undefined]",weakMapTag="[object WeakMap]",weakSetTag="[object WeakSet]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g,reEscapedHtml=/&(?:amp|lt|gt|quot|#39);/g,reUnescapedHtml=/[&<>"']/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source),reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g,reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reHasRegExpChar=RegExp(reRegExpChar.source),reTrim=/^\s+|\s+$/g,reTrimStart=/^\s+/,reTrimEnd=/\s+$/,reWrapComment=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,reWrapDetails=/\{\n\/\* \[wrapped with (.+)\] \*/,reSplitDetails=/,? & /,reAsciiWord=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,reEscapeChar=/\\(\\)?/g,reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,reFlags=/\w*$/,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,reLatin=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,reNoMatch=/($^)/,reUnescapedString=/['\n\r\u2028\u2029\\]/g,rsAstralRange="\\ud800-\\udfff",rsComboMarksRange="\\u0300-\\u036f",reComboHalfMarksRange="\\ufe20-\\ufe2f",rsComboSymbolsRange="\\u20d0-\\u20ff",rsComboRange=rsComboMarksRange+reComboHalfMarksRange+rsComboSymbolsRange,rsDingbatRange="\\u2700-\\u27bf",rsLowerRange="a-z\\xdf-\\xf6\\xf8-\\xff",rsMathOpRange="\\xac\\xb1\\xd7\\xf7",rsNonCharRange="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",rsPunctuationRange="\\u2000-\\u206f",rsSpaceRange=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",rsUpperRange="A-Z\\xc0-\\xd6\\xd8-\\xde",rsVarRange="\\ufe0e\\ufe0f",rsBreakRange=rsMathOpRange+rsNonCharRange+rsPunctuationRange+rsSpaceRange,rsApos="['’]",rsAstral="["+rsAstralRange+"]",rsBreak="["+rsBreakRange+"]",rsCombo="["+rsComboRange+"]",rsDigits="\\d+",rsDingbat="["+rsDingbatRange+"]",rsLower="["+rsLowerRange+"]",rsMisc="[^"+rsAstralRange+rsBreakRange+rsDigits+rsDingbatRange+rsLowerRange+rsUpperRange+"]",rsFitz="\\ud83c[\\udffb-\\udfff]",rsModifier="(?:"+rsCombo+"|"+rsFitz+")",rsNonAstral="[^"+rsAstralRange+"]",rsRegional="(?:\\ud83c[\\udde6-\\uddff]){2}",rsSurrPair="[\\ud800-\\udbff][\\udc00-\\udfff]",rsUpper="["+rsUpperRange+"]",rsZWJ="\\u200d",rsMiscLower="(?:"+rsLower+"|"+rsMisc+")",rsMiscUpper="(?:"+rsUpper+"|"+rsMisc+")",rsOptContrLower="(?:"+rsApos+"(?:d|ll|m|re|s|t|ve))?",rsOptContrUpper="(?:"+rsApos+"(?:D|LL|M|RE|S|T|VE))?",reOptMod=rsModifier+"?",rsOptVar="["+rsVarRange+"]?",rsOptJoin="(?:"+rsZWJ+"(?:"+[rsNonAstral,rsRegional,rsSurrPair].join("|")+")"+rsOptVar+reOptMod+")*",rsOrdLower="\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)",rsOrdUpper="\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)",rsSeq=rsOptVar+reOptMod+rsOptJoin,rsEmoji="(?:"+[rsDingbat,rsRegional,rsSurrPair].join("|")+")"+rsSeq,rsSymbol="(?:"+[rsNonAstral+rsCombo+"?",rsCombo,rsRegional,rsSurrPair,rsAstral].join("|")+")",reApos=RegExp(rsApos,"g"),reComboMark=RegExp(rsCombo,"g"),reUnicode=RegExp(rsFitz+"(?="+rsFitz+")|"+rsSymbol+rsSeq,"g"),reUnicodeWord=RegExp([rsUpper+"?"+rsLower+"+"+rsOptContrLower+"(?="+[rsBreak,rsUpper,"$"].join("|")+")",rsMiscUpper+"+"+rsOptContrUpper+"(?="+[rsBreak,rsUpper+rsMiscLower,"$"].join("|")+")",rsUpper+"?"+rsMiscLower+"+"+rsOptContrLower,rsUpper+"+"+rsOptContrUpper,rsOrdUpper,rsOrdLower,rsDigits,rsEmoji].join("|"),"g"),reHasUnicode=RegExp("["+rsZWJ+rsAstralRange+rsComboRange+rsVarRange+"]"),reHasUnicodeWord=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,contextProps=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],templateCounter=-1,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[dataViewTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[mapTag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[setTag]=cloneableTags[stringTag]=cloneableTags[symbolTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=!0,cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[weakMapTag]=!1;var deburredLetters={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'"},htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'"},stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},freeParseFloat=parseFloat,freeParseInt=parseInt,freeGlobal="object"==typeof global&&global&&global.Object===Object&&global,freeSelf="object"==typeof self&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==typeof exports&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==typeof module&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch(e){}}(),nodeIsArrayBuffer=nodeUtil&&nodeUtil.isArrayBuffer,nodeIsDate=nodeUtil&&nodeUtil.isDate,nodeIsMap=nodeUtil&&nodeUtil.isMap,nodeIsRegExp=nodeUtil&&nodeUtil.isRegExp,nodeIsSet=nodeUtil&&nodeUtil.isSet,nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,asciiSize=baseProperty("length"),deburrLetter=basePropertyOf(deburredLetters),escapeHtmlChar=basePropertyOf(htmlEscapes),unescapeHtmlChar=basePropertyOf(htmlUnescapes),runInContext=function runInContext(context){function lodash(value){if(isObjectLike(value)&&!isArray(value)&&!(value instanceof LazyWrapper)){if(value instanceof LodashWrapper)return value;if(hasOwnProperty.call(value,"__wrapped__"))return wrapperClone(value)}return new LodashWrapper(value)}function baseLodash(){}function LodashWrapper(value,chainAll){this.__wrapped__=value,this.__actions__=[],this.__chain__=!!chainAll,this.__index__=0,this.__values__=undefined}function LazyWrapper(value){this.__wrapped__=value,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=MAX_ARRAY_LENGTH,this.__views__=[]}function lazyClone(){var result=new LazyWrapper(this.__wrapped__);return result.__actions__=copyArray(this.__actions__),result.__dir__=this.__dir__,result.__filtered__=this.__filtered__,result.__iteratees__=copyArray(this.__iteratees__),result.__takeCount__=this.__takeCount__,result.__views__=copyArray(this.__views__),result}function lazyReverse(){if(this.__filtered__){var result=new LazyWrapper(this);result.__dir__=-1,result.__filtered__=!0}else result=this.clone(),result.__dir__*=-1;return result}function lazyValue(){var array=this.__wrapped__.value(),dir=this.__dir__,isArr=isArray(array),isRight=dir<0,arrLength=isArr?array.length:0,view=getView(0,arrLength,this.__views__),start=view.start,end=view.end,length=end-start,index=isRight?end:start-1,iteratees=this.__iteratees__,iterLength=iteratees.length,resIndex=0,takeCount=nativeMin(length,this.__takeCount__);if(!isArr||arrLength-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}function MapCache(entries){var index=-1,length=null==entries?0:entries.length;for(this.clear();++index=lower?number:lower)),number}function baseClone(value,bitmask,customizer,key,object,stack){var result,isDeep=bitmask&CLONE_DEEP_FLAG,isFlat=bitmask&CLONE_FLAT_FLAG,isFull=bitmask&CLONE_SYMBOLS_FLAG;if(customizer&&(result=object?customizer(value,key,object,stack):customizer(value)),result!==undefined)return result;if(!isObject(value))return value;var isArr=isArray(value);if(isArr){if(result=initCloneArray(value),!isDeep)return copyArray(value,result)}else{var tag=getTag(value),isFunc=tag==funcTag||tag==genTag;if(isBuffer(value))return cloneBuffer(value,isDeep);if(tag==objectTag||tag==argsTag||isFunc&&!object){if(result=isFlat||isFunc?{}:initCloneObject(value),!isDeep)return isFlat?copySymbolsIn(value,baseAssignIn(result,value)):copySymbols(value,baseAssign(result,value))}else{if(!cloneableTags[tag])return object?value:{};result=initCloneByTag(value,tag,baseClone,isDeep)}}stack||(stack=new Stack);var stacked=stack.get(value);if(stacked)return stacked;stack.set(value,result);var keysFunc=isFull?isFlat?getAllKeysIn:getAllKeys:isFlat?keysIn:keys,props=isArr?undefined:keysFunc(value);return arrayEach(props||value,function(subValue,key){props&&(key=subValue,subValue=value[key]),assignValue(result,key,baseClone(subValue,bitmask,customizer,key,value,stack))}),result}function baseConforms(source){var props=keys(source);return function(object){return baseConformsTo(object,source,props)}}function baseConformsTo(object,source,props){var length=props.length;if(null==object)return!length;for(object=Object(object);length--;){var key=props[length],predicate=source[key],value=object[key];if(value===undefined&&!(key in object)||!predicate(value))return!1}return!0}function baseDelay(func,wait,args){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return setTimeout(function(){func.apply(undefined,args)},wait)}function baseDifference(array,values,iteratee,comparator){var index=-1,includes=arrayIncludes,isCommon=!0,length=array.length,result=[],valuesLength=values.length;if(!length)return result;iteratee&&(values=arrayMap(values,baseUnary(iteratee))),comparator?(includes=arrayIncludesWith,isCommon=!1):values.length>=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++indexlength?0:length+start),end=end===undefined||end>length?length:toInteger(end),end<0&&(end+=length),end=start>end?0:toLength(end);start0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return object&&baseForRight(object,iteratee,keys)}function baseFunctions(object,props){return arrayFilter(props,function(key){return isFunction(object[key])})}function baseGet(object,path){path=castPath(path,object);for(var index=0,length=path.length;null!=object&&indexother}function baseHas(object,key){return null!=object&&hasOwnProperty.call(object,key)}function baseHasIn(object,key){return null!=object&&key in Object(object)}function baseInRange(number,start,end){return number>=nativeMin(start,end)&&number=120&&array.length>=120)?new SetCache(othIndex&&array):undefined}array=arrays[0];var index=-1,seen=caches[0];outer:for(;++index-1;)seen!==array&&splice.call(seen,fromIndex,1),splice.call(array,fromIndex,1);return array}function basePullAt(array,indexes){for(var length=array?indexes.length:0,lastIndex=length-1;length--;){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;isIndex(index)?splice.call(array,index,1):baseUnset(array,index)}}return array}function baseRandom(lower,upper){return lower+nativeFloor(nativeRandom()*(upper-lower+1))}function baseRange(start,end,step,fromRight){for(var index=-1,length=nativeMax(nativeCeil((end-start)/(step||1)),0),result=Array(length);length--;)result[fromRight?length:++index]=start,start+=step;return result}function baseRepeat(string,n){var result="";if(!string||n<1||n>MAX_SAFE_INTEGER)return result;do n%2&&(result+=string),n=nativeFloor(n/2),n&&(string+=string);while(n);return result}function baseRest(func,start){return setToString(overRest(func,start,identity),func+"")}function baseSample(collection){return arraySample(values(collection))}function baseSampleSize(collection,n){var array=values(collection);return shuffleSelf(array,baseClamp(n,0,array.length))}function baseSet(object,path,value,customizer){if(!isObject(object))return object;path=castPath(path,object);for(var index=-1,length=path.length,lastIndex=length-1,nested=object;null!=nested&&++indexlength?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index>>1,computed=array[mid];null!==computed&&!isSymbol(computed)&&(retHighest?computed<=value:computed=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index=length?array:baseSlice(array,start,end)}function cloneBuffer(buffer,isDeep){if(isDeep)return buffer.slice();var length=buffer.length,result=allocUnsafe?allocUnsafe(length):new buffer.constructor(length);return buffer.copy(result),result}function cloneArrayBuffer(arrayBuffer){var result=new arrayBuffer.constructor(arrayBuffer.byteLength);return new Uint8Array(result).set(new Uint8Array(arrayBuffer)),result}function cloneDataView(dataView,isDeep){var buffer=isDeep?cloneArrayBuffer(dataView.buffer):dataView.buffer;return new dataView.constructor(buffer,dataView.byteOffset,dataView.byteLength)}function cloneMap(map,isDeep,cloneFunc){var array=isDeep?cloneFunc(mapToArray(map),CLONE_DEEP_FLAG):mapToArray(map);return arrayReduce(array,addMapEntry,new map.constructor)}function cloneRegExp(regexp){var result=new regexp.constructor(regexp.source,reFlags.exec(regexp));return result.lastIndex=regexp.lastIndex,result}function cloneSet(set,isDeep,cloneFunc){var array=isDeep?cloneFunc(setToArray(set),CLONE_DEEP_FLAG):setToArray(set);return arrayReduce(array,addSetEntry,new set.constructor)}function cloneSymbol(symbol){return symbolValueOf?Object(symbolValueOf.call(symbol)):{}}function cloneTypedArray(typedArray,isDeep){var buffer=isDeep?cloneArrayBuffer(typedArray.buffer):typedArray.buffer;return new typedArray.constructor(buffer,typedArray.byteOffset,typedArray.length)}function compareAscending(value,other){if(value!==other){var valIsDefined=value!==undefined,valIsNull=null===value,valIsReflexive=value===value,valIsSymbol=isSymbol(value),othIsDefined=other!==undefined,othIsNull=null===other,othIsReflexive=other===other,othIsSymbol=isSymbol(other);if(!othIsNull&&!othIsSymbol&&!valIsSymbol&&value>other||valIsSymbol&&othIsDefined&&othIsReflexive&&!othIsNull&&!othIsSymbol||valIsNull&&othIsDefined&&othIsReflexive||!valIsDefined&&othIsReflexive||!valIsReflexive)return 1;if(!valIsNull&&!valIsSymbol&&!othIsSymbol&&value=ordersLength)return result;var order=orders[index];return result*("desc"==order?-1:1)}}return object.index-other.index}function composeArgs(args,partials,holders,isCurried){for(var argsIndex=-1,argsLength=args.length,holdersLength=holders.length,leftIndex=-1,leftLength=partials.length,rangeLength=nativeMax(argsLength-holdersLength,0),result=Array(leftLength+rangeLength),isUncurried=!isCurried;++leftIndex1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;for(customizer=assigner.length>3&&"function"==typeof customizer?(length--,customizer):undefined,guard&&isIterateeCall(sources[0],sources[1],guard)&&(customizer=length<3?undefined:customizer,length=1),object=Object(object);++index-1?iterable[iteratee?collection[index]:index]:undefined}}function createFlow(fromRight){return flatRest(function(funcs){var length=funcs.length,index=length,prereq=LodashWrapper.prototype.thru;for(fromRight&&funcs.reverse();index--;){var func=funcs[index];if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);if(prereq&&!wrapper&&"wrapper"==getFuncName(func))var wrapper=new LodashWrapper([],!0)}for(index=wrapper?index:length;++index=LARGE_ARRAY_SIZE)return wrapper.plant(value).value();for(var index=0,result=length?funcs[index].apply(this,args):value;++index1&&args.reverse(),isAry&&aryarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:undefined;for(stack.set(array,other),stack.set(other,array);++index1?"& ":"")+details[lastIndex],details=details.join(length>2?", ":" "),source.replace(reWrapComment,"{\n/* [wrapped with "+details+"] */\n")}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function isIndex(value,length){return length=null==length?MAX_SAFE_INTEGER:length,!!length&&("number"==typeof value||reIsUint.test(value))&&value>-1&&value%1==0&&value0){if(++count>=HOT_COUNT)return arguments[0]}else count=0;return func.apply(undefined,arguments)}}function shuffleSelf(array,size){var index=-1,length=array.length,lastIndex=length-1;for(size=size===undefined?length:size;++index=this.__values__.length,value=done?undefined:this.__values__[this.__index__++];return{done:done,value:value}}function wrapperToIterator(){return this}function wrapperPlant(value){for(var result,parent=this;parent instanceof baseLodash;){var clone=wrapperClone(parent);clone.__index__=0,clone.__values__=undefined,result?previous.__wrapped__=clone:result=clone;var previous=clone;parent=parent.__wrapped__}return previous.__wrapped__=value,result}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){var wrapped=value;return this.__actions__.length&&(wrapped=new LazyWrapper(this)),wrapped=wrapped.reverse(),wrapped.__actions__.push({func:thru,args:[reverse],thisArg:undefined}),new LodashWrapper(wrapped,this.__chain__)}return this.thru(reverse)}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function every(collection,predicate,guard){var func=isArray(collection)?arrayEvery:baseEvery;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function filter(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter;return func(collection,getIteratee(predicate,3))}function flatMap(collection,iteratee){return baseFlatten(map(collection,iteratee),1)}function flatMapDeep(collection,iteratee){return baseFlatten(map(collection,iteratee),INFINITY)}function flatMapDepth(collection,iteratee,depth){return depth=depth===undefined?1:toInteger(depth),baseFlatten(map(collection,iteratee),depth)}function forEach(collection,iteratee){var func=isArray(collection)?arrayEach:baseEach;return func(collection,getIteratee(iteratee,3))}function forEachRight(collection,iteratee){var func=isArray(collection)?arrayEachRight:baseEachRight;return func(collection,getIteratee(iteratee,3))}function includes(collection,value,fromIndex,guard){collection=isArrayLike(collection)?collection:values(collection),fromIndex=fromIndex&&!guard?toInteger(fromIndex):0;var length=collection.length;return fromIndex<0&&(fromIndex=nativeMax(length+fromIndex,0)),isString(collection)?fromIndex<=length&&collection.indexOf(value,fromIndex)>-1:!!length&&baseIndexOf(collection,value,fromIndex)>-1}function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,getIteratee(iteratee,3))}function orderBy(collection,iteratees,orders,guard){return null==collection?[]:(isArray(iteratees)||(iteratees=null==iteratees?[]:[iteratees]),orders=guard?undefined:orders,isArray(orders)||(orders=null==orders?[]:[orders]),baseOrderBy(collection,iteratees,orders))}function reduce(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduce:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEach)}function reduceRight(collection,iteratee,accumulator){var func=isArray(collection)?arrayReduceRight:baseReduce,initAccum=arguments.length<3;return func(collection,getIteratee(iteratee,4),accumulator,initAccum,baseEachRight)}function reject(collection,predicate){var func=isArray(collection)?arrayFilter:baseFilter; +return func(collection,negate(getIteratee(predicate,3)))}function sample(collection){var func=isArray(collection)?arraySample:baseSample;return func(collection)}function sampleSize(collection,n,guard){n=(guard?isIterateeCall(collection,n,guard):n===undefined)?1:toInteger(n);var func=isArray(collection)?arraySampleSize:baseSampleSize;return func(collection,n)}function shuffle(collection){var func=isArray(collection)?arrayShuffle:baseShuffle;return func(collection)}function size(collection){if(null==collection)return 0;if(isArrayLike(collection))return isString(collection)?stringSize(collection):collection.length;var tag=getTag(collection);return tag==mapTag||tag==setTag?collection.size:baseKeys(collection).length}function some(collection,predicate,guard){var func=isArray(collection)?arraySome:baseSome;return guard&&isIterateeCall(collection,predicate,guard)&&(predicate=undefined),func(collection,getIteratee(predicate,3))}function after(n,func){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){if(--n<1)return func.apply(this,arguments)}}function ary(func,n,guard){return n=guard?undefined:n,n=func&&null==n?func.length:n,createWrap(func,WRAP_ARY_FLAG,undefined,undefined,undefined,undefined,n)}function before(n,func){var result;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return n=toInteger(n),function(){return--n>0&&(result=func.apply(this,arguments)),n<=1&&(func=undefined),result}}function curry(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curry.placeholder,result}function curryRight(func,arity,guard){arity=guard?undefined:arity;var result=createWrap(func,WRAP_CURRY_RIGHT_FLAG,undefined,undefined,undefined,undefined,undefined,arity);return result.placeholder=curryRight.placeholder,result}function debounce(func,wait,options){function invokeFunc(time){var args=lastArgs,thisArg=lastThis;return lastArgs=lastThis=undefined,lastInvokeTime=time,result=func.apply(thisArg,args)}function leadingEdge(time){return lastInvokeTime=time,timerId=setTimeout(timerExpired,wait),leading?invokeFunc(time):result}function remainingWait(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime,result=wait-timeSinceLastCall;return maxing?nativeMin(result,maxWait-timeSinceLastInvoke):result}function shouldInvoke(time){var timeSinceLastCall=time-lastCallTime,timeSinceLastInvoke=time-lastInvokeTime;return lastCallTime===undefined||timeSinceLastCall>=wait||timeSinceLastCall<0||maxing&&timeSinceLastInvoke>=maxWait}function timerExpired(){var time=now();return shouldInvoke(time)?trailingEdge(time):void(timerId=setTimeout(timerExpired,remainingWait(time)))}function trailingEdge(time){return timerId=undefined,trailing&&lastArgs?invokeFunc(time):(lastArgs=lastThis=undefined,result)}function cancel(){timerId!==undefined&&clearTimeout(timerId),lastInvokeTime=0,lastArgs=lastCallTime=lastThis=timerId=undefined}function flush(){return timerId===undefined?result:trailingEdge(now())}function debounced(){var time=now(),isInvoking=shouldInvoke(time);if(lastArgs=arguments,lastThis=this,lastCallTime=time,isInvoking){if(timerId===undefined)return leadingEdge(lastCallTime);if(maxing)return timerId=setTimeout(timerExpired,wait),invokeFunc(lastCallTime)}return timerId===undefined&&(timerId=setTimeout(timerExpired,wait)),result}var lastArgs,lastThis,maxWait,result,timerId,lastCallTime,lastInvokeTime=0,leading=!1,maxing=!1,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return wait=toNumber(wait)||0,isObject(options)&&(leading=!!options.leading,maxing="maxWait"in options,maxWait=maxing?nativeMax(toNumber(options.maxWait)||0,wait):maxWait,trailing="trailing"in options?!!options.trailing:trailing),debounced.cancel=cancel,debounced.flush=flush,debounced}function flip(func){return createWrap(func,WRAP_FLIP_FLAG)}function memoize(func,resolver){if("function"!=typeof func||null!=resolver&&"function"!=typeof resolver)throw new TypeError(FUNC_ERROR_TEXT);var memoized=function(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key))return cache.get(key);var result=func.apply(this,args);return memoized.cache=cache.set(key,result)||cache,result};return memoized.cache=new(memoize.Cache||MapCache),memoized}function negate(predicate){if("function"!=typeof predicate)throw new TypeError(FUNC_ERROR_TEXT);return function(){var args=arguments;switch(args.length){case 0:return!predicate.call(this);case 1:return!predicate.call(this,args[0]);case 2:return!predicate.call(this,args[0],args[1]);case 3:return!predicate.call(this,args[0],args[1],args[2])}return!predicate.apply(this,args)}}function once(func){return before(2,func)}function rest(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?start:toInteger(start),baseRest(func,start)}function spread(func,start){if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return start=start===undefined?0:nativeMax(toInteger(start),0),baseRest(function(args){var array=args[start],otherArgs=castSlice(args,0,start);return array&&arrayPush(otherArgs,array),apply(func,this,otherArgs)})}function throttle(func,wait,options){var leading=!0,trailing=!0;if("function"!=typeof func)throw new TypeError(FUNC_ERROR_TEXT);return isObject(options)&&(leading="leading"in options?!!options.leading:leading,trailing="trailing"in options?!!options.trailing:trailing),debounce(func,wait,{leading:leading,maxWait:wait,trailing:trailing})}function unary(func){return ary(func,1)}function wrap(value,wrapper){return partial(castFunction(wrapper),value)}function castArray(){if(!arguments.length)return[];var value=arguments[0];return isArray(value)?value:[value]}function clone(value){return baseClone(value,CLONE_SYMBOLS_FLAG)}function cloneWith(value,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseClone(value,CLONE_SYMBOLS_FLAG,customizer)}function cloneDeep(value){return baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG)}function cloneDeepWith(value,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseClone(value,CLONE_DEEP_FLAG|CLONE_SYMBOLS_FLAG,customizer)}function conformsTo(object,source){return null==source||baseConformsTo(object,source,keys(source))}function eq(value,other){return value===other||value!==value&&other!==other}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isBoolean(value){return value===!0||value===!1||isObjectLike(value)&&baseGetTag(value)==boolTag}function isElement(value){return isObjectLike(value)&&1===value.nodeType&&!isPlainObject(value)}function isEmpty(value){if(null==value)return!0;if(isArrayLike(value)&&(isArray(value)||"string"==typeof value||"function"==typeof value.splice||isBuffer(value)||isTypedArray(value)||isArguments(value)))return!value.length;var tag=getTag(value);if(tag==mapTag||tag==setTag)return!value.size;if(isPrototype(value))return!baseKeys(value).length;for(var key in value)if(hasOwnProperty.call(value,key))return!1;return!0}function isEqual(value,other){return baseIsEqual(value,other)}function isEqualWith(value,other,customizer){customizer="function"==typeof customizer?customizer:undefined;var result=customizer?customizer(value,other):undefined;return result===undefined?baseIsEqual(value,other,undefined,customizer):!!result}function isError(value){if(!isObjectLike(value))return!1;var tag=baseGetTag(value);return tag==errorTag||tag==domExcTag||"string"==typeof value.message&&"string"==typeof value.name&&!isPlainObject(value)}function isFinite(value){return"number"==typeof value&&nativeIsFinite(value)}function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag}function isInteger(value){return"number"==typeof value&&value==toInteger(value)}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type=typeof value;return null!=value&&("object"==type||"function"==type)}function isObjectLike(value){return null!=value&&"object"==typeof value}function isMatch(object,source){return object===source||baseIsMatch(object,source,getMatchData(source))}function isMatchWith(object,source,customizer){return customizer="function"==typeof customizer?customizer:undefined,baseIsMatch(object,source,getMatchData(source),customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(isMaskable(value))throw new Error(CORE_ERROR_TEXT);return baseIsNative(value)}function isNull(value){return null===value}function isNil(value){return null==value}function isNumber(value){return"number"==typeof value||isObjectLike(value)&&baseGetTag(value)==numberTag}function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag)return!1;var proto=getPrototype(value);if(null===proto)return!0;var Ctor=hasOwnProperty.call(proto,"constructor")&&proto.constructor;return"function"==typeof Ctor&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function isSafeInteger(value){return isInteger(value)&&value>=-MAX_SAFE_INTEGER&&value<=MAX_SAFE_INTEGER}function isString(value){return"string"==typeof value||!isArray(value)&&isObjectLike(value)&&baseGetTag(value)==stringTag}function isSymbol(value){return"symbol"==typeof value||isObjectLike(value)&&baseGetTag(value)==symbolTag}function isUndefined(value){return value===undefined}function isWeakMap(value){return isObjectLike(value)&&getTag(value)==weakMapTag}function isWeakSet(value){return isObjectLike(value)&&baseGetTag(value)==weakSetTag}function toArray(value){if(!value)return[];if(isArrayLike(value))return isString(value)?stringToArray(value):copyArray(value);if(symIterator&&value[symIterator])return iteratorToArray(value[symIterator]());var tag=getTag(value),func=tag==mapTag?mapToArray:tag==setTag?setToArray:values;return func(value)}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toLength(value){return value?baseClamp(toInteger(value),0,MAX_ARRAY_LENGTH):0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toPlainObject(value){return copyObject(value,keysIn(value))}function toSafeInteger(value){return baseClamp(toInteger(value),-MAX_SAFE_INTEGER,MAX_SAFE_INTEGER)}function toString(value){return null==value?"":baseToString(value)}function create(prototype,properties){var result=baseCreate(prototype);return null==properties?result:baseAssign(result,properties)}function findKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwn)}function findLastKey(object,predicate){return baseFindKey(object,getIteratee(predicate,3),baseForOwnRight)}function forIn(object,iteratee){return null==object?object:baseFor(object,getIteratee(iteratee,3),keysIn)}function forInRight(object,iteratee){return null==object?object:baseForRight(object,getIteratee(iteratee,3),keysIn)}function forOwn(object,iteratee){return object&&baseForOwn(object,getIteratee(iteratee,3))}function forOwnRight(object,iteratee){return object&&baseForOwnRight(object,getIteratee(iteratee,3))}function functions(object){return null==object?[]:baseFunctions(object,keys(object))}function functionsIn(object){return null==object?[]:baseFunctions(object,keysIn(object))}function get(object,path,defaultValue){var result=null==object?undefined:baseGet(object,path);return result===undefined?defaultValue:result}function has(object,path){return null!=object&&hasPath(object,path,baseHas)}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,!0):baseKeysIn(object)}function mapKeys(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,iteratee(value,key,object),value)}),result}function mapValues(object,iteratee){var result={};return iteratee=getIteratee(iteratee,3),baseForOwn(object,function(value,key,object){baseAssignValue(result,key,iteratee(value,key,object))}),result}function omitBy(object,predicate){return pickBy(object,negate(getIteratee(predicate)))}function pickBy(object,predicate){if(null==object)return{};var props=arrayMap(getAllKeysIn(object),function(prop){return[prop]});return predicate=getIteratee(predicate),basePickBy(object,props,function(value,path){return predicate(value,path[0])})}function result(object,path,defaultValue){path=castPath(path,object);var index=-1,length=path.length;for(length||(length=1,object=undefined);++indexupper){var temp=lower;lower=upper,upper=temp}if(floating||lower%1||upper%1){var rand=nativeRandom();return nativeMin(lower+rand*(upper-lower+freeParseFloat("1e-"+((rand+"").length-1))),upper)}return baseRandom(lower,upper)}function capitalize(string){return upperFirst(toString(string).toLowerCase())}function deburr(string){return string=toString(string),string&&string.replace(reLatin,deburrLetter).replace(reComboMark,"")}function endsWith(string,target,position){string=toString(string),target=baseToString(target);var length=string.length;position=position===undefined?length:baseClamp(toInteger(position),0,length);var end=position;return position-=target.length,position>=0&&string.slice(position,end)==target}function escape(string){return string=toString(string),string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){return string=toString(string),string&&reHasRegExpChar.test(string)?string.replace(reRegExpChar,"\\$&"):string}function pad(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;if(!length||strLength>=length)return string;var mid=(length-strLength)/2;return createPadding(nativeFloor(mid),chars)+string+createPadding(nativeCeil(mid),chars)}function padEnd(string,length,chars){string=toString(string),length=toInteger(length);var strLength=length?stringSize(string):0;return length&&strLength>>0)?(string=toString(string),string&&("string"==typeof separator||null!=separator&&!isRegExp(separator))&&(separator=baseToString(separator),!separator&&hasUnicode(string))?castSlice(stringToArray(string),0,limit):string.split(separator,limit)):[]}function startsWith(string,target,position){return string=toString(string),position=baseClamp(toInteger(position),0,string.length),target=baseToString(target),string.slice(position,position+target.length)==target}function template(string,options,guard){var settings=lodash.templateSettings;guard&&isIterateeCall(string,options,guard)&&(options=undefined),string=toString(string),options=assignInWith({},options,settings,assignInDefaults);var isEscaping,isEvaluating,imports=assignInWith({},options.imports,settings.imports,assignInDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys),index=0,interpolate=options.interpolate||reNoMatch,source="__p += '",reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g"),sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){return interpolateValue||(interpolateValue=esTemplateValue),source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar),escapeValue&&(isEscaping=!0,source+="' +\n__e("+escapeValue+") +\n'"),evaluateValue&&(isEvaluating=!0,source+="';\n"+evaluateValue+";\n__p += '"),interpolateValue&&(source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"),index=offset+match.length,match}),source+="';\n";var variable=options.variable;variable||(source="with (obj) {\n"+source+"\n}\n"),source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;"),source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});if(result.source=source,isError(result))throw result;return result}function toLower(value){return toString(value).toLowerCase()}function toUpper(value){return toString(value).toUpperCase()}function trim(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrim,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),chrSymbols=stringToArray(chars),start=charsStartIndex(strSymbols,chrSymbols),end=charsEndIndex(strSymbols,chrSymbols)+1;return castSlice(strSymbols,start,end).join("")}function trimEnd(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimEnd,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),end=charsEndIndex(strSymbols,stringToArray(chars))+1;return castSlice(strSymbols,0,end).join("")}function trimStart(string,chars,guard){if(string=toString(string),string&&(guard||chars===undefined))return string.replace(reTrimStart,"");if(!string||!(chars=baseToString(chars)))return string;var strSymbols=stringToArray(string),start=charsStartIndex(strSymbols,stringToArray(chars));return castSlice(strSymbols,start).join("")}function truncate(string,options){var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?toInteger(options.length):length,omission="omission"in options?baseToString(options.omission):omission}string=toString(string);var strLength=string.length;if(hasUnicode(string)){var strSymbols=stringToArray(string);strLength=strSymbols.length}if(length>=strLength)return string;var end=length-stringSize(omission);if(end<1)return omission;var result=strSymbols?castSlice(strSymbols,0,end).join(""):string.slice(0,end);if(separator===undefined)return result+omission;if(strSymbols&&(end+=result.length-end),isRegExp(separator)){if(string.slice(end).search(separator)){var match,substring=result;for(separator.global||(separator=RegExp(separator.source,toString(reFlags.exec(separator))+"g")),separator.lastIndex=0;match=separator.exec(substring);)var newEnd=match.index;result=result.slice(0,newEnd===undefined?end:newEnd)}}else if(string.indexOf(baseToString(separator),end)!=end){var index=result.lastIndexOf(separator);index>-1&&(result=result.slice(0,index))}return result+omission}function unescape(string){return string=toString(string),string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){return string=toString(string),pattern=guard?undefined:pattern,pattern===undefined?hasUnicodeWord(string)?unicodeWords(string):asciiWords(string):string.match(pattern)||[]}function cond(pairs){var length=null==pairs?0:pairs.length,toIteratee=getIteratee();return pairs=length?arrayMap(pairs,function(pair){if("function"!=typeof pair[1])throw new TypeError(FUNC_ERROR_TEXT);return[toIteratee(pair[0]),pair[1]]}):[],baseRest(function(args){for(var index=-1;++indexMAX_SAFE_INTEGER)return[];var index=MAX_ARRAY_LENGTH,length=nativeMin(n,MAX_ARRAY_LENGTH);iteratee=getIteratee(iteratee),n-=MAX_ARRAY_LENGTH;for(var result=baseTimes(length,iteratee);++index1?arrays[length-1]:undefined;return iteratee="function"==typeof iteratee?(arrays.pop(),iteratee):undefined,unzipWith(arrays,iteratee)}),wrapperAt=flatRest(function(paths){var length=paths.length,start=length?paths[0]:0,value=this.__wrapped__,interceptor=function(object){return baseAt(object,paths)};return!(length>1||this.__actions__.length)&&value instanceof LazyWrapper&&isIndex(start)?(value=value.slice(start,+start+(length?1:0)),value.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(value,this.__chain__).thru(function(array){return length&&!array.length&&array.push(undefined),array})):this.thru(interceptor)}),countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:baseAssignValue(result,key,1)}),find=createFind(findIndex),findLast=createFind(findLastIndex),groupBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key].push(value):baseAssignValue(result,key,[value])}),invokeMap=baseRest(function(collection,path,args){var index=-1,isFunc="function"==typeof path,result=isArrayLike(collection)?Array(collection.length):[];return baseEach(collection,function(value){result[++index]=isFunc?apply(path,value,args):baseInvoke(value,path,args)}),result}),keyBy=createAggregator(function(result,value,key){baseAssignValue(result,key,value)}),partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]}),sortBy=baseRest(function(collection,iteratees){if(null==collection)return[];var length=iteratees.length;return length>1&&isIterateeCall(collection,iteratees[0],iteratees[1])?iteratees=[]:length>2&&isIterateeCall(iteratees[0],iteratees[1],iteratees[2])&&(iteratees=[iteratees[0]]),baseOrderBy(collection,baseFlatten(iteratees,1),[])}),now=ctxNow||function(){return root.Date.now()},bind=baseRest(function(func,thisArg,partials){var bitmask=WRAP_BIND_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bind));bitmask|=WRAP_PARTIAL_FLAG}return createWrap(func,bitmask,thisArg,partials,holders)}),bindKey=baseRest(function(object,key,partials){var bitmask=WRAP_BIND_FLAG|WRAP_BIND_KEY_FLAG;if(partials.length){var holders=replaceHolders(partials,getHolder(bindKey));bitmask|=WRAP_PARTIAL_FLAG}return createWrap(key,bitmask,object,partials,holders)}),defer=baseRest(function(func,args){return baseDelay(func,1,args)}),delay=baseRest(function(func,wait,args){return baseDelay(func,toNumber(wait)||0,args)});memoize.Cache=MapCache;var overArgs=castRest(function(func,transforms){transforms=1==transforms.length&&isArray(transforms[0])?arrayMap(transforms[0],baseUnary(getIteratee())):arrayMap(baseFlatten(transforms,1),baseUnary(getIteratee()));var funcsLength=transforms.length;return baseRest(function(args){for(var index=-1,length=nativeMin(args.length,funcsLength);++index=other}),isArguments=baseIsArguments(function(){return arguments}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")},isArray=Array.isArray,isArrayBuffer=nodeIsArrayBuffer?baseUnary(nodeIsArrayBuffer):baseIsArrayBuffer,isBuffer=nativeIsBuffer||stubFalse,isDate=nodeIsDate?baseUnary(nodeIsDate):baseIsDate,isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap,isRegExp=nodeIsRegExp?baseUnary(nodeIsRegExp):baseIsRegExp,isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray,lt=createRelationalOperation(baseLt),lte=createRelationalOperation(function(value,other){return value<=other}),assign=createAssigner(function(object,source){if(isPrototype(source)||isArrayLike(source))return void copyObject(source,keys(source),object);for(var key in source)hasOwnProperty.call(source,key)&&assignValue(object,key,source[key])}),assignIn=createAssigner(function(object,source){copyObject(source,keysIn(source),object)}),assignInWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keysIn(source),object,customizer)}),assignWith=createAssigner(function(object,source,srcIndex,customizer){copyObject(source,keys(source),object,customizer)}),at=flatRest(baseAt),defaults=baseRest(function(args){return args.push(undefined,assignInDefaults),apply(assignInWith,undefined,args)}),defaultsDeep=baseRest(function(args){return args.push(undefined,mergeDefaults),apply(mergeWith,undefined,args)}),invert=createInverter(function(result,value,key){result[value]=key},constant(identity)),invertBy=createInverter(function(result,value,key){hasOwnProperty.call(result,value)?result[value].push(key):result[value]=[key]},getIteratee),invoke=baseRest(baseInvoke),merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex)}),mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer)}),omit=flatRest(function(object,paths){var result={};if(null==object)return result;var isDeep=!1;paths=arrayMap(paths,function(path){return path=castPath(path,object),isDeep||(isDeep=path.length>1),path}),copyObject(object,getAllKeysIn(object),result),isDeep&&(result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG));for(var length=paths.length;length--;)baseUnset(result,paths[length]);return result}),pick=flatRest(function(object,paths){return null==object?{}:basePick(object,paths)}),toPairs=createToPairs(keys),toPairsIn=createToPairs(keysIn),camelCase=createCompounder(function(result,word,index){return word=word.toLowerCase(),result+(index?capitalize(word):word)}),kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()}),lowerCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toLowerCase()}),lowerFirst=createCaseFirst("toLowerCase"),snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()}),startCase=createCompounder(function(result,word,index){return result+(index?" ":"")+upperFirst(word)}),upperCase=createCompounder(function(result,word,index){return result+(index?" ":"")+word.toUpperCase()}),upperFirst=createCaseFirst("toUpperCase"),attempt=baseRest(function(func,args){try{return apply(func,undefined,args)}catch(e){return isError(e)?e:new Error(e)}}),bindAll=flatRest(function(object,methodNames){return arrayEach(methodNames,function(key){key=toKey(key),baseAssignValue(object,key,bind(object[key],object))}),object}),flow=createFlow(),flowRight=createFlow(!0),method=baseRest(function(path,args){return function(object){return baseInvoke(object,path,args)}}),methodOf=baseRest(function(object,args){return function(path){return baseInvoke(object,path,args)}}),over=createOver(arrayMap),overEvery=createOver(arrayEvery),overSome=createOver(arraySome),range=createRange(),rangeRight=createRange(!0),add=createMathOperation(function(augend,addend){return augend+addend},0),ceil=createRound("ceil"),divide=createMathOperation(function(dividend,divisor){return dividend/divisor},1),floor=createRound("floor"),multiply=createMathOperation(function(multiplier,multiplicand){return multiplier*multiplicand},1),round=createRound("round"),subtract=createMathOperation(function(minuend,subtrahend){return minuend-subtrahend},0);return lodash.after=after,lodash.ary=ary,lodash.assign=assign,lodash.assignIn=assignIn,lodash.assignInWith=assignInWith,lodash.assignWith=assignWith,lodash.at=at,lodash.before=before,lodash.bind=bind,lodash.bindAll=bindAll,lodash.bindKey=bindKey,lodash.castArray=castArray,lodash.chain=chain,lodash.chunk=chunk,lodash.compact=compact,lodash.concat=concat,lodash.cond=cond,lodash.conforms=conforms,lodash.constant=constant,lodash.countBy=countBy,lodash.create=create,lodash.curry=curry,lodash.curryRight=curryRight,lodash.debounce=debounce,lodash.defaults=defaults,lodash.defaultsDeep=defaultsDeep,lodash.defer=defer,lodash.delay=delay,lodash.difference=difference,lodash.differenceBy=differenceBy,lodash.differenceWith=differenceWith,lodash.drop=drop,lodash.dropRight=dropRight,lodash.dropRightWhile=dropRightWhile,lodash.dropWhile=dropWhile,lodash.fill=fill,lodash.filter=filter,lodash.flatMap=flatMap,lodash.flatMapDeep=flatMapDeep,lodash.flatMapDepth=flatMapDepth,lodash.flatten=flatten,lodash.flattenDeep=flattenDeep,lodash.flattenDepth=flattenDepth,lodash.flip=flip,lodash.flow=flow,lodash.flowRight=flowRight,lodash.fromPairs=fromPairs,lodash.functions=functions,lodash.functionsIn=functionsIn,lodash.groupBy=groupBy,lodash.initial=initial,lodash.intersection=intersection,lodash.intersectionBy=intersectionBy,lodash.intersectionWith=intersectionWith,lodash.invert=invert,lodash.invertBy=invertBy,lodash.invokeMap=invokeMap,lodash.iteratee=iteratee,lodash.keyBy=keyBy,lodash.keys=keys,lodash.keysIn=keysIn,lodash.map=map,lodash.mapKeys=mapKeys,lodash.mapValues=mapValues,lodash.matches=matches,lodash.matchesProperty=matchesProperty,lodash.memoize=memoize,lodash.merge=merge,lodash.mergeWith=mergeWith,lodash.method=method,lodash.methodOf=methodOf,lodash.mixin=mixin,lodash.negate=negate,lodash.nthArg=nthArg,lodash.omit=omit,lodash.omitBy=omitBy,lodash.once=once,lodash.orderBy=orderBy,lodash.over=over,lodash.overArgs=overArgs,lodash.overEvery=overEvery,lodash.overSome=overSome,lodash.partial=partial,lodash.partialRight=partialRight,lodash.partition=partition,lodash.pick=pick,lodash.pickBy=pickBy,lodash.property=property,lodash.propertyOf=propertyOf,lodash.pull=pull,lodash.pullAll=pullAll,lodash.pullAllBy=pullAllBy,lodash.pullAllWith=pullAllWith,lodash.pullAt=pullAt,lodash.range=range,lodash.rangeRight=rangeRight,lodash.rearg=rearg,lodash.reject=reject,lodash.remove=remove,lodash.rest=rest,lodash.reverse=reverse,lodash.sampleSize=sampleSize,lodash.set=set,lodash.setWith=setWith,lodash.shuffle=shuffle,lodash.slice=slice,lodash.sortBy=sortBy,lodash.sortedUniq=sortedUniq,lodash.sortedUniqBy=sortedUniqBy,lodash.split=split,lodash.spread=spread,lodash.tail=tail,lodash.take=take,lodash.takeRight=takeRight,lodash.takeRightWhile=takeRightWhile,lodash.takeWhile=takeWhile,lodash.tap=tap,lodash.throttle=throttle,lodash.thru=thru,lodash.toArray=toArray,lodash.toPairs=toPairs,lodash.toPairsIn=toPairsIn,lodash.toPath=toPath,lodash.toPlainObject=toPlainObject,lodash.transform=transform,lodash.unary=unary,lodash.union=union,lodash.unionBy=unionBy,lodash.unionWith=unionWith,lodash.uniq=uniq,lodash.uniqBy=uniqBy,lodash.uniqWith=uniqWith,lodash.unset=unset,lodash.unzip=unzip,lodash.unzipWith=unzipWith,lodash.update=update,lodash.updateWith=updateWith,lodash.values=values,lodash.valuesIn=valuesIn,lodash.without=without,lodash.words=words,lodash.wrap=wrap,lodash.xor=xor,lodash.xorBy=xorBy,lodash.xorWith=xorWith,lodash.zip=zip,lodash.zipObject=zipObject,lodash.zipObjectDeep=zipObjectDeep,lodash.zipWith=zipWith,lodash.entries=toPairs,lodash.entriesIn=toPairsIn,lodash.extend=assignIn,lodash.extendWith=assignInWith,mixin(lodash,lodash),lodash.add=add,lodash.attempt=attempt,lodash.camelCase=camelCase,lodash.capitalize=capitalize,lodash.ceil=ceil,lodash.clamp=clamp,lodash.clone=clone,lodash.cloneDeep=cloneDeep,lodash.cloneDeepWith=cloneDeepWith,lodash.cloneWith=cloneWith,lodash.conformsTo=conformsTo,lodash.deburr=deburr,lodash.defaultTo=defaultTo,lodash.divide=divide,lodash.endsWith=endsWith,lodash.eq=eq,lodash.escape=escape,lodash.escapeRegExp=escapeRegExp,lodash.every=every,lodash.find=find,lodash.findIndex=findIndex,lodash.findKey=findKey,lodash.findLast=findLast,lodash.findLastIndex=findLastIndex,lodash.findLastKey=findLastKey,lodash.floor=floor,lodash.forEach=forEach,lodash.forEachRight=forEachRight,lodash.forIn=forIn,lodash.forInRight=forInRight,lodash.forOwn=forOwn,lodash.forOwnRight=forOwnRight,lodash.get=get,lodash.gt=gt,lodash.gte=gte,lodash.has=has,lodash.hasIn=hasIn,lodash.head=head,lodash.identity=identity,lodash.includes=includes,lodash.indexOf=indexOf,lodash.inRange=inRange,lodash.invoke=invoke,lodash.isArguments=isArguments,lodash.isArray=isArray,lodash.isArrayBuffer=isArrayBuffer,lodash.isArrayLike=isArrayLike,lodash.isArrayLikeObject=isArrayLikeObject,lodash.isBoolean=isBoolean,lodash.isBuffer=isBuffer,lodash.isDate=isDate,lodash.isElement=isElement,lodash.isEmpty=isEmpty,lodash.isEqual=isEqual,lodash.isEqualWith=isEqualWith,lodash.isError=isError,lodash.isFinite=isFinite,lodash.isFunction=isFunction,lodash.isInteger=isInteger,lodash.isLength=isLength,lodash.isMap=isMap,lodash.isMatch=isMatch,lodash.isMatchWith=isMatchWith,lodash.isNaN=isNaN,lodash.isNative=isNative,lodash.isNil=isNil,lodash.isNull=isNull,lodash.isNumber=isNumber,lodash.isObject=isObject,lodash.isObjectLike=isObjectLike,lodash.isPlainObject=isPlainObject,lodash.isRegExp=isRegExp,lodash.isSafeInteger=isSafeInteger,lodash.isSet=isSet,lodash.isString=isString,lodash.isSymbol=isSymbol,lodash.isTypedArray=isTypedArray,lodash.isUndefined=isUndefined,lodash.isWeakMap=isWeakMap,lodash.isWeakSet=isWeakSet,lodash.join=join,lodash.kebabCase=kebabCase,lodash.last=last,lodash.lastIndexOf=lastIndexOf,lodash.lowerCase=lowerCase,lodash.lowerFirst=lowerFirst,lodash.lt=lt,lodash.lte=lte,lodash.max=max,lodash.maxBy=maxBy,lodash.mean=mean,lodash.meanBy=meanBy,lodash.min=min,lodash.minBy=minBy,lodash.stubArray=stubArray,lodash.stubFalse=stubFalse,lodash.stubObject=stubObject,lodash.stubString=stubString,lodash.stubTrue=stubTrue,lodash.multiply=multiply,lodash.nth=nth,lodash.noConflict=noConflict,lodash.noop=noop,lodash.now=now,lodash.pad=pad,lodash.padEnd=padEnd,lodash.padStart=padStart,lodash.parseInt=parseInt,lodash.random=random,lodash.reduce=reduce,lodash.reduceRight=reduceRight,lodash.repeat=repeat,lodash.replace=replace,lodash.result=result,lodash.round=round,lodash.runInContext=runInContext,lodash.sample=sample,lodash.size=size,lodash.snakeCase=snakeCase,lodash.some=some,lodash.sortedIndex=sortedIndex,lodash.sortedIndexBy=sortedIndexBy,lodash.sortedIndexOf=sortedIndexOf,lodash.sortedLastIndex=sortedLastIndex,lodash.sortedLastIndexBy=sortedLastIndexBy,lodash.sortedLastIndexOf=sortedLastIndexOf,lodash.startCase=startCase,lodash.startsWith=startsWith,lodash.subtract=subtract,lodash.sum=sum,lodash.sumBy=sumBy,lodash.template=template,lodash.times=times,lodash.toFinite=toFinite,lodash.toInteger=toInteger,lodash.toLength=toLength,lodash.toLower=toLower,lodash.toNumber=toNumber,lodash.toSafeInteger=toSafeInteger,lodash.toString=toString,lodash.toUpper=toUpper,lodash.trim=trim,lodash.trimEnd=trimEnd,lodash.trimStart=trimStart,lodash.truncate=truncate,lodash.unescape=unescape,lodash.uniqueId=uniqueId,lodash.upperCase=upperCase,lodash.upperFirst=upperFirst,lodash.each=forEach,lodash.eachRight=forEachRight,lodash.first=head,mixin(lodash,function(){var source={};return baseForOwn(lodash,function(func,methodName){hasOwnProperty.call(lodash.prototype,methodName)||(source[methodName]=func)}),source}(),{chain:!1}),lodash.VERSION=VERSION,arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash}),arrayEach(["drop","take"],function(methodName,index){LazyWrapper.prototype[methodName]=function(n){var filtered=this.__filtered__;if(filtered&&!index)return new LazyWrapper(this);n=n===undefined?1:nativeMax(toInteger(n),0);var result=this.clone();return filtered?result.__takeCount__=nativeMin(n,result.__takeCount__):result.__views__.push({size:nativeMin(n,MAX_ARRAY_LENGTH),type:methodName+(result.__dir__<0?"Right":"")}),result},LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()}}),arrayEach(["filter","map","takeWhile"],function(methodName,index){var type=index+1,isFilter=type==LAZY_FILTER_FLAG||type==LAZY_WHILE_FLAG;LazyWrapper.prototype[methodName]=function(iteratee){var result=this.clone();return result.__iteratees__.push({iteratee:getIteratee(iteratee,3),type:type}),result.__filtered__=result.__filtered__||isFilter,result}}),arrayEach(["head","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}}),arrayEach(["initial","tail"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this.__filtered__?new LazyWrapper(this):this[dropName](1)}}),LazyWrapper.prototype.compact=function(){return this.filter(identity)},LazyWrapper.prototype.find=function(predicate){return this.filter(predicate).head()},LazyWrapper.prototype.findLast=function(predicate){return this.reverse().find(predicate)},LazyWrapper.prototype.invokeMap=baseRest(function(path,args){return"function"==typeof path?new LazyWrapper(this):this.map(function(value){return baseInvoke(value,path,args)})}),LazyWrapper.prototype.reject=function(predicate){return this.filter(negate(getIteratee(predicate)))},LazyWrapper.prototype.slice=function(start,end){start=toInteger(start);var result=this;return result.__filtered__&&(start>0||end<0)?new LazyWrapper(result):(start<0?result=result.takeRight(-start):start&&(result=result.drop(start)),end!==undefined&&(end=toInteger(end),result=end<0?result.dropRight(-end):result.take(end-start)),result)},LazyWrapper.prototype.takeRightWhile=function(predicate){return this.reverse().takeWhile(predicate).reverse()},LazyWrapper.prototype.toArray=function(){return this.take(MAX_ARRAY_LENGTH)},baseForOwn(LazyWrapper.prototype,function(func,methodName){var checkIteratee=/^(?:filter|find|map|reject)|While$/.test(methodName),isTaker=/^(?:head|last)$/.test(methodName),lodashFunc=lodash[isTaker?"take"+("last"==methodName?"Right":""):methodName],retUnwrapped=isTaker||/^find/.test(methodName);lodashFunc&&(lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=isTaker?[1]:arguments,isLazy=value instanceof LazyWrapper,iteratee=args[0],useLazy=isLazy||isArray(value),interceptor=function(value){var result=lodashFunc.apply(lodash,arrayPush([value],args));return isTaker&&chainAll?result[0]:result};useLazy&&checkIteratee&&"function"==typeof iteratee&&1!=iteratee.length&&(isLazy=useLazy=!1);var chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isUnwrapped=retUnwrapped&&!chainAll,onlyLazy=isLazy&&!isHybrid;if(!retUnwrapped&&useLazy){value=onlyLazy?value:new LazyWrapper(this);var result=func.apply(value,args);return result.__actions__.push({func:thru,args:[interceptor],thisArg:undefined}),new LodashWrapper(result,chainAll)}return isUnwrapped&&onlyLazy?func.apply(this,args):(result=this.thru(interceptor),isUnwrapped?isTaker?result.value()[0]:result.value():result)})}),arrayEach(["pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){var value=this.value();return func.apply(isArray(value)?value:[],args)}return this[chainName](function(value){return func.apply(isArray(value)?value:[],args)})}}),baseForOwn(LazyWrapper.prototype,function(func,methodName){var lodashFunc=lodash[methodName];if(lodashFunc){var key=lodashFunc.name+"",names=realNames[key]||(realNames[key]=[]);names.push({name:methodName,func:lodashFunc})}}),realNames[createHybrid(undefined,WRAP_BIND_KEY_FLAG).name]=[{name:"wrapper",func:undefined}],LazyWrapper.prototype.clone=lazyClone,LazyWrapper.prototype.reverse=lazyReverse,LazyWrapper.prototype.value=lazyValue,lodash.prototype.at=wrapperAt,lodash.prototype.chain=wrapperChain,lodash.prototype.commit=wrapperCommit,lodash.prototype.next=wrapperNext,lodash.prototype.plant=wrapperPlant,lodash.prototype.reverse=wrapperReverse,lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue,lodash.prototype.first=lodash.prototype.head,symIterator&&(lodash.prototype[symIterator]=wrapperToIterator),lodash},_=runInContext();root._=_,__WEBPACK_AMD_DEFINE_RESULT__=function(){return _}.call(exports,__webpack_require__,exports,module),!(__WEBPACK_AMD_DEFINE_RESULT__!==undefined&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}).call(this)}).call(exports,__webpack_require__(8),__webpack_require__(16)(module))},function(module,exports){function stubFalse(){return!1}module.exports=stubFalse},function(module,exports,__webpack_require__){function priv(obj,key,val){var sym;return symbols[key]?sym=symbols[key]:(sym=makeSymbol(key),symbols[key]=sym),2===arguments.length?obj[sym]:(obj[sym]=val,val)}function naiveLength(){return 1}function LRUCache(options){if(!(this instanceof LRUCache))return new LRUCache(options);"number"==typeof options&&(options={max:options}),options||(options={});var max=priv(this,"max",options.max);(!max||"number"!=typeof max||max<=0)&&priv(this,"max",1/0);var lc=options.length||naiveLength;"function"!=typeof lc&&(lc=naiveLength),priv(this,"lengthCalculator",lc),priv(this,"allowStale",options.stale||!1),priv(this,"maxAge",options.maxAge||0),priv(this,"dispose",options.dispose),this.reset()}function forEachStep(self,fn,node,thisp){var hit=node.value;isStale(self,hit)&&(del(self,node),priv(self,"allowStale")||(hit=void 0)),hit&&fn.call(thisp,hit.value,hit.key,self)}function get(self,key,doUse){var node=priv(self,"cache").get(key);if(node){var hit=node.value;isStale(self,hit)?(del(self,node),priv(self,"allowStale")||(hit=void 0)):doUse&&priv(self,"lruList").unshiftNode(node),hit&&(hit=hit.value)}return hit}function isStale(self,hit){if(!hit||!hit.maxAge&&!priv(self,"maxAge"))return!1;var stale=!1,diff=Date.now()-hit.now;return stale=hit.maxAge?diff>hit.maxAge:priv(self,"maxAge")&&diff>priv(self,"maxAge")}function trim(self){if(priv(self,"length")>priv(self,"max"))for(var walker=priv(self,"lruList").tail;priv(self,"length")>priv(self,"max")&&null!==walker;){var prev=walker.prev;del(self,walker),walker=prev}}function del(self,node){if(node){var hit=node.value;priv(self,"dispose")&&priv(self,"dispose").call(this,hit.key,hit.value),priv(self,"length",priv(self,"length")-hit.length),priv(self,"cache").delete(hit.key),priv(self,"lruList").removeNode(node)}}function Entry(key,value,length,now,maxAge){this.key=key,this.value=value,this.length=length,this.now=now,this.maxAge=maxAge||0}module.exports=LRUCache;var makeSymbol,Map=__webpack_require__(261),util=__webpack_require__(12),Yallist=__webpack_require__(312),symbols={},hasSymbol="function"==typeof Symbol;makeSymbol=hasSymbol?function(key){return Symbol.for(key)}:function(key){return"_"+key},Object.defineProperty(LRUCache.prototype,"max",{set:function(mL){(!mL||"number"!=typeof mL||mL<=0)&&(mL=1/0),priv(this,"max",mL),trim(this)},get:function(){return priv(this,"max")},enumerable:!0}),Object.defineProperty(LRUCache.prototype,"allowStale",{set:function(allowStale){priv(this,"allowStale",!!allowStale)},get:function(){return priv(this,"allowStale")},enumerable:!0}),Object.defineProperty(LRUCache.prototype,"maxAge",{set:function(mA){(!mA||"number"!=typeof mA||mA<0)&&(mA=0),priv(this,"maxAge",mA),trim(this)},get:function(){return priv(this,"maxAge")},enumerable:!0}),Object.defineProperty(LRUCache.prototype,"lengthCalculator",{set:function(lC){"function"!=typeof lC&&(lC=naiveLength),lC!==priv(this,"lengthCalculator")&&(priv(this,"lengthCalculator",lC),priv(this,"length",0),priv(this,"lruList").forEach(function(hit){hit.length=priv(this,"lengthCalculator").call(this,hit.value,hit.key),priv(this,"length",priv(this,"length")+hit.length)},this)),trim(this)},get:function(){return priv(this,"lengthCalculator")},enumerable:!0}),Object.defineProperty(LRUCache.prototype,"length",{get:function(){return priv(this,"length")},enumerable:!0}),Object.defineProperty(LRUCache.prototype,"itemCount",{get:function(){return priv(this,"lruList").length},enumerable:!0}),LRUCache.prototype.rforEach=function(fn,thisp){thisp=thisp||this;for(var walker=priv(this,"lruList").tail;null!==walker;){var prev=walker.prev;forEachStep(this,fn,walker,thisp),walker=prev}},LRUCache.prototype.forEach=function(fn,thisp){thisp=thisp||this;for(var walker=priv(this,"lruList").head;null!==walker;){var next=walker.next;forEachStep(this,fn,walker,thisp),walker=next}},LRUCache.prototype.keys=function(){return priv(this,"lruList").toArray().map(function(k){return k.key},this)},LRUCache.prototype.values=function(){return priv(this,"lruList").toArray().map(function(k){return k.value},this)},LRUCache.prototype.reset=function(){priv(this,"dispose")&&priv(this,"lruList")&&priv(this,"lruList").length&&priv(this,"lruList").forEach(function(hit){priv(this,"dispose").call(this,hit.key,hit.value)},this),priv(this,"cache",new Map),priv(this,"lruList",new Yallist),priv(this,"length",0)},LRUCache.prototype.dump=function(){return priv(this,"lruList").map(function(hit){if(!isStale(this,hit))return{k:hit.key,v:hit.value,e:hit.now+(hit.maxAge||0)}},this).toArray().filter(function(h){return h})},LRUCache.prototype.dumpLru=function(){return priv(this,"lruList")},LRUCache.prototype.inspect=function(n,opts){var str="LRUCache {",extras=!1,as=priv(this,"allowStale");as&&(str+="\n allowStale: true",extras=!0);var max=priv(this,"max");max&&max!==1/0&&(extras&&(str+=","),str+="\n max: "+util.inspect(max,opts),extras=!0);var maxAge=priv(this,"maxAge");maxAge&&(extras&&(str+=","),str+="\n maxAge: "+util.inspect(maxAge,opts),extras=!0);var lc=priv(this,"lengthCalculator");lc&&lc!==naiveLength&&(extras&&(str+=","),str+="\n length: "+util.inspect(priv(this,"length"),opts),extras=!0);var didFirst=!1;return priv(this,"lruList").forEach(function(item){didFirst?str+=",\n ":(extras&&(str+=",\n"),didFirst=!0,str+="\n ");var key=util.inspect(item.key).split("\n").join("\n "),val={value:item.value};item.maxAge!==maxAge&&(val.maxAge=item.maxAge),lc!==naiveLength&&(val.length=item.length),isStale(this,item)&&(val.stale=!0),val=util.inspect(val,opts).split("\n").join("\n "),str+=key+" => "+val}),(didFirst||extras)&&(str+="\n"),str+="}"},LRUCache.prototype.set=function(key,value,maxAge){maxAge=maxAge||priv(this,"maxAge");var now=maxAge?Date.now():0,len=priv(this,"lengthCalculator").call(this,value,key);if(priv(this,"cache").has(key)){if(len>priv(this,"max"))return del(this,priv(this,"cache").get(key)),!1;var node=priv(this,"cache").get(key),item=node.value;return priv(this,"dispose")&&priv(this,"dispose").call(this,key,item.value),item.now=now,item.maxAge=maxAge,item.value=value,priv(this,"length",priv(this,"length")+(len-item.length)),item.length=len,this.get(key),trim(this),!0}var hit=new Entry(key,value,len,now,maxAge);return hit.length>priv(this,"max")?(priv(this,"dispose")&&priv(this,"dispose").call(this,key,value),!1):(priv(this,"length",priv(this,"length")+hit.length),priv(this,"lruList").unshift(hit),priv(this,"cache").set(key,priv(this,"lruList").head),trim(this),!0)},LRUCache.prototype.has=function(key){if(!priv(this,"cache").has(key))return!1;var hit=priv(this,"cache").get(key).value;return!isStale(this,hit)},LRUCache.prototype.get=function(key){return get(this,key,!0)},LRUCache.prototype.peek=function(key){return get(this,key,!1)},LRUCache.prototype.pop=function(){var node=priv(this,"lruList").tail;return node?(del(this,node),node.value):null},LRUCache.prototype.del=function(key){del(this,priv(this,"cache").get(key))},LRUCache.prototype.load=function(arr){this.reset();for(var now=Date.now(),l=arr.length-1;l>=0;l--){var hit=arr[l],expiresAt=hit.e||0;if(0===expiresAt)this.set(hit.k,hit.v);else{var maxAge=expiresAt-now;maxAge>0&&this.set(hit.k,hit.v,maxAge)}}},LRUCache.prototype.prune=function(){var self=this;priv(this,"cache").forEach(function(value,key){get(self,key,!1)})}},function(module,exports){function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}module.exports=assert,assert.equal=function(l,r,msg){if(l!=r)throw new Error(msg||"Assertion failed: "+l+" != "+r); +}},function(module,exports){function read(buf,offset){var b,res=0,offset=offset||0,shift=0,counter=offset,l=buf.length;do{if(counter>=l)throw read.bytes=0,new RangeError("Could not decode varint");b=buf[counter++],res+=shift<28?(b&REST)<=MSB);return read.bytes=counter-offset,res}module.exports=read;var MSB=128,REST=127},function(module,exports){function encode(num,out,offset){out=out||[],offset=offset||0;for(var oldOffset=offset;num>=INT;)out[offset++]=255&num|MSB,num/=128;for(;num&MSBALL;)out[offset++]=255&num|MSB,num>>>=7;return out[offset]=0|num,encode.bytes=offset-oldOffset+1,out}module.exports=encode;var MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31)},function(module,exports){var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63);module.exports=function(value){return value=parts.length)throw ParseError("invalid address: "+str);tuples.push([part,parts[p]])}else tuples.push([part])}return tuples}function stringTuplesToString(tuples){var parts=[];return map(tuples,function(tup){var proto=protoFromTuple(tup);parts.push(proto.name),tup.length>1&&parts.push(tup[1])}),"/"+parts.join("/")}function stringTuplesToTuples(tuples){return map(tuples,function(tup){Array.isArray(tup)||(tup=[tup]);var proto=protoFromTuple(tup);return tup.length>1?[proto.code,convert.toBuffer(proto.code,tup[1])]:[proto.code]})}function tuplesToStringTuples(tuples){return map(tuples,function(tup){var proto=protoFromTuple(tup);return tup.length>1?[proto.code,convert.toString(proto.code,tup[1])]:[proto.code]})}function tuplesToBuffer(tuples){return fromBuffer(Buffer.concat(map(tuples,function(tup){var proto=protoFromTuple(tup),buf=new Buffer(varint.encode(proto.code));return tup.length>1&&(buf=Buffer.concat([buf,tup[1]])),buf})))}function sizeForAddr(p,addr){if(p.size>0)return p.size/8;if(0===p.size)return 0;{const size=varint.decode(addr);return size+varint.decode.bytes}}function bufferToTuples(buf){const tuples=[];let i=0;for(;ibuf.length)throw ParseError("Invalid address buffer: "+buf.toString("hex"));tuples.push([code,addr])}else tuples.push([code]),i+=n}return tuples}function bufferToString(buf){var a=bufferToTuples(buf),b=tuplesToStringTuples(a);return stringTuplesToString(b)}function stringToBuffer(str){str=cleanPath(str);var a=stringToStringTuples(str),b=stringTuplesToTuples(a);return tuplesToBuffer(b)}function fromString(str){return stringToBuffer(str)}function fromBuffer(buf){var err=validateBuffer(buf);if(err)throw err;return new Buffer(buf)}function validateBuffer(buf){try{bufferToTuples(buf)}catch(err){return err}}function isValidBuffer(buf){return void 0===validateBuffer(buf)}function cleanPath(str){return"/"+filter(str.trim().split("/")).join("/")}function ParseError(str){return new Error("Error parsing address: "+str)}function protoFromTuple(tup){var proto=protocols(tup[0]);return proto}var map=__webpack_require__(52),filter=__webpack_require__(203),convert=__webpack_require__(234),protocols=__webpack_require__(57),varint=__webpack_require__(55);module.exports={stringToStringTuples:stringToStringTuples,stringTuplesToString:stringTuplesToString,tuplesToStringTuples:tuplesToStringTuples,stringTuplesToTuples:stringTuplesToTuples,bufferToTuples:bufferToTuples,tuplesToBuffer:tuplesToBuffer,bufferToString:bufferToString,stringToBuffer:stringToBuffer,fromString:fromString,fromBuffer:fromBuffer,validateBuffer:validateBuffer,isValidBuffer:isValidBuffer,cleanPath:cleanPath,ParseError:ParseError,protoFromTuple:protoFromTuple,sizeForAddr:sizeForAddr}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function Convert(proto,a){return a instanceof Buffer?Convert.toString(proto,a):Convert.toBuffer(proto,a)}function port2buf(port){var buf=new Buffer(2);return buf.writeUInt16BE(port,0),buf}function buf2port(buf){return buf.readUInt16BE(0)}function mh2buf(hash){const mh=new Buffer(bs58.decode(hash)),size=new Buffer(varint.encode(mh.length));return Buffer.concat([size,mh])}function buf2mh(buf){const size=varint.decode(buf),address=buf.slice(varint.decode.bytes);if(address.length!==size)throw new Error("inconsistent lengths");return bs58.encode(address)}var ip=__webpack_require__(170),protocols=__webpack_require__(57),bs58=__webpack_require__(10),varint=__webpack_require__(55);module.exports=Convert,Convert.toString=function(proto,buf){switch(proto=protocols(proto),proto.code){case 4:case 41:return ip.toString(buf);case 6:case 17:case 33:case 132:return buf2port(buf);case 421:return buf2mh(buf);default:return buf.toString("hex")}},Convert.toBuffer=function(proto,str){switch(proto=protocols(proto),proto.code){case 4:case 41:return ip.toBuffer(str);case 6:case 17:case 33:case 132:return port2buf(parseInt(str,10));case 421:return mh2buf(str);default:return new Buffer(str,"hex")}}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";var constants=[["base1","1"],["base2","0"],["base8","7"],["base10","9"],["base16","f"],["base58flickr","Z"],["base58btc","z"],["base64","y"],["base64url","Y"]],names=constants.reduce(function(prev,tupple){return prev[tupple[0]]=tupple[1],prev},{}),codes=constants.reduce(function(prev,tupple){return prev[tupple[1]]=tupple[0],prev},{});module.exports={names:names,codes:codes}},function(module,exports,__webpack_require__){"use strict";exports=module.exports=__webpack_require__(237)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function multibase(nameOrCode,buf){if(!buf)throw new Error("requires an encoded buffer");var code=getCode(nameOrCode),codeBuf=new Buffer(code),name=getName(nameOrCode);return validEncode(name,buf),Buffer.concat([codeBuf,buf])}function encode(nameOrCode,buf){var name=getName(nameOrCode),encode=void 0;switch(name){case"base58btc":encode=function(buf){return new Buffer(bs58.encode(buf))};break;default:throw errNotSupported}return multibase(name,encode(buf))}function decode(bufOrString){Buffer.isBuffer(bufOrString)&&(bufOrString=bufOrString.toString());var code=bufOrString.substring(0,1);bufOrString=bufOrString.substring(1,bufOrString.length),"string"==typeof bufOrString&&(bufOrString=new Buffer(bufOrString));var decode=void 0;switch(code){case"z":decode=function(buf){return new Buffer(bs58.decode(buf.toString()))};break;default:throw errNotSupported}return decode(bufOrString)}function isEncoded(bufOrString){Buffer.isBuffer(bufOrString)&&(bufOrString=bufOrString.toString());var code=bufOrString.substring(0,1);try{var name=getName(code);return name}catch(err){return!1}}function validNameOrCode(nameOrCode){var err=new Error("Unsupported encoding");if(!constants.names[nameOrCode]&&!constants.codes[nameOrCode])throw err}function validEncode(name,buf){var decode=void 0;switch(name){case"base58btc":decode=bs58.decode,buf=buf.toString();break;default:throw errNotSupported}decode(buf)}function getCode(nameOrCode){validNameOrCode(nameOrCode);var code=nameOrCode;return constants.names[nameOrCode]&&(code=constants.names[nameOrCode]),code}function getName(nameOrCode){validNameOrCode(nameOrCode);var name=nameOrCode;return constants.codes[nameOrCode]&&(name=constants.codes[nameOrCode]),name}var constants=__webpack_require__(235),bs58=__webpack_require__(10);exports=module.exports=multibase,exports.encode=encode,exports.decode=decode,exports.isEncoded=isEncoded;var errNotSupported=new Error("Unsupported encoding")}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function varintBuf(n){return new Buffer(varint.encode(n))}var varint=__webpack_require__(117);exports=module.exports,exports.raw=varintBuf(0),exports.protobuf=varintBuf(80),exports.cbor=varintBuf(81),exports.rlp=varintBuf(96),exports.multicodec=varintBuf(64),exports.multihash=varintBuf(65),exports.multiaddr=varintBuf(66),exports["dag-pb"]=new Buffer("70","hex"),exports["dag-cbor"]=new Buffer("71","hex"),exports["eth-block"]=new Buffer("90","hex"),exports["eth-tx"]=new Buffer("91","hex")}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){var table=__webpack_require__(238),varint=__webpack_require__(117);exports=module.exports,exports.addPrefix=function(multicodecStrOrCode,data){var pfx=void 0;if(Buffer.isBuffer(multicodecStrOrCode))pfx=multicodecStrOrCode;else{if(!table[multicodecStrOrCode])throw new Error("multicodec not recognized");pfx=table[multicodecStrOrCode]}return Buffer.concat([pfx,data])},exports.rmPrefix=function(data){return varint.decode(data),data.slice(varint.decode.bytes)},exports.getCodec=function(prefixedData){var v=varint.decode(prefixedData),code=new Buffer(v.toString(16),"hex"),codec=void 0;return Object.keys(table).forEach(function(mc){code.equals(table[mc])&&(codec=mc)}),codec}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";exports.names={sha1:17,"sha2-256":18,"sha2-512":19,sha3:20,blake2b:64,blake2s:65},exports.codes={17:"sha1",18:"sha2-256",19:"sha2-512",20:"sha3",64:"blake2b",65:"blake2s"},exports.defaultLengths={17:20,18:32,19:64,20:64,64:64,65:32}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function getWebCrypto(){if("undefined"!=typeof window){if(window.crypto)return window.crypto.subtle||window.crypto.webkitSubtle;if(window.msCrypto)return window.msCrypto.subtle}}function webCryptoHash(type){if(!webCrypto)throw new Error("Please use a browser with webcrypto support");return(data,callback)=>{const res=webCrypto.digest({name:type},data);return"function"!=typeof res.then?(res.onerror=(()=>{callback(`Error hashing data using ${type}`)}),void(res.oncomplete=(e=>{callback(null,e.target.result)}))):void nodeify(res.then(raw=>new Buffer(new Uint8Array(raw))),callback)}}function sha1(buf,callback){webCryptoHash("SHA-1")(buf,callback)}function sha2256(buf,callback){webCryptoHash("SHA-256")(buf,callback)}function sha2512(buf,callback){webCryptoHash("SHA-512")(buf,callback)}function sha3(buf,callback){const d=new SHA3.SHA3Hash,digest=new Buffer(d.update(buf).digest("hex"),"hex");callback(null,digest)}const SHA3=__webpack_require__(154),nodeify=__webpack_require__(29),webCrypto=getWebCrypto();module.exports={sha1:sha1,sha2256:sha2256,sha2512:sha2512,sha3:sha3}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){function Multipart(boundary){return!this instanceof Multipart?new Multipart(boundary):(this.boundary=boundary||Math.random().toString(36).slice(2),Sandwich.call(this,{head:"--"+this.boundary+CRNL,tail:CRNL+"--"+this.boundary+"--",separator:CRNL+"--"+this.boundary+CRNL}),this._add=this.add,void(this.add=this.addPart))}var Sandwich=__webpack_require__(272).SandwichStream,stream=__webpack_require__(5),inherits=__webpack_require__(1),isStream=__webpack_require__(180),CRNL="\r\n";module.exports=Multipart,inherits(Multipart,Sandwich),Multipart.prototype.addPart=function(part){part=part||{};var partStream=new stream.PassThrough;if(part.headers)for(var key in part.headers){var header=part.headers[key];partStream.write(key+": "+header+CRNL)}partStream.write(CRNL),isStream(part.body)?part.body.pipe(partStream):partStream.end(part.body),this._add(partStream)}},function(module,exports){module.exports=Array.isArray||function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}},function(module,exports,__webpack_require__){(function(process){function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||0===hwm?hwm:16384,this.highWaterMark=~~this.highWaterMark,this.buffer=[],this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=!1,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.calledRead=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.objectMode=!!options.objectMode,this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=__webpack_require__(7).StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){return this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(null===chunk||void 0===chunk)state.reading=!1,state.ended||onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):(state.reading=!1,state.buffer.push(chunk)),state.needReadable&&emitReadable(stream),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:null===n||isNaN(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.length>0?emitReadable(stream):endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length0)return;return 0===state.pipesCount?(state.flowing=!1,void(EE.listenerCount(src,"data")>0&&emitDataEvents(src))):void(state.ranOut=!0)}function pipeOnReadable(){this._readableState.ranOut&&(this._readableState.ranOut=!1,flow(this))}function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing)throw new Error("Cannot switch to old mode now.");var paused=startPaused||!1,readable=!1;stream.readable=!0,stream.pipe=Stream.prototype.pipe,stream.on=stream.addListener=Stream.prototype.on,stream.on("readable",function(){readable=!0;for(var c;!paused&&null!==(c=stream.read());)stream.emit("data",c);null===c&&(readable=!1,stream._readableState.needReadable=!0)}),stream.pause=function(){paused=!0,this.emit("pause")},stream.resume=function(){paused=!1,readable?process.nextTick(function(){stream.emit("readable")}):this.read(0),this.emit("resume")},stream.emit("readable")}function fromList(n,state){var ret,list=state.buffer,length=state.length,stringMode=!!state.decoder,objectMode=!!state.objectMode;if(0===list.length)return null;if(0===length)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");!state.endEmitted&&state.calledRead&&(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return ret=null,state.length>0&&state.decoder&&(ret=fromList(n,state),state.length-=ret.length),0===state.length&&endReadable(this),ret;var doRead=state.needReadable;return state.length-n<=state.highWaterMark&&(doRead=!0),(state.ended||state.reading)&&(doRead=!1),doRead&&(state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1),doRead&&!state.reading&&(n=howMuchToRead(nOrig,state)),ret=n>0?fromList(n,state):null,null===ret&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),state.ended&&!state.endEmitted&&0===state.length&&endReadable(this),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){readable===src&&cleanup()}function onend(){dest.end()}function cleanup(){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",cleanup),dest._writableState&&!dest._writableState.needDrain||ondrain()}function onerror(er){unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){dest.removeListener("close",onclose),unpipe()}function unpipe(){src.unpipe(dest)}var src=this,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)}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(this.on("readable",pipeOnReadable),state.flowing=!0,process.nextTick(function(){flow(src)})),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,this.removeListener("readable",pipeOnReadable),state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,this.removeListener("readable",pipeOnReadable),state.flowing=!1;for(var i=0;i=0;i--){var last=parts[i];"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--)}if(allowAboveRoot)for(;up--;up)parts.unshift("..");return parts}function filter(xs,f){if(xs.filter)return xs.filter(f);for(var res=[],i=0;i=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if("string"!=typeof path)throw new TypeError("Arguments to path.resolve must be strings");path&&(resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0))}return resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/"),(resolvedAbsolute?"/":"")+resolvedPath||"."},exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash="/"===substr(path,-1);return path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/"),path||isAbsolute||(path="."),path&&trailingSlash&&(path+="/"),(isAbsolute?"/":"")+path},exports.isAbsolute=function(path){return"/"===path.charAt(0)},exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if("string"!=typeof p)throw new TypeError("Arguments to path.join must be strings");return p}).join("/"))},exports.relative=function(from,to){function trim(arr){for(var start=0;start=0&&""===arr[end];end--);return start>end?[]:arr.slice(start,end-start+1)}from=exports.resolve(from).substr(1),to=exports.resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=Math.min(fromParts.length,toParts.length),samePartsLength=length,i=0;i{addr=ensureMultiaddr(addr);var exists=!1;this.multiaddrs.some((m,i)=>{if(m.equals(addr))return exists=!0,!0}),exists||this.multiaddrs.push(addr)}),this.multiaddr.addSafe=(addr=>{addr=ensureMultiaddr(addr);var check=!1;observedMultiaddrs.some((m,i)=>{m.equals(addr)&&(this.multiaddr.add(addr),observedMultiaddrs.splice(i,1),check=!0)}),check||observedMultiaddrs.push(addr)}),this.multiaddr.rm=(addr=>{addr=ensureMultiaddr(addr),this.multiaddrs.some((m,i)=>{if(m.equals(addr))return this.multiaddrs.splice(i,1),!0})}),this.multiaddr.replace=((existing,fresh)=>{Array.isArray(existing)||(existing=[existing]),Array.isArray(fresh)||(fresh=[fresh]),existing.forEach(m=>{this.multiaddr.rm(m)}),fresh.forEach(m=>{this.multiaddr.add(m)})}),this.distinctMultiaddr=(()=>{var result=uniqBy(this.multiaddrs,function(item){return[item.toOptions().port,item.toOptions().transport].join()});return result})}const Id=__webpack_require__(96),multiaddr=__webpack_require__(56),uniqBy=__webpack_require__(226).uniqBy;exports=module.exports=PeerInfo,PeerInfo.create=((id,callback)=>{return"function"==typeof id?(callback=id,id=null,void Id.create((err,id)=>{return err?callback(err):void callback(null,new PeerInfo(id))})):void callback(null,new PeerInfo(id))})},function(module,exports,__webpack_require__){(function(process){function Promise(fn){function next(skipTimeout){waiting.length?(running=!0,waiting.shift()(skipTimeout||!1)):running=!1}function then(cb,eb){return new Promise(function(resolver){function done(skipTimeout){function timeoutDone(){var val;try{val=callback(value)}catch(ex){return resolver.reject(ex),next()}resolver.fulfill(val),next(!0)}var callback=isFulfilled?cb:eb;"function"==typeof callback?skipTimeout?timeoutDone():nextTick(timeoutDone):isFulfilled?(resolver.fulfill(value),next(skipTimeout)):(resolver.reject(value),next(skipTimeout))}waiting.push(done),isResolved&&!running&&next()})}if(!(this instanceof Promise))return"function"==typeof fn?new Promise(fn):defer();var value,isResolved=!1,isFulfilled=!1,waiting=[],running=!1;this.then=then,function(){function fulfill(val){isResolved||(isPromise(val)?val.then(fulfill,reject):(isResolved=isFulfilled=!0,value=val,next()))}function reject(err){isResolved||(isResolved=!0,isFulfilled=!1,value=err,next())}for(var resolver={fulfill:fulfill,reject:reject},i=0;i"!==tokens[0])throw new Error("Unexpected token in map type: "+tokens[0]);tokens.shift(),field.name=tokens.shift();break;case"repeated":case"required":case"optional":var t=tokens.shift();field.required="required"===t,field.repeated="repeated"===t,field.type=tokens.shift(),field.name=tokens.shift();break;case"[":field.options=onfieldoptions(tokens);break;case";":if(null===field.name)throw new Error("Missing field name");if(null===field.type)throw new Error("Missing type in message field: "+field.name);if(field.tag===-1)throw new Error("Missing tag number in message field: "+field.name);return tokens.shift(),field;default:throw new Error("Unexpected token in message field: "+tokens[0])}throw new Error("No ; found for message field")},onmessagebody=function(tokens){for(var body={enums:[],messages:[],fields:[],extends:[],extensions:null};tokens.length;)switch(tokens[0]){case"map":case"repeated":case"optional":case"required":body.fields.push(onfield(tokens));break;case"enum":body.enums.push(onenum(tokens));break;case"message":body.messages.push(onmessage(tokens));break;case"extensions":body.extensions=onextensions(tokens);break;case"oneof":tokens.shift();var name=tokens.shift();if("{"!==tokens[0])throw new Error("Unexpected token in oneof: "+tokens[0]);for(tokens.shift();"}"!==tokens[0];){tokens.unshift("optional");var field=onfield(tokens);field.oneof=name,body.fields.push(field)}tokens.shift();break;case"extend":body.extends.push(onextend(tokens));break;case";":tokens.shift();break;default:tokens.unshift("optional"),body.fields.push(onfield(tokens))}return body},onextend=function(tokens){var out={name:tokens[1],message:onmessage(tokens)};return out},onextensions=function(tokens){tokens.shift();var from=Number(tokens.shift());if(isNaN(from))throw new Error("Invalid from in extensions definition");if("to"!==tokens.shift())throw new Error("Expected keyword 'to' in extensions definition");var to=tokens.shift();if("max"===to&&(to=MAX_RANGE),to=Number(to),isNaN(to))throw new Error("Invalid to in extensions definition");if(";"!==tokens.shift())throw new Error("Missing ; in extensions definition");return{from:from,to:to}},onmessage=function(tokens){tokens.shift();var lvl=1,body=[],msg={name:tokens.shift(),enums:[],extends:[],messages:[],fields:[]};if("{"!==tokens[0])throw new Error("Expected { but found "+tokens[0]);for(tokens.shift();tokens.length;){if("{"===tokens[0]?lvl++:"}"===tokens[0]&&lvl--,!lvl)return tokens.shift(),body=onmessagebody(body),msg.enums=body.enums,msg.messages=body.messages,msg.fields=body.fields,msg.extends=body.extends,msg.extensions=body.extensions,msg;body.push(tokens.shift())}if(lvl)throw new Error("No closing tag for message")},onpackagename=function(tokens){tokens.shift();var name=tokens.shift();if(";"!==tokens[0])throw new Error("Expected ; but found "+tokens[0]);return tokens.shift(),name},onsyntaxversion=function(tokens){if(tokens.shift(),"="!==tokens[0])throw new Error("Expected = but found "+tokens[0]);tokens.shift();var version=tokens.shift();switch(version){case'"proto2"':version=2;break;case'"proto3"':version=3;break;default:throw new Error("Expected protobuf syntax version but found "+version)}if(";"!==tokens[0])throw new Error("Expected ; but found "+tokens[0]);return tokens.shift(),version},onenumvalue=function(tokens){if(tokens.length<4)throw new Error("Invalid enum value: "+tokens.slice(0,3).join(" "));if("="!==tokens[1])throw new Error("Expected = but found "+tokens[1]);if(";"!==tokens[3]&&"["!==tokens[3])throw new Error("Expected ; or [ but found "+tokens[1]);var name=tokens.shift();tokens.shift();var val={value:null,options:{}};return val.value=Number(tokens.shift()),"["===tokens[0]&&(val.options=onfieldoptions(tokens)),tokens.shift(),{name:name,val:val}},onenum=function(tokens){tokens.shift();var options={},e={name:tokens.shift(),values:{},options:{}};if("{"!==tokens[0])throw new Error("Expected { but found "+tokens[0]);for(tokens.shift();tokens.length;){if("}"===tokens[0])return tokens.shift(),";"===tokens[0]&&tokens.shift(),e;if("option"!==tokens[0]){var val=onenumvalue(tokens);e.values[val.name]=val.val}else options=onoption(tokens),e.options[options.name]=options.value}throw new Error("No closing tag for enum")},onoption=function(tokens){for(var name=null,value=null,parse=function(value){return"true"===value||"false"!==value&&value.replace(/^"+|"+$/gm,"")};tokens.length;){if(";"===tokens[0])return tokens.shift(),{name:name,value:value};switch(tokens[0]){case"option":tokens.shift();var hasBracket="("===tokens[0];if(hasBracket&&tokens.shift(),name=tokens.shift(),hasBracket){if(")"!==tokens[0])throw new Error("Expected ) but found "+tokens[0]);tokens.shift()}break;case"=":if(tokens.shift(),null===name)throw new Error("Expected key for option with value: "+tokens[0]);if(value=parse(tokens.shift()),"optimize_for"===name&&!/^(SPEED|CODE_SIZE|LITE_RUNTIME)$/.test(value))throw new Error("Unexpected value for option optimize_for: "+value);"{"===value&&(value=onoptionMap(tokens));break;default:throw new Error("Unexpected token in option: "+tokens[0])}}},onoptionMap=function(tokens){for(var parse=function(value){return"true"===value||"false"!==value&&value.replace(/^"+|"+$/gm,"")},map={};tokens.length;){if("}"===tokens[0])return tokens.shift(),map;var hasBracket="("===tokens[0];hasBracket&&tokens.shift();var key=tokens.shift();if(hasBracket){if(")"!==tokens[0])throw new Error("Expected ) but found "+tokens[0]);tokens.shift()}var value=null;switch(tokens[0]){case":":if(void 0!==map[key])throw new Error("Duplicate option map key "+key);tokens.shift(),value=parse(tokens.shift()),"{"===value&&(value=onoptionMap(tokens)),map[key]=value;break;case"{":if(tokens.shift(),value=onoptionMap(tokens),void 0===map[key]&&(map[key]=[]),!Array.isArray(map[key]))throw new Error("Duplicate option map key "+key);map[key].push(value);break;default:throw new Error("Unexpected token in option map: "+tokens[0])}}throw new Error("No closing tag for option map")},onimport=function(tokens){tokens.shift();var file=tokens.shift().replace(/^"+|"+$/gm,"");if(";"!==tokens[0])throw new Error("Unexpected token: "+tokens[0]+'. Expected ";"');return tokens.shift(),file},onservice=function(tokens){tokens.shift();var service={name:tokens.shift(),methods:[],options:{}};if("{"!==tokens[0])throw new Error("Expected { but found "+tokens[0]);for(tokens.shift();tokens.length;){if("}"===tokens[0])return tokens.shift(),";"===tokens[0]&&tokens.shift(),service;switch(tokens[0]){case"option":var opt=onoption(tokens);if(void 0!==service.options[opt.name])throw new Error("Duplicate option "+opt.name);service.options[opt.name]=opt.value;break;case"rpc":service.methods.push(onrpc(tokens));break;default:throw new Error("Unexpected token in service: "+tokens[0])}}throw new Error("No closing tag for service")},onrpc=function(tokens){tokens.shift();var rpc={name:tokens.shift(),input_type:null,output_type:null,client_streaming:!1,server_streaming:!1,options:{}};if("("!==tokens[0])throw new Error("Expected ( but found "+tokens[0]);if(tokens.shift(),"stream"===tokens[0]&&(tokens.shift(),rpc.client_streaming=!0),rpc.input_type=tokens.shift(),")"!==tokens[0])throw new Error("Expected ) but found "+tokens[0]);if(tokens.shift(),"returns"!==tokens[0])throw new Error("Expected returns but found "+tokens[0]);if(tokens.shift(),"("!==tokens[0])throw new Error("Expected ( but found "+tokens[0]);if(tokens.shift(),"stream"===tokens[0]&&(tokens.shift(),rpc.server_streaming=!0),rpc.output_type=tokens.shift(),")"!==tokens[0])throw new Error("Expected ) but found "+tokens[0]);if(tokens.shift(),";"===tokens[0])return tokens.shift(),rpc;if("{"!==tokens[0])throw new Error("Expected { but found "+tokens[0]);for(tokens.shift();tokens.length;){if("}"===tokens[0])return tokens.shift(),";"===tokens[0]&&tokens.shift(),rpc;if("option"!==tokens[0])throw new Error("Unexpected token in rpc options: "+tokens[0]);var opt=onoption(tokens);if(void 0!==rpc.options[opt.name])throw new Error("Duplicate option "+opt.name);rpc.options[opt.name]=opt.value}throw new Error("No closing tag for rpc")},parse=function(buf){for(var tokens=tokenize(buf.toString()),i=0;imsg.extensions.to)throw new Error(msg.name+" does not declare "+field.tag+" as an extension number");msg.fields.push(field)})})}),schema};module.exports=parse},function(module,exports){var onfield=function(f,result){var prefix=f.repeated?"repeated":f.required?"required":"optional";"map"===f.type&&(prefix="map<"+f.map.from+","+f.map.to+">"),f.oneof&&(prefix="");var opts=Object.keys(f.options||{}).map(function(key){return key+" = "+f.options[key]}).join(",");return opts&&(opts=" ["+opts+"]"),result.push((prefix?prefix+" ":"")+("map"===f.map?"":f.type+" ")+f.name+" = "+f.tag+opts+";"),result},onmessage=function(m,result){result.push("message "+m.name+" {"),m.enums||(m.enums=[]),m.enums.forEach(function(e){result.push(onenum(e,[]))}),m.messages||(m.messages=[]),m.messages.forEach(function(m){result.push(onmessage(m,[]))});var oneofs={};return m.fields||(m.fields=[]),m.fields.forEach(function(f){f.oneof?(oneofs[f.oneof]||(oneofs[f.oneof]=[]),oneofs[f.oneof].push(onfield(f,[]))):result.push(onfield(f,[]))}),Object.keys(oneofs).forEach(function(n){oneofs[n].unshift("oneof "+n+" {"),oneofs[n].push("}"),result.push(oneofs[n])}),result.push("}",""),result},onenum=function(e,result){result.push("enum "+e.name+" {"),e.options||(e.options={});var options=onoption(e.options,[]);return options.length>1&&result.push(options.slice(0,-1)),Object.keys(e.values).map(function(v){var val=onenumvalue(e.values[v]);result.push([v+" = "+val+";"])}),result.push("}",""),result},onenumvalue=function(v,result){var opts=Object.keys(v.options||{}).map(function(key){return key+" = "+v.options[key]}).join(",");opts&&(opts=" ["+opts+"]");var val=v.value+opts;return val},onoption=function(o,result){var keys=Object.keys(o);return keys.forEach(function(option){var v=o[option];~option.indexOf(".")&&(option="("+option+")");var type=typeof v;"object"===type?(v=onoptionMap(v,[]),v.length&&result.push("option "+option+" = {",v,"};")):("string"===type&&"optimize_for"!==option&&(v='"'+v+'"'),result.push("option "+option+" = "+v+";"))}),keys.length>0&&result.push(""),result},onoptionMap=function(o,result){var keys=Object.keys(o);return keys.forEach(function(k){var v=o[k],type=typeof v;"object"===type?Array.isArray(v)?v.forEach(function(v){v=onoptionMap(v,[]),v.length&&result.push(k+" {",v,"}")}):(v=onoptionMap(v,[]),v.length&&result.push(k+" {",v,"}")):("string"===type&&(v='"'+v+'"'),result.push(k+": "+v))}),result},onservices=function(s,result){return result.push("service "+s.name+" {"),s.options||(s.options={}),onoption(s.options,result),s.methods||(s.methods=[]),s.methods.forEach(function(m){result.push(onrpc(m,[]))}),result.push("}",""),result},onrpc=function(rpc,result){var def="rpc "+rpc.name+"(";rpc.client_streaming&&(def+="stream "),def+=rpc.input_type+") returns (",rpc.server_streaming&&(def+="stream "),def+=rpc.output_type+")",rpc.options||(rpc.options={});var options=onoption(rpc.options,[]);return options.length>1?result.push(def+" {",options.slice(0,-1),"}"):result.push(def+";"),result},indent=function(lvl){return function(line){return Array.isArray(line)?line.map(indent(lvl+" ")).join("\n"):lvl+line}};module.exports=function(schema){var result=[];return result.push('syntax = "proto'+schema.syntax+'";',""),schema.package&&result.push("package "+schema.package+";",""),schema.options||(schema.options={}),onoption(schema.options,result),schema.enums||(schema.enums=[]),schema.enums.forEach(function(e){onenum(e,result)}),schema.messages||(schema.messages=[]),schema.messages.forEach(function(m){onmessage(m,result)}),schema.services&&schema.services.forEach(function(s){onservices(s,result)}),result.map(indent("")).join("\n")}},function(module,exports){module.exports=function(sch){var noComments=function(line){var i=line.indexOf("//");return i>-1?line.slice(0,i):line},noMultilineComments=function(){var inside=!1;return function(token){return"/*"===token?(inside=!0,!1):"*/"===token?(inside=!1,!1):!inside}},trim=function(line){return line.trim()};return sch.replace(/([;,{}\(\)=\:\[\]<>]|\/\*|\*\/)/g," $1 ").split(/\n/).map(trim).filter(Boolean).map(noComments).map(trim).filter(Boolean).join("\n").split(/\s+|\n+/gm).filter(noMultilineComments())}},function(module,exports,__webpack_require__){(function(Buffer){var encodings=__webpack_require__(257),varint=__webpack_require__(97),genobj=__webpack_require__(166),genfun=__webpack_require__(165),flatten=function(values){if(!values)return null;var result={};return Object.keys(values).forEach(function(k){result[k]=values[k].value}),result},skip=function(type,buffer,offset){switch(type){case 0:return varint.decode(buffer,offset),offset+varint.decode.bytes;case 1:return offset+8;case 2:var len=varint.decode(buffer,offset);return offset+varint.decode.bytes+len;case 3:case 4:throw new Error("Groups are not supported");case 5:return offset+4}throw new Error("Unknown wire type: "+type)},defined=function(val){return null!==val&&void 0!==val&&("number"!=typeof val||!isNaN(val))},isString=function(def){try{return!!def&&"string"==typeof JSON.parse(def)}catch(err){return!1}},defaultValue=function(f,def){if(f.map)return"{}";if(f.repeated)return"[]";switch(f.type){case"string":return isString(def)?def:'""';case"bool":return"true"===def?"true":"false";case"float":case"double":case"sfixed32":case"fixed32":case"varint":case"enum":case"uint64":case"uint32":case"int64":case"int32":case"sint64":case"sint32":return""+Number(def||0);default:return"null"}};module.exports=function(schema,extraEncodings){var messages={},enums={},cache={},visit=function(schema,prefix){schema.enums&&schema.enums.forEach(function(e){e.id=prefix+(prefix?".":"")+e.name,enums[e.id]=e,visit(e,e.id)}),schema.messages&&schema.messages.forEach(function(m){m.id=prefix+(prefix?".":"")+m.name,messages[m.id]=m,m.fields.forEach(function(f){if(f.map){var name="Map_"+f.map.from+"_"+f.map.to,map={name:name,enums:[],messages:[],fields:[{name:"key",type:f.map.from,tag:1,repeated:!1,required:!0},{name:"value",type:f.map.to,tag:2,repeated:!1,required:!1}],extensions:null,id:prefix+(prefix?".":"")+name};messages[map.id]||(messages[map.id]=map,schema.messages.push(map)),f.type=name,f.repeated=!0}}),visit(m,m.id)})};visit(schema,"");var compileEnum=function(e){var conditions=Object.keys(e.values).map(function(k){return"val !== "+parseInt(e.values[k].value,10)}).join(" && ");conditions||(conditions="true");var encode=genfun()("function encode (val, buf, offset) {")('if (%s) throw new Error("Invalid enum value: "+val)',conditions)("varint.encode(val, buf, offset)")("encode.bytes = varint.encode.bytes")("return buf")("}").toFunction({varint:varint}),decode=genfun()("function decode (buf, offset) {")("var val = varint.decode(buf, offset)")('if (%s) throw new Error("Invalid enum value: "+val)',conditions)("decode.bytes = varint.decode.bytes")("return val")("}").toFunction({varint:varint});return encodings.make(0,encode,decode,varint.encodingLength)},compileMessage=function(m,exports){m.messages.forEach(function(nested){exports[nested.name]=resolve(nested.name,m.id)}),m.enums.forEach(function(val){exports[val.name]=flatten(val.values)}),exports.type=2,exports.message=!0,exports.name=m.name;var oneofs={};m.fields.forEach(function(f){f.oneof&&(oneofs[f.oneof]||(oneofs[f.oneof]=[]),oneofs[f.oneof].push(f.name))});var enc=m.fields.map(function(f){return resolve(f.type,m.id)}),forEach=function(fn){for(var i=0;i 1) throw new Error(%s)",cnt,msg)}),forEach(function(e,f,val,i){var packed=f.repeated&&f.options&&f.options.packed&&"false"!==f.options.packed,hl=varint.encodingLength(f.tag<<3|e.type);f.required?encodingLength("if (!defined(%s)) throw new Error(%s)",val,JSON.stringify(f.name+" is required")):encodingLength("if (defined(%s)) {",val),f.map&&(encodingLength()("var tmp = Object.keys(%s)",val)("for (var i = 0; i < tmp.length; i++) {")("tmp[i] = {key: tmp[i], value: %s[tmp[i]]}",val)("}"),val="tmp"),packed?(encodingLength()("var packedLen = 0")("for (var i = 0; i < %s.length; i++) {",val)("if (!defined(%s)) continue",val+"[i]")("var len = enc[%d].encodingLength(%s)",i,val+"[i]")("packedLen += len"),e.message&&encodingLength("packedLen += varint.encodingLength(len)"),encodingLength("}")("if (packedLen) {")("length += %d + packedLen + varint.encodingLength(packedLen)",hl)("}")):(f.repeated&&(encodingLength("for (var i = 0; i < %s.length; i++) {",val),val+="[i]",encodingLength("if (!defined(%s)) continue",val)),encodingLength("var len = enc[%d].encodingLength(%s)",i,val),e.message&&encodingLength("length += varint.encodingLength(len)"),encodingLength("length += %d + len",hl),f.repeated&&encodingLength("}")),f.required||encodingLength("}")}),encodingLength()("return length")("}"),encodingLength=encodingLength.toFunction({defined:defined,varint:varint,enc:enc});var encode=genfun()("function encode (obj, buf, offset) {")("if (!offset) offset = 0")("if (!buf) buf = new Buffer(encodingLength(obj))")("var oldOffset = offset");Object.keys(oneofs).forEach(function(name){var msg=JSON.stringify("only one of the properties defined in oneof "+name+" can be set"),cnt=oneofs[name].map(function(prop){return"+defined("+genobj("obj",prop)+")"}).join(" + ");encode("if ((%s) > 1) throw new Error(%s)",cnt,msg)}),forEach(function(e,f,val,i){f.required?encode("if (!defined(%s)) throw new Error(%s)",val,JSON.stringify(f.name+" is required")):encode("if (defined(%s)) {",val);var j,packed=f.repeated&&f.options&&f.options.packed&&"false"!==f.options.packed,p=varint.encode(f.tag<<3|2),h=varint.encode(f.tag<<3|e.type);if(f.map&&(encode()("var tmp = Object.keys(%s)",val)("for (var i = 0; i < tmp.length; i++) {")("tmp[i] = {key: tmp[i], value: %s[tmp[i]]}",val)("}"),val="tmp"),packed){for(encode()("var packedLen = 0")("for (var i = 0; i < %s.length; i++) {",val)("if (!defined(%s)) continue",val+"[i]")("packedLen += enc[%d].encodingLength(%s)",i,val+"[i]")("}"),encode("if (packedLen) {"),j=0;j> 3")("switch (tag) {"),forEach(function(e,f,val,i){var packed=f.repeated&&f.options&&f.options.packed&&"false"!==f.options.packed;decode("case %d:",f.tag),f.oneof&&m.fields.forEach(function(otherField){otherField.oneof===f.oneof&&f.name!==otherField.name&&decode("delete %s",genobj("obj",otherField.name))}),packed&&decode()("var packedEnd = varint.decode(buf, offset)")("offset += varint.decode.bytes")("packedEnd += offset")("while (offset < packedEnd) {"),e.message?(decode("var len = varint.decode(buf, offset)"),decode("offset += varint.decode.bytes"),f.map?(decode("var tmp = enc[%d].decode(buf, offset, offset + len)",i),decode("%s[tmp.key] = tmp.value",val)):f.repeated?decode("%s.push(enc[%d].decode(buf, offset, offset + len))",val,i):decode("%s = enc[%d].decode(buf, offset, offset + len)",val,i)):f.repeated?decode("%s.push(enc[%d].decode(buf, offset))",val,i):decode("%s = enc[%d].decode(buf, offset)",val,i),decode("offset += enc[%d].decode.bytes",i),packed&&decode("}"),f.required&&decode("found%d = true",i),decode("break")}),decode()("default:")("offset = skip(prefix & 7, buf, offset)")("}")("}")("}"),decode=decode.toFunction({varint:varint,skip:skip,enc:enc}),encode.bytes=decode.bytes=0,exports.buffer=!0,exports.encode=encode,exports.decode=decode,exports.encodingLength=encodingLength,exports},resolve=function(name,from,compile){if(extraEncodings&&extraEncodings[name])return extraEncodings[name];if(encodings[name])return encodings[name];var m=(from?from+"."+name:name).split(".").map(function(part,i,list){ +return list.slice(0,i).concat(name).join(".")}).reverse().reduce(function(result,id){return result||messages[id]||enums[id]},null);if(compile===!1)return m;if(!m)throw new Error("Could not resolve "+name);return m.values?compileEnum(m):cache[m.id]||compileMessage(m,cache[m.id]={})};return(schema.enums||[]).concat((schema.messages||[]).map(function(message){return resolve(message.id)}))}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(Buffer){var varint=__webpack_require__(97),svarint=__webpack_require__(273),encoder=function(type,encode,decode,encodingLength){return encode.bytes=decode.bytes=0,{type:type,encode:encode,decode:decode,encodingLength:encodingLength}};exports.make=encoder,exports.bytes=function(tag){var bufferLength=function(val){return Buffer.isBuffer(val)?val.length:Buffer.byteLength(val)},encodingLength=function(val){var len=bufferLength(val);return varint.encodingLength(len)+len},encode=function(val,buffer,offset){var oldOffset=offset,len=bufferLength(val);return varint.encode(len,buffer,offset),offset+=varint.encode.bytes,Buffer.isBuffer(val)?val.copy(buffer,offset):buffer.write(val,offset,len),offset+=len,encode.bytes=offset-oldOffset,buffer},decode=function(buffer,offset){var oldOffset=offset,len=varint.decode(buffer,offset);offset+=varint.decode.bytes;var val=buffer.slice(offset,offset+len);return offset+=val.length,decode.bytes=offset-oldOffset,val};return encoder(2,encode,decode,encodingLength)}(),exports.string=function(){var encodingLength=function(val){var len=Buffer.byteLength(val);return varint.encodingLength(len)+len},encode=function(val,buffer,offset){var oldOffset=offset,len=Buffer.byteLength(val);return varint.encode(len,buffer,offset,"utf-8"),offset+=varint.encode.bytes,buffer.write(val,offset,len),offset+=len,encode.bytes=offset-oldOffset,buffer},decode=function(buffer,offset){var oldOffset=offset,len=varint.decode(buffer,offset);offset+=varint.decode.bytes;var val=buffer.toString("utf-8",offset,offset+len);return offset+=len,decode.bytes=offset-oldOffset,val};return encoder(2,encode,decode,encodingLength)}(),exports.bool=function(){var encodingLength=function(val){return 1},encode=function(val,buffer,offset){return buffer[offset]=val?1:0,encode.bytes=1,buffer},decode=function(buffer,offset){var bool=buffer[offset]>0;return decode.bytes=1,bool};return encoder(0,encode,decode,encodingLength)}(),exports.int32=function(){var decode=function(buffer,offset){var val=varint.decode(buffer,offset);return decode.bytes=varint.decode.bytes,val>2147483647?val-4294967296:val},encodingLength=function(val){return varint.encodingLength(val<0?val+4294967296:val)};return encoder(0,varint.encode,decode,encodingLength)}(),exports.int64=function(){var decode=function(buffer,offset){var val=varint.decode(buffer,offset);if(val>=Math.pow(2,63)){for(var limit=9;255===buffer[offset+limit-1];)limit--;limit=limit||9;var subset=new Buffer(limit);buffer.copy(subset,0,offset,offset+limit),subset[limit-1]=127&subset[limit-1],val=-1*varint.decode(subset,0),decode.bytes=10}else decode.bytes=varint.decode.bytes;return val},encode=function(val,buffer,offset){if(val<0){var last=offset+9;for(varint.encode(val*-1,buffer,offset),offset+=varint.encode.bytes-1,buffer[offset]=128|buffer[offset];offset=l)throw read.bytes=0,new RangeError("Could not decode varint");b=buf[counter++],res+=shift<28?(b&REST)<=MSB);return read.bytes=counter-offset,res}module.exports=read;var MSB=128,REST=127},function(module,exports){function encode(num,out,offset){out=out||[],offset=offset||0;for(var oldOffset=offset;num>=INT;)out[offset++]=255&num|MSB,num/=128;for(;num&MSBALL;)out[offset++]=255&num|MSB,num>>>=7;return out[offset]=0|num,encode.bytes=offset-oldOffset+1,out}module.exports=encode;var MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31)},function(module,exports){var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63);module.exports=function(value){return value1&&(result=parts[0]+"@",string=parts[1]),string=string.replace(regexSeparators,".");var labels=string.split("."),encoded=map(labels,fn).join(".");return result+encoded}function ucs2decode(string){for(var value,extra,output=[],counter=0,length=string.length;counter=55296&&value<=56319&&counter65535&&(value-=65536,output+=stringFromCharCode(value>>>10&1023|55296),value=56320|1023&value),output+=stringFromCharCode(value)}).join("")}function basicToDigit(codePoint){return codePoint-48<10?codePoint-22:codePoint-65<26?codePoint-65:codePoint-97<26?codePoint-97:base}function digitToBasic(digit,flag){return digit+22+75*(digit<26)-((0!=flag)<<5)}function adapt(delta,numPoints,firstTime){var k=0;for(delta=firstTime?floor(delta/damp):delta>>1,delta+=floor(delta/numPoints);delta>baseMinusTMin*tMax>>1;k+=base)delta=floor(delta/baseMinusTMin);return floor(k+(baseMinusTMin+1)*delta/(delta+skew))}function decode(input){var out,basic,j,index,oldi,w,k,digit,t,baseMinusT,output=[],inputLength=input.length,i=0,n=initialN,bias=initialBias;for(basic=input.lastIndexOf(delimiter),basic<0&&(basic=0),j=0;j=128&&error("not-basic"),output.push(input.charCodeAt(j));for(index=basic>0?basic+1:0;index=inputLength&&error("invalid-input"),digit=basicToDigit(input.charCodeAt(index++)),(digit>=base||digit>floor((maxInt-i)/w))&&error("overflow"),i+=digit*w,t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias,!(digitfloor(maxInt/baseMinusT)&&error("overflow"),w*=baseMinusT;out=output.length+1,bias=adapt(i-oldi,out,0==oldi),floor(i/out)>maxInt-n&&error("overflow"),n+=floor(i/out),i%=out,output.splice(i++,0,n)}return ucs2encode(output)}function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,inputLength,handledCPCountPlusOne,baseMinusT,qMinusT,output=[];for(input=ucs2decode(input),inputLength=input.length,n=initialN,delta=0,bias=initialBias,j=0;j=n&¤tValuefloor((maxInt-delta)/handledCPCountPlusOne)&&error("overflow"),delta+=(m-n)*handledCPCountPlusOne,n=m,j=0;jmaxInt&&error("overflow"),currentValue==n){for(q=delta,k=base;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias,!(q= 0x80 (not a basic code point)","invalid-input":"Invalid input"},baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode;punycode={version:"1.4.1",ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode},__WEBPACK_AMD_DEFINE_RESULT__=function(){return punycode}.call(exports,__webpack_require__,exports,module),!(void 0!==__WEBPACK_AMD_DEFINE_RESULT__&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}(this)}).call(exports,__webpack_require__(16)(module),__webpack_require__(8))},function(module,exports,__webpack_require__){"use strict";var stringify=__webpack_require__(266),parse=__webpack_require__(265),formats=__webpack_require__(98);module.exports={formats:formats,parse:parse,stringify:stringify}},function(module,exports,__webpack_require__){"use strict";var utils=__webpack_require__(99),has=Object.prototype.hasOwnProperty,defaults={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:utils.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,options.parameterLimit===1/0?void 0:options.parameterLimit),i=0;i=0&&options.parseArrays&&index<=options.arrayLimit?(obj=[],obj[index]=parseObject(chain,val,options)):obj[cleanRoot]=parseObject(chain,val,options)}return obj},parseKeys=function(givenKey,val,options){if(givenKey){var key=options.allowDots?givenKey.replace(/\.([^\.\[]+)/g,"[$1]"):givenKey,parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key),keys=[];if(segment[1]){if(!options.plainObjects&&has.call(Object.prototype,segment[1])&&!options.allowPrototypes)return;keys.push(segment[1])}for(var i=0;null!==(segment=child.exec(key))&&i0&&len>maxKeys&&(len=maxKeys);for(var i=0;i=0?(kstr=x.substr(0,idx),vstr=x.substr(idx+1)):(kstr=x,vstr=""),k=decodeURIComponent(kstr),v=decodeURIComponent(vstr),hasOwnProperty(obj,k)?isArray(obj[k])?obj[k].push(v):obj[k]=[obj[k],v]:obj[k]=v}return obj};var isArray=Array.isArray||function(xs){return"[object Array]"===Object.prototype.toString.call(xs)}},function(module,exports){"use strict";function map(xs,f){if(xs.map)return xs.map(f);for(var res=[],i=0;i0&&this._separator&&this.push(this._separator)},SandwichStream.prototype._pushTail=function(){this._tail&&this.push(this._tail)},sandwichStream.SandwichStream=SandwichStream,module.exports=sandwichStream},function(module,exports,__webpack_require__){var varint=__webpack_require__(276);exports.encode=function encode(v,b,o){v=v>=0?2*v:v*-2-1;var r=varint.encode(v,b,o);return encode.bytes=varint.encode.bytes,r},exports.decode=function decode(b,o){var v=varint.decode(b,o);return decode.bytes=varint.decode.bytes,1&v?(v+1)/-2:v/2},exports.encodingLength=function(v){return varint.encodingLength(v>=0?2*v:v*-2-1)}},function(module,exports){function read(buf,offset){var b,res=0,offset=offset||0,shift=0,counter=offset,l=buf.length;do{if(counter>=l)throw read.bytes=0,new RangeError("Could not decode varint");b=buf[counter++],res+=shift<28?(b&REST)<=MSB);return read.bytes=counter-offset,res}module.exports=read;var MSB=128,REST=127},function(module,exports){function encode(num,out,offset){out=out||[],offset=offset||0;for(var oldOffset=offset;num>=INT;)out[offset++]=255&num|MSB,num/=128;for(;num&MSBALL;)out[offset++]=255&num|MSB,num>>>=7;return out[offset]=0|num,encode.bytes=offset-oldOffset+1,out}module.exports=encode;var MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31)},function(module,exports,__webpack_require__){module.exports={encode:__webpack_require__(275),decode:__webpack_require__(274),encodingLength:__webpack_require__(277)}},function(module,exports){var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63);module.exports=function(value){return value=1?push(this,this.mapper(this._last+list.shift())):remaining=this._last+remaining,i=0;i0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk)),state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):(state.reading=!1,state.buffer.push(chunk)),state.needReadable&&emitReadable(stream),maybeReadMore(stream,state);else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM)n=MAX_HWM;else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){return 0===state.length&&state.ended?0:state.objectMode?0===n?0:1:null===n||isNaN(n)?state.flowing&&state.buffer.length?state.buffer[0].length:state.length:n<=0?0:(n>state.highWaterMark&&(state.highWaterMark=roundUpToNextPowerOf2(n)),n>state.length?state.ended?state.length:(state.needReadable=!0,0):n)}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,state.length>0?emitReadable(stream):endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(state.emittedReadable=!0,state.sync?process.nextTick(function(){emitReadable_(stream)}):emitReadable_(stream))}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,process.nextTick(function(){maybeReadMore_(stream,state)}))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length0)return;return 0===state.pipesCount?(state.flowing=!1,void(EE.listenerCount(src,"data")>0&&emitDataEvents(src))):void(state.ranOut=!0)}function pipeOnReadable(){this._readableState.ranOut&&(this._readableState.ranOut=!1,flow(this))}function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing)throw new Error("Cannot switch to old mode now.");var paused=startPaused||!1,readable=!1;stream.readable=!0,stream.pipe=Stream.prototype.pipe,stream.on=stream.addListener=Stream.prototype.on,stream.on("readable",function(){readable=!0;for(var c;!paused&&null!==(c=stream.read());)stream.emit("data",c);null===c&&(readable=!1,stream._readableState.needReadable=!0)}),stream.pause=function(){paused=!0,this.emit("pause")},stream.resume=function(){paused=!1,readable?process.nextTick(function(){stream.emit("readable")}):this.read(0),this.emit("resume")},stream.emit("readable")}function fromList(n,state){var ret,list=state.buffer,length=state.length,stringMode=!!state.decoder,objectMode=!!state.objectMode;if(0===list.length)return null;if(0===length)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length)ret=stringMode?list.join(""):Buffer.concat(list,length),list.length=0;else if(n0)throw new Error("endReadable called on non-empty stream");!state.endEmitted&&state.calledRead&&(state.ended=!0,process.nextTick(function(){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}))}function forEach(xs,f){for(var i=0,l=xs.length;i0)&&(state.emittedReadable=!1),0===n&&state.needReadable&&(state.length>=state.highWaterMark||state.ended))return emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return ret=null,state.length>0&&state.decoder&&(ret=fromList(n,state),state.length-=ret.length),0===state.length&&endReadable(this),ret;var doRead=state.needReadable;return state.length-n<=state.highWaterMark&&(doRead=!0),(state.ended||state.reading)&&(doRead=!1),doRead&&(state.reading=!0,state.sync=!0,0===state.length&&(state.needReadable=!0),this._read(state.highWaterMark),state.sync=!1),doRead&&!state.reading&&(n=howMuchToRead(nOrig,state)),ret=n>0?fromList(n,state):null,null===ret&&(state.needReadable=!0,n=0),state.length-=n,0!==state.length||state.ended||(state.needReadable=!0),state.ended&&!state.endEmitted&&0===state.length&&endReadable(this),ret},Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){readable===src&&cleanup()}function onend(){dest.end()}function cleanup(){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",cleanup),dest._writableState&&!dest._writableState.needDrain||ondrain()}function onerror(er){unpipe(),dest.removeListener("error",onerror),0===EE.listenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe()}function onfinish(){dest.removeListener("close",onclose),unpipe()}function unpipe(){src.unpipe(dest)}var src=this,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)}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?process.nextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);return dest.on("drain",ondrain),dest._events&&dest._events.error?isArray(dest._events.error)?dest._events.error.unshift(onerror):dest._events.error=[onerror,dest._events.error]:dest.on("error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(this.on("readable",pipeOnReadable),state.flowing=!0,process.nextTick(function(){flow(src)})),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,this.removeListener("readable",pipeOnReadable),state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,this.removeListener("readable",pipeOnReadable),state.flowing=!1;for(var i=0;ilen&&(r=len),e>len&&(e=len),li=l,ri=r;;)if(li0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(104)},function(module,exports,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(5)}catch(_){}}();exports=module.exports=__webpack_require__(105),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=__webpack_require__(60),exports.Duplex=__webpack_require__(15),exports.Transform=__webpack_require__(59),exports.PassThrough=__webpack_require__(104),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(exports,__webpack_require__(2))},function(module,exports,__webpack_require__){module.exports=__webpack_require__(59)},function(module,exports,__webpack_require__){module.exports=__webpack_require__(60)},function(module,exports,__webpack_require__){(function(Buffer,global,process){function decideMode(preferBinary,useFetch){return capability.fetch&&useFetch?"fetch":capability.mozchunkedarraybuffer?"moz-chunked-arraybuffer":capability.msstream?"ms-stream":capability.arraybuffer&&preferBinary?"arraybuffer":capability.vbArray&&preferBinary?"text:vbarray":"text"}function statusValid(xhr){try{var status=xhr.status;return null!==status&&0!==status}catch(e){return!1}}var capability=__webpack_require__(107),inherits=__webpack_require__(1),response=__webpack_require__(293),stream=__webpack_require__(111),toArrayBuffer=__webpack_require__(302),IncomingMessage=response.IncomingMessage,rStates=response.readyStates,ClientRequest=module.exports=function(opts){var self=this;stream.Writable.call(self),self._opts=opts,self._body=[],self._headers={},opts.auth&&self.setHeader("Authorization","Basic "+new Buffer(opts.auth).toString("base64")),Object.keys(opts.headers).forEach(function(name){self.setHeader(name,opts.headers[name])});var preferBinary,useFetch=!0;if("disable-fetch"===opts.mode)useFetch=!1,preferBinary=!0;else if("prefer-streaming"===opts.mode)preferBinary=!1;else if("allow-wrong-content-type"===opts.mode)preferBinary=!capability.overrideMimeType;else{if(opts.mode&&"default"!==opts.mode&&"prefer-fast"!==opts.mode)throw new Error("Invalid value for opts.mode");preferBinary=!0}self._mode=decideMode(preferBinary,useFetch),self.on("finish",function(){self._onFinish()})};inherits(ClientRequest,stream.Writable),ClientRequest.prototype.setHeader=function(name,value){var self=this,lowerName=name.toLowerCase();unsafeHeaders.indexOf(lowerName)===-1&&(self._headers[lowerName]={name:name,value:value})},ClientRequest.prototype.getHeader=function(name){var self=this;return self._headers[name.toLowerCase()].value},ClientRequest.prototype.removeHeader=function(name){var self=this;delete self._headers[name.toLowerCase()]},ClientRequest.prototype._onFinish=function(){var self=this;if(!self._destroyed){var body,opts=self._opts,headersObj=self._headers;if("POST"!==opts.method&&"PUT"!==opts.method&&"PATCH"!==opts.method&&"MERGE"!==opts.method||(body=capability.blobConstructor?new global.Blob(self._body.map(function(buffer){return toArrayBuffer(buffer)}),{type:(headersObj["content-type"]||{}).value||""}):Buffer.concat(self._body).toString()),"fetch"===self._mode){var headers=Object.keys(headersObj).map(function(name){return[headersObj[name].name,headersObj[name].value]});global.fetch(self._opts.url,{method:self._opts.method,headers:headers,body:body,mode:"cors",credentials:opts.withCredentials?"include":"same-origin"}).then(function(response){self._fetchResponse=response,self._connect()},function(reason){self.emit("error",reason)})}else{var xhr=self._xhr=new global.XMLHttpRequest;try{xhr.open(self._opts.method,self._opts.url,!0)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}"responseType"in xhr&&(xhr.responseType=self._mode.split(":")[0]),"withCredentials"in xhr&&(xhr.withCredentials=!!opts.withCredentials),"text"===self._mode&&"overrideMimeType"in xhr&&xhr.overrideMimeType("text/plain; charset=x-user-defined"),Object.keys(headersObj).forEach(function(name){xhr.setRequestHeader(headersObj[name].name,headersObj[name].value)}),self._response=null,xhr.onreadystatechange=function(){switch(xhr.readyState){case rStates.LOADING:case rStates.DONE:self._onXHRProgress()}},"moz-chunked-arraybuffer"===self._mode&&(xhr.onprogress=function(){self._onXHRProgress()}),xhr.onerror=function(){self._destroyed||self.emit("error",new Error("XHR error"))};try{xhr.send(body)}catch(err){return void process.nextTick(function(){self.emit("error",err)})}}}},ClientRequest.prototype._onXHRProgress=function(){var self=this;statusValid(self._xhr)&&!self._destroyed&&(self._response||self._connect(),self._response._onXHRProgress())},ClientRequest.prototype._connect=function(){var self=this;self._destroyed||(self._response=new IncomingMessage(self._xhr,self._fetchResponse,self._mode),self.emit("response",self._response))},ClientRequest.prototype._write=function(chunk,encoding,cb){var self=this;self._body.push(chunk),cb()},ClientRequest.prototype.abort=ClientRequest.prototype.destroy=function(){var self=this;self._destroyed=!0,self._response&&(self._response._destroyed=!0),self._xhr&&self._xhr.abort()},ClientRequest.prototype.end=function(data,encoding,cb){var self=this;"function"==typeof data&&(cb=data,data=void 0),stream.Writable.prototype.end.call(self,data,encoding,cb)},ClientRequest.prototype.flushHeaders=function(){},ClientRequest.prototype.setTimeout=function(){},ClientRequest.prototype.setNoDelay=function(){},ClientRequest.prototype.setSocketKeepAlive=function(){};var unsafeHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","user-agent","via"]}).call(exports,__webpack_require__(0).Buffer,__webpack_require__(8),__webpack_require__(2))},function(module,exports,__webpack_require__){(function(process,Buffer,global){var capability=__webpack_require__(107),inherits=__webpack_require__(1),stream=__webpack_require__(111),rStates=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},IncomingMessage=exports.IncomingMessage=function(xhr,response,mode){function read(){reader.read().then(function(result){if(!self._destroyed){if(result.done)return void self.push(null);self.push(new Buffer(result.value)),read()}})}var self=this;if(stream.Readable.call(self),self._mode=mode,self.headers={},self.rawHeaders=[],self.trailers={},self.rawTrailers=[],self.on("end",function(){process.nextTick(function(){self.emit("close")})}),"fetch"===mode){self._fetchResponse=response,self.url=response.url,self.statusCode=response.status,self.statusMessage=response.statusText,response.headers.forEach(function(header,key){self.headers[key.toLowerCase()]=header,self.rawHeaders.push(key,header)});var reader=response.body.getReader();read()}else{self._xhr=xhr,self._pos=0,self.url=xhr.responseURL,self.statusCode=xhr.status,self.statusMessage=xhr.statusText;var headers=xhr.getAllResponseHeaders().split(/\r?\n/);if(headers.forEach(function(header){var matches=header.match(/^([^:]+):\s*(.*)/);if(matches){var key=matches[1].toLowerCase();"set-cookie"===key?(void 0===self.headers[key]&&(self.headers[key]=[]),self.headers[key].push(matches[2])):void 0!==self.headers[key]?self.headers[key]+=", "+matches[2]:self.headers[key]=matches[2],self.rawHeaders.push(matches[1],matches[2])}}),self._charset="x-user-defined",!capability.overrideMimeType){var mimeType=self.rawHeaders["mime-type"];if(mimeType){var charsetMatch=mimeType.match(/;\s*charset=([^;])(;|$)/);charsetMatch&&(self._charset=charsetMatch[1].toLowerCase())}self._charset||(self._charset="utf-8")}}};inherits(IncomingMessage,stream.Readable),IncomingMessage.prototype._read=function(){},IncomingMessage.prototype._onXHRProgress=function(){var self=this,xhr=self._xhr,response=null;switch(self._mode){case"text:vbarray":if(xhr.readyState!==rStates.DONE)break;try{response=new global.VBArray(xhr.responseBody).toArray()}catch(e){}if(null!==response){self.push(new Buffer(response));break}case"text":try{response=xhr.responseText}catch(e){self._mode="text:vbarray";break}if(response.length>self._pos){var newData=response.substr(self._pos);if("x-user-defined"===self._charset){for(var buffer=new Buffer(newData.length),i=0;iself._pos&&(self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))),self._pos=reader.result.byteLength)},reader.onload=function(){self.push(null)},reader.readAsArrayBuffer(response)}self._xhr.readyState===rStates.DONE&&"ms-stream"!==self._mode&&self.push(null)}}).call(exports,__webpack_require__(2),__webpack_require__(0).Buffer,__webpack_require__(8))},function(module,exports,__webpack_require__){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=__webpack_require__(109),util=__webpack_require__(3);util.inherits=__webpack_require__(1),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},function(module,exports,__webpack_require__){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(__webpack_require__(0).Buffer,__webpack_require__(11));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){var util=__webpack_require__(12),stream=__webpack_require__(5);module.exports.createReadStream=function(object,options){return new MultiStream(object,options)};var MultiStream=function(object,options){object instanceof Buffer||"string"==typeof object?(options=options||{},stream.Readable.call(this,{highWaterMark:options.highWaterMark,encoding:options.encoding})):stream.Readable.call(this,{objectMode:!0}),this._object=object};util.inherits(MultiStream,stream.Readable),MultiStream.prototype._read=function(){this.push(this._object),this._object=null}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){var util=__webpack_require__(12),bl=__webpack_require__(47),xtend=__webpack_require__(31),headers=__webpack_require__(112),Writable=__webpack_require__(43).Writable,PassThrough=__webpack_require__(43).PassThrough,noop=function(){},overflow=function(size){return size&=511,size&&512-size},emptyStream=function(self,offset){var s=new Source(self,offset);return s.end(),s},mixinPax=function(header,pax){return pax.path&&(header.name=pax.path),pax.linkpath&&(header.linkname=pax.linkpath),header.pax=pax,header},Source=function(self,offset){this._parent=self,this.offset=offset,PassThrough.call(this)};util.inherits(Source,PassThrough),Source.prototype.destroy=function(err){this._parent.destroy(err)};var Extract=function(opts){if(!(this instanceof Extract))return new Extract(opts);Writable.call(this,opts),this._offset=0,this._buffer=bl(),this._missing=0,this._onparse=noop,this._header=null, +this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var self=this,b=self._buffer,oncontinue=function(){self._continue()},onunlock=function(err){return self._locked=!1,err?self.destroy(err):void(self._stream||oncontinue())},onstreamend=function(){self._stream=null;var drain=overflow(self._header.size);drain?self._parse(drain,ondrain):self._parse(512,onheader),self._locked||oncontinue()},ondrain=function(){self._buffer.consume(overflow(self._header.size)),self._parse(512,onheader),oncontinue()},onpaxglobalheader=function(){var size=self._header.size;self._paxGlobal=headers.decodePax(b.slice(0,size)),b.consume(size),onstreamend()},onpaxheader=function(){var size=self._header.size;self._pax=headers.decodePax(b.slice(0,size)),self._paxGlobal&&(self._pax=xtend(self._paxGlobal,self._pax)),b.consume(size),onstreamend()},ongnulongpath=function(){var size=self._header.size;this._gnuLongPath=headers.decodeLongPath(b.slice(0,size)),b.consume(size),onstreamend()},ongnulonglinkpath=function(){var size=self._header.size;this._gnuLongLinkPath=headers.decodeLongPath(b.slice(0,size)),b.consume(size),onstreamend()},onheader=function(){var header,offset=self._offset;try{header=self._header=headers.decode(b.slice(0,512))}catch(err){self.emit("error",err)}return b.consume(512),header?"gnu-long-path"===header.type?(self._parse(header.size,ongnulongpath),void oncontinue()):"gnu-long-link-path"===header.type?(self._parse(header.size,ongnulonglinkpath),void oncontinue()):"pax-global-header"===header.type?(self._parse(header.size,onpaxglobalheader),void oncontinue()):"pax-header"===header.type?(self._parse(header.size,onpaxheader),void oncontinue()):(self._gnuLongPath&&(header.name=self._gnuLongPath,self._gnuLongPath=null),self._gnuLongLinkPath&&(header.linkname=self._gnuLongLinkPath,self._gnuLongLinkPath=null),self._pax&&(self._header=header=mixinPax(header,self._pax),self._pax=null),self._locked=!0,header.size?(self._stream=new Source(self,offset),self.emit("entry",header,self._stream,onunlock),self._parse(header.size,onstreamend),void oncontinue()):(self._parse(512,onheader),void self.emit("entry",header,emptyStream(self,offset),onunlock))):(self._parse(512,onheader),void oncontinue())};this._parse(512,onheader)};util.inherits(Extract,Writable),Extract.prototype.destroy=function(err){this._destroyed||(this._destroyed=!0,err&&this.emit("error",err),this.emit("close"),this._stream&&this._stream.emit("close"))},Extract.prototype._parse=function(size,onparse){this._destroyed||(this._offset+=size,this._missing=size,this._onparse=onparse)},Extract.prototype._continue=function(){if(!this._destroyed){var cb=this._cb;this._cb=noop,this._overflow?this._write(this._overflow,void 0,cb):cb()}},Extract.prototype._write=function(data,enc,cb){if(!this._destroyed){var s=this._stream,b=this._buffer,missing=this._missing;if(data.lengthmissing&&(overflow=data.slice(missing),data=data.slice(0,missing)),s?s.end(data):b.append(data),this._overflow=overflow,this._onparse()}},module.exports=Extract},function(module,exports,__webpack_require__){exports.extract=__webpack_require__(297),exports.pack=__webpack_require__(301)},function(module,exports,__webpack_require__){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=__webpack_require__(114),util=__webpack_require__(3);util.inherits=__webpack_require__(1),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},function(module,exports,__webpack_require__){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(__webpack_require__(0).Buffer,__webpack_require__(11));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},function(module,exports,__webpack_require__){(function(Buffer,process){function modeToType(mode){switch(mode&constants.S_IFMT){case constants.S_IFBLK:return"block-device";case constants.S_IFCHR:return"character-device";case constants.S_IFDIR:return"directory";case constants.S_IFIFO:return"fifo";case constants.S_IFLNK:return"symlink"}return"file"}var constants=__webpack_require__(183),eos=__webpack_require__(162),util=__webpack_require__(12),Readable=__webpack_require__(43).Readable,Writable=__webpack_require__(43).Writable,StringDecoder=__webpack_require__(7).StringDecoder,headers=__webpack_require__(112),DMODE=parseInt("755",8),FMODE=parseInt("644",8),END_OF_TAR=new Buffer(1024);END_OF_TAR.fill(0);var noop=function(){},overflow=function(self,size){size&=511,size&&self.push(END_OF_TAR.slice(0,512-size))},Sink=function(to){Writable.call(this),this.written=0,this._to=to,this._destroyed=!1};util.inherits(Sink,Writable),Sink.prototype._write=function(data,enc,cb){return this.written+=data.length,this._to.push(data)?cb():void(this._to._drain=cb)},Sink.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var LinkSink=function(){Writable.call(this),this.linkname="",this._decoder=new StringDecoder("utf-8"),this._destroyed=!1};util.inherits(LinkSink,Writable),LinkSink.prototype._write=function(data,enc,cb){this.linkname+=this._decoder.write(data),cb()},LinkSink.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Void=function(){Writable.call(this),this._destroyed=!1};util.inherits(Void,Writable),Void.prototype._write=function(data,enc,cb){cb(new Error("No body allowed for this entry"))},Void.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit("close"))};var Pack=function(opts){return this instanceof Pack?(Readable.call(this,opts),this._drain=noop,this._finalized=!1,this._finalizing=!1,this._destroyed=!1,void(this._stream=null)):new Pack(opts)};util.inherits(Pack,Readable),Pack.prototype.entry=function(header,buffer,callback){if(this._stream)throw new Error("already piping an entry");if(!this._finalized&&!this._destroyed){"function"==typeof buffer&&(callback=buffer,buffer=null),callback||(callback=noop);var self=this;if(header.size&&"symlink"!==header.type||(header.size=0),header.type||(header.type=modeToType(header.mode)),header.mode||(header.mode="directory"===header.type?DMODE:FMODE),header.uid||(header.uid=0),header.gid||(header.gid=0),header.mtime||(header.mtime=new Date),"string"==typeof buffer&&(buffer=new Buffer(buffer)),Buffer.isBuffer(buffer))return header.size=buffer.length,this._encode(header),this.push(buffer),overflow(self,header.size),process.nextTick(callback),new Void;if("symlink"===header.type&&!header.linkname){var linkSink=new LinkSink;return eos(linkSink,function(err){return err?(self.destroy(),callback(err)):(header.linkname=linkSink.linkname,self._encode(header),void callback())}),linkSink}if(this._encode(header),"file"!==header.type&&"contiguous-file"!==header.type)return process.nextTick(callback),new Void;var sink=new Sink(this);return this._stream=sink,eos(sink,function(err){return self._stream=null,err?(self.destroy(),callback(err)):sink.written!==header.size?(self.destroy(),callback(new Error("size mismatch"))):(overflow(self,header.size),self._finalizing&&self.finalize(),void callback())}),sink}},Pack.prototype.finalize=function(){return this._stream?void(this._finalizing=!0):void(this._finalized||(this._finalized=!0,this.push(END_OF_TAR),this.push(null)))},Pack.prototype.destroy=function(err){this._destroyed||(this._destroyed=!0,err&&this.emit("error",err),this.emit("close"),this._stream&&this._stream.destroy&&this._stream.destroy())},Pack.prototype._encode=function(header){if(!header.pax){var buf=headers.encode(header);if(buf)return void this.push(buf)}this._encodePax(header)},Pack.prototype._encodePax=function(header){var paxHeader=headers.encodePax({name:header.name,linkname:header.linkname,pax:header.pax}),newHeader={name:"PaxHeader",mode:header.mode,uid:header.uid,gid:header.gid,size:paxHeader.length,mtime:header.mtime,type:"pax-header",linkname:header.linkname&&"PaxHeader",uname:header.uname,gname:header.gname,devmajor:header.devmajor,devminor:header.devminor};this.push(headers.encode(newHeader)),this.push(paxHeader),overflow(this,paxHeader.length),newHeader.size=header.size,newHeader.type=header.type,this.push(headers.encode(newHeader))},Pack.prototype._read=function(n){var drain=this._drain;this._drain=noop,drain()},module.exports=Pack}).call(exports,__webpack_require__(0).Buffer,__webpack_require__(2))},function(module,exports,__webpack_require__){var Buffer=__webpack_require__(0).Buffer;module.exports=function(buf){if(buf instanceof Uint8Array){if(0===buf.byteOffset&&buf.byteLength===buf.buffer.byteLength)return buf.buffer;if("function"==typeof buf.buffer.slice)return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.byteLength)}if(Buffer.isBuffer(buf)){for(var arrayCopy=new Uint8Array(buf.length),len=buf.length,i=0;iMAX_ARRAY_LENGTH)throw new RangeError("Array too large for polyfill");var i;for(i=0;i>s}function as_unsigned(value,bits){var s=32-bits;return value<>>s}function packI8(n){return[255&n]}function unpackI8(bytes){return as_signed(bytes[0],8)}function packU8(n){return[255&n]}function unpackU8(bytes){return as_unsigned(bytes[0],8)}function packU8Clamped(n){return n=round(Number(n)),[n<0?0:n>255?255:255&n]}function packI16(n){return[n>>8&255,255&n]}function unpackI16(bytes){return as_signed(bytes[0]<<8|bytes[1],16)}function packU16(n){return[n>>8&255,255&n]}function unpackU16(bytes){return as_unsigned(bytes[0]<<8|bytes[1],16)}function packI32(n){return[n>>24&255,n>>16&255,n>>8&255,255&n]}function unpackI32(bytes){return as_signed(bytes[0]<<24|bytes[1]<<16|bytes[2]<<8|bytes[3],32)}function packU32(n){return[n>>24&255,n>>16&255,n>>8&255,255&n]}function unpackU32(bytes){return as_unsigned(bytes[0]<<24|bytes[1]<<16|bytes[2]<<8|bytes[3],32)}function packIEEE754(v,ebits,fbits){function roundToEven(n){var w=floor(n),f=n-w;return f<.5?w:f>.5?w+1:w%2?w+1:w}var s,e,f,i,bits,str,bytes,bias=(1<=pow(2,1-bias)?(e=min(floor(log(v)/LN2),1023),f=roundToEven(v/pow(2,e)*pow(2,fbits)),f/pow(2,fbits)>=2&&(e+=1,f=1),e>bias?(e=(1<>=1;return bits.reverse(),str=bits.join(""),bias=(1<0?s*pow(2,e-bias)*(1+f/pow(2,fbits)):0!==f?s*pow(2,-(bias-1))*(f/pow(2,fbits)):s<0?-0:0}function unpackF64(b){return unpackIEEE754(b,11,52)}function packF64(v){return packIEEE754(v,11,52)}function unpackF32(b){return unpackIEEE754(b,8,23)}function packF32(v){return packIEEE754(v,8,23)}var defineProp,undefined=void 0,MAX_ARRAY_LENGTH=1e5,ECMAScript=function(){var opts=Object.prototype.toString,ophop=Object.prototype.hasOwnProperty;return{Class:function(v){return opts.call(v).replace(/^\[object *|\]$/g,"")},HasProperty:function(o,p){return p in o},HasOwnProperty:function(o,p){return ophop.call(o,p)},IsCallable:function(o){return"function"==typeof o},ToInt32:function(v){return v>>0},ToUint32:function(v){return v>>>0}}}(),LN2=Math.LN2,abs=Math.abs,floor=Math.floor,log=Math.log,min=Math.min,pow=Math.pow,round=Math.round;defineProp=Object.defineProperty&&function(){try{return Object.defineProperty({},"x",{}),!0}catch(e){return!1}}()?Object.defineProperty:function(o,p,desc){if(!o===Object(o))throw new TypeError("Object.defineProperty called on non-object");return ECMAScript.HasProperty(desc,"get")&&Object.prototype.__defineGetter__&&Object.prototype.__defineGetter__.call(o,p,desc.get),ECMAScript.HasProperty(desc,"set")&&Object.prototype.__defineSetter__&&Object.prototype.__defineSetter__.call(o,p,desc.set),ECMAScript.HasProperty(desc,"value")&&(o[p]=desc.value),o};var getOwnPropNames=Object.getOwnPropertyNames||function(o){if(o!==Object(o))throw new TypeError("Object.getOwnPropertyNames called on non-object");var p,props=[];for(p in o)ECMAScript.HasOwnProperty(o,p)&&props.push(p);return props};!function(){function makeConstructor(bytesPerElement,pack,unpack){var ctor;return ctor=function(buffer,byteOffset,length){var array,sequence,i,s;if(arguments.length&&"number"!=typeof arguments[0])if("object"==typeof arguments[0]&&arguments[0].constructor===ctor)for(array=arguments[0],this.length=array.length,this.byteLength=this.length*this.BYTES_PER_ELEMENT,this.buffer=new ArrayBuffer(this.byteLength),this.byteOffset=0,i=0;ithis.buffer.byteLength)throw new RangeError("byteOffset out of range");if(this.byteOffset%this.BYTES_PER_ELEMENT)throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");if(arguments.length<3){if(this.byteLength=this.buffer.byteLength-this.byteOffset,this.byteLength%this.BYTES_PER_ELEMENT)throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");this.length=this.byteLength/this.BYTES_PER_ELEMENT}else this.length=ECMAScript.ToUint32(length),this.byteLength=this.length*this.BYTES_PER_ELEMENT;if(this.byteOffset+this.byteLength>this.buffer.byteLength)throw new RangeError("byteOffset and length reference an area beyond the end of the buffer")}else for(sequence=arguments[0],this.length=ECMAScript.ToUint32(sequence.length),this.byteLength=this.length*this.BYTES_PER_ELEMENT,this.buffer=new ArrayBuffer(this.byteLength),this.byteOffset=0,i=0;i=this.length)return undefined;var i,o,bytes=[];for(i=0,o=this.byteOffset+index*this.BYTES_PER_ELEMENT;i=this.length)return undefined;var i,o,bytes=this._pack(value);for(i=0,o=this.byteOffset+index*this.BYTES_PER_ELEMENT;ithis.length)throw new RangeError("Offset plus length of array is out of range");if(byteOffset=this.byteOffset+offset*this.BYTES_PER_ELEMENT,byteLength=array.length*this.BYTES_PER_ELEMENT,array.buffer===this.buffer){for(tmp=[],i=0,s=array.byteOffset;ithis.length)throw new RangeError("Offset plus length of array is out of range");for(i=0;imax?max:v}start=ECMAScript.ToInt32(start),end=ECMAScript.ToInt32(end),arguments.length<1&&(start=0),arguments.length<2&&(end=this.length),start<0&&(start=this.length+start),end<0&&(end=this.length+end),start=clamp(start,0,this.length),end=clamp(end,0,this.length);var len=end-start;return len<0&&(len=0),new this.constructor(this.buffer,this.byteOffset+start*this.BYTES_PER_ELEMENT,len)},ctor}var ArrayBuffer=function(length){if(length=ECMAScript.ToInt32(length),length<0)throw new RangeError("ArrayBuffer size is not a small enough positive integer");this.byteLength=length,this._bytes=[],this._bytes.length=length;var i;for(i=0;ithis.byteLength)throw new RangeError("Array index out of range");byteOffset+=this.byteOffset;var i,uint8Array=new exports.Uint8Array(this.buffer,byteOffset,arrayType.BYTES_PER_ELEMENT),bytes=[];for(i=0;ithis.byteLength)throw new RangeError("Array index out of range");var i,byteView,typeArray=new arrayType([value]),byteArray=new exports.Uint8Array(typeArray.buffer),bytes=[];for(i=0;ithis.buffer.byteLength)throw new RangeError("byteOffset out of range");if(arguments.length<3?this.byteLength=this.buffer.byteLength-this.byteOffset:this.byteLength=ECMAScript.ToUint32(byteLength),this.byteOffset+this.byteLength>this.buffer.byteLength)throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");configureProperties(this)};DataView.prototype.getUint8=makeGetter(exports.Uint8Array),DataView.prototype.getInt8=makeGetter(exports.Int8Array),DataView.prototype.getUint16=makeGetter(exports.Uint16Array),DataView.prototype.getInt16=makeGetter(exports.Int16Array),DataView.prototype.getUint32=makeGetter(exports.Uint32Array),DataView.prototype.getInt32=makeGetter(exports.Int32Array),DataView.prototype.getFloat32=makeGetter(exports.Float32Array),DataView.prototype.getFloat64=makeGetter(exports.Float64Array),DataView.prototype.setUint8=makeSetter(exports.Uint8Array),DataView.prototype.setInt8=makeSetter(exports.Int8Array),DataView.prototype.setUint16=makeSetter(exports.Uint16Array),DataView.prototype.setInt16=makeSetter(exports.Int16Array),DataView.prototype.setUint32=makeSetter(exports.Uint32Array),DataView.prototype.setInt32=makeSetter(exports.Int32Array),DataView.prototype.setFloat32=makeSetter(exports.Float32Array),DataView.prototype.setFloat64=makeSetter(exports.Float64Array),exports.DataView=exports.DataView||DataView}()},function(module,exports){"use strict";module.exports={isString:function(arg){return"string"==typeof arg},isObject:function(arg){return"object"==typeof arg&&null!==arg},isNull:function(arg){return null===arg},isNullOrUndefined:function(arg){return null==arg}}},function(module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},function(module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},function(module,exports){function read(buf,offset){var b,res=0,offset=offset||0,shift=0,counter=offset,l=buf.length;do{if(counter>=l)return read.bytes=0,void(read.bytesRead=0);b=buf[counter++],res+=shift<28?(b&REST)<=MSB);return read.bytes=counter-offset,res}module.exports=read;var MSB=128,REST=127},function(module,exports){function encode(num,out,offset){out=out||[],offset=offset||0;for(var oldOffset=offset;num>=INT;)out[offset++]=255&num|MSB,num/=128;for(;num&MSBALL;)out[offset++]=255&num|MSB,num>>>=7;return out[offset]=0|num,encode.bytes=offset-oldOffset+1,out}module.exports=encode;var MSB=128,REST=127,MSBALL=~REST,INT=Math.pow(2,31)},function(module,exports){var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63);module.exports=function(value){return value2&&(prv=!0,info.shift());var jwk={ext:!0};switch(info[0][0]){case"1.2.840.113549.1.1.1":var rsaComp=["n","e","d","p","q","dp","dq","qi"],rsaKey=b2der(info[1]);prv&&rsaKey.shift();for(var i=0;i2&&(prv=!0,rsaKey.unshift(new Uint8Array([0]))),info[0][0]="1.2.840.113549.1.1.1",key=rsaKey;break;default:throw new TypeError("Unsupported key type")}return info.push(new Uint8Array(der2b(key)).buffer),prv?info.unshift(new Uint8Array([0])):info[1]={tag:3,value:info[1]},new Uint8Array(der2b(info)).buffer}function b2der(buf,ctx){if(buf instanceof ArrayBuffer&&(buf=new Uint8Array(buf)),ctx||(ctx={pos:0,end:buf.length}),ctx.end-ctx.pos<2||ctx.end>buf.length)throw new RangeError("Malformed DER");var tag=buf[ctx.pos++],len=buf[ctx.pos++];if(len>=128){if(len&=127,ctx.end-ctx.pos=128){var xlen=len,len=4;for(buf.splice(pos,0,xlen>>24&255,xlen>>16&255,xlen>>8&255,255&xlen);len>1&&!(xlen>>24);)xlen<<=8,len--;len<4&&buf.splice(pos,4-len),len|=128}return buf.splice(pos-2,2,tag,len),buf}function CryptoKey(key,alg,ext,use){Object.defineProperties(this,{_key:{value:key},type:{value:key.type,enumerable:!0},extractable:{value:void 0===ext?key.extractable:ext,enumerable:!0},algorithm:{value:void 0===alg?key.algorithm:alg,enumerable:!0},usages:{value:void 0===use?key.usages:use,enumerable:!0}})}function isPubKeyUse(u){return"verify"===u||"encrypt"===u||"wrapKey"===u}function isPrvKeyUse(u){return"sign"===u||"decrypt"===u||"unwrapKey"===u}if("function"!=typeof Promise)throw"Promise support required";var _crypto=global.crypto||global.msCrypto;if(_crypto){var _subtle=_crypto.subtle||_crypto.webkitSubtle;if(_subtle){var _Crypto=global.Crypto||_crypto.constructor||Object,_SubtleCrypto=global.SubtleCrypto||_subtle.constructor||Object,isEdge=(global.CryptoKey||global.Key||Object,window.navigator.userAgent.indexOf("Edge/")>-1),isIE=!!global.msCrypto&&!isEdge,isWebkit=!!_crypto.webkitSubtle;if(isIE||isWebkit){var oid2str={KoZIhvcNAQEB:"1.2.840.113549.1.1.1"},str2oid={"1.2.840.113549.1.1.1":"KoZIhvcNAQEB"};if(["generateKey","importKey","unwrapKey"].forEach(function(m){var _fn=_subtle[m];_subtle[m]=function(a,b,c){var ka,kx,ku,args=[].slice.call(arguments);switch(m){case"generateKey":ka=alg(a),kx=b,ku=c;break;case"importKey":ka=alg(c),kx=args[3],ku=args[4],"jwk"===a&&(b=b2jwk(b),b.alg||(b.alg=jwkAlg(ka)),b.key_ops||(b.key_ops="oct"!==b.kty?"d"in b?ku.filter(isPrvKeyUse):ku.filter(isPubKeyUse):ku.slice()),args[1]=jwk2b(b));break;case"unwrapKey":ka=args[4],kx=args[5],ku=args[6],args[2]=c._key}if("generateKey"===m&&"HMAC"===ka.name&&ka.hash)return ka.length=ka.length||{"SHA-1":512,"SHA-256":512,"SHA-384":1024,"SHA-512":1024}[ka.hash.name],_subtle.importKey("raw",_crypto.getRandomValues(new Uint8Array(ka.length+7>>3)),ka,kx,ku);if(isWebkit&&"generateKey"===m&&"RSASSA-PKCS1-v1_5"===ka.name&&(!ka.modulusLength||ka.modulusLength>=2048))return a=alg(a),a.name="RSAES-PKCS1-v1_5",delete a.hash,_subtle.generateKey(a,!0,["encrypt","decrypt"]).then(function(k){return Promise.all([_subtle.exportKey("jwk",k.publicKey),_subtle.exportKey("jwk",k.privateKey)])}).then(function(keys){return keys[0].alg=keys[1].alg=jwkAlg(ka),keys[0].key_ops=ku.filter(isPubKeyUse),keys[1].key_ops=ku.filter(isPrvKeyUse),Promise.all([_subtle.importKey("jwk",keys[0],ka,!0,keys[0].key_ops),_subtle.importKey("jwk",keys[1],ka,kx,keys[1].key_ops)])}).then(function(keys){return{publicKey:keys[0],privateKey:keys[1]}});if((isWebkit||isIE&&"SHA-1"===(ka.hash||{}).name)&&"importKey"===m&&"jwk"===a&&"HMAC"===ka.name&&"oct"===b.kty)return _subtle.importKey("raw",s2b(a2s(b.k)),c,args[3],args[4]);if(isWebkit&&"importKey"===m&&("spki"===a||"pkcs8"===a))return _subtle.importKey("jwk",pkcs2jwk(b),c,args[3],args[4]);if(isIE&&"unwrapKey"===m)return _subtle.decrypt(args[3],c,b).then(function(k){return _subtle.importKey(a,k,args[4],args[5],args[6])});var op;try{op=_fn.apply(_subtle,args)}catch(e){return Promise.reject(e)}return isIE&&(op=new Promise(function(res,rej){op.onabort=op.onerror=function(e){rej(e)},op.oncomplete=function(r){res(r.target.result)}})),op=op.then(function(k){return"HMAC"===ka.name&&(ka.length||(ka.length=8*k.algorithm.length)),0==ka.name.search("RSA")&&(ka.modulusLength||(ka.modulusLength=(k.publicKey||k).algorithm.modulusLength),ka.publicExponent||(ka.publicExponent=(k.publicKey||k).algorithm.publicExponent)),k=k.publicKey&&k.privateKey?{publicKey:new CryptoKey(k.publicKey,ka,kx,ku.filter(isPubKeyUse)),privateKey:new CryptoKey(k.privateKey,ka,kx,ku.filter(isPrvKeyUse))}:new CryptoKey(k,ka,kx,ku)})}}),["exportKey","wrapKey"].forEach(function(m){var _fn=_subtle[m];_subtle[m]=function(a,b,c){var args=[].slice.call(arguments);switch(m){case"exportKey":args[1]=b._key;break;case"wrapKey":args[1]=b._key,args[2]=c._key}if((isWebkit||isIE&&"SHA-1"===(b.algorithm.hash||{}).name)&&"exportKey"===m&&"jwk"===a&&"HMAC"===b.algorithm.name&&(args[0]="raw"),!isWebkit||"exportKey"!==m||"spki"!==a&&"pkcs8"!==a||(args[0]="jwk"),isIE&&"wrapKey"===m)return _subtle.exportKey(a,b).then(function(k){return"jwk"===a&&(k=s2b(unescape(encodeURIComponent(JSON.stringify(b2jwk(k)))))),_subtle.encrypt(args[3],c,k)});var op;try{op=_fn.apply(_subtle,args)}catch(e){return Promise.reject(e)}return isIE&&(op=new Promise(function(res,rej){op.onabort=op.onerror=function(e){rej(e)},op.oncomplete=function(r){res(r.target.result)}})),"exportKey"===m&&"jwk"===a&&(op=op.then(function(k){return(isWebkit||isIE&&"SHA-1"===(b.algorithm.hash||{}).name)&&"HMAC"===b.algorithm.name?{kty:"oct",alg:jwkAlg(b.algorithm),key_ops:b.usages.slice(),ext:!0,k:s2a(b2s(k))}:(k=b2jwk(k),k.alg||(k.alg=jwkAlg(b.algorithm)),k.key_ops||(k.key_ops="public"===b.type?b.usages.filter(isPubKeyUse):"private"===b.type?b.usages.filter(isPrvKeyUse):b.usages.slice()),k)})),!isWebkit||"exportKey"!==m||"spki"!==a&&"pkcs8"!==a||(op=op.then(function(k){return k=jwk2pkcs(b2jwk(k))})),op}}),["encrypt","decrypt","sign","verify"].forEach(function(m){var _fn=_subtle[m];_subtle[m]=function(a,b,c,d){if(isIE&&(!c.byteLength||d&&!d.byteLength))throw new Error("Empy input is not allowed");var args=[].slice.call(arguments),ka=alg(a);if(isIE&&"decrypt"===m&&"AES-GCM"===ka.name){var tl=a.tagLength>>3;args[2]=(c.buffer||c).slice(0,c.byteLength-tl),a.tag=(c.buffer||c).slice(c.byteLength-tl)}args[1]=b._key;var op;try{op=_fn.apply(_subtle,args)}catch(e){return Promise.reject(e)}return isIE&&(op=new Promise(function(res,rej){op.onabort=op.onerror=function(e){rej(e)},op.oncomplete=function(r){var r=r.target.result;if("encrypt"===m&&r instanceof AesGcmEncryptResult){var c=r.ciphertext,t=r.tag;r=new Uint8Array(c.byteLength+t.byteLength),r.set(new Uint8Array(c),0),r.set(new Uint8Array(t),c.byteLength),r=r.buffer}res(r)}})),op}}),isIE){var _digest=_subtle.digest;_subtle.digest=function(a,b){if(!b.byteLength)throw new Error("Empy input is not allowed");var op;try{op=_digest.call(_subtle,a,b)}catch(e){return Promise.reject(e)}return op=new Promise(function(res,rej){op.onabort=op.onerror=function(e){rej(e)},op.oncomplete=function(r){res(r.target.result)}})},global.crypto=Object.create(_crypto,{getRandomValues:{value:function(a){return _crypto.getRandomValues(a)}},subtle:{value:_subtle}}),global.CryptoKey=CryptoKey}isWebkit&&(_crypto.subtle=_subtle,global.Crypto=_Crypto,global.SubtleCrypto=_SubtleCrypto,global.CryptoKey=CryptoKey)}}}}},function(module,exports){function Yallist(list){var self=this;if(self instanceof Yallist||(self=new Yallist),self.tail=null,self.head=null,self.length=0,list&&"function"==typeof list.forEach)list.forEach(function(item){self.push(item)});else if(arguments.length>0)for(var i=0,l=arguments.length;i1)acc=initial;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");walker=this.head.next,acc=this.head.value}for(var i=0;null!==walker;i++)acc=fn(acc,walker.value,i),walker=walker.next;return acc},Yallist.prototype.reduceReverse=function(fn,initial){var acc,walker=this.tail;if(arguments.length>1)acc=initial;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");walker=this.tail.prev,acc=this.tail.value}for(var i=this.length-1;null!==walker;i--)acc=fn(acc,walker.value,i),walker=walker.prev;return acc},Yallist.prototype.toArray=function(){for(var arr=new Array(this.length),i=0,walker=this.head;null!==walker;i++)arr[i]=walker.value,walker=walker.next;return arr},Yallist.prototype.toArrayReverse=function(){for(var arr=new Array(this.length),i=0,walker=this.tail;null!==walker;i++)arr[i]=walker.value,walker=walker.prev;return arr},Yallist.prototype.slice=function(from,to){to=to||this.length,to<0&&(to+=this.length),from=from||0,from<0&&(from+=this.length);var ret=new Yallist;if(tothis.length&&(to=this.length);for(var i=0,walker=this.head;null!==walker&&ithis.length&&(to=this.length);for(var i=this.length,walker=this.tail;null!==walker&&i>to;i--)walker=walker.prev;for(;null!==walker&&i>from;i--,walker=walker.prev)ret.push(walker.value);return ret},Yallist.prototype.reverse=function(){for(var head=this.head,tail=this.tail,walker=head;null!==walker;walker=walker.prev){var p=walker.prev;walker.prev=walker.next,walker.next=p}return this.head=tail,this.tail=head,this}},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{wantlist:promisify(callback=>{send({path:"bitswap/wantlist"},callback)}),stat:promisify(callback=>{send({path:"bitswap/stat"},callback)}),unwant:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"bitswap/unwant",args:args,qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const promisify=__webpack_require__(4),bl=__webpack_require__(47),Block=__webpack_require__(171),multihash=__webpack_require__(14),CID=__webpack_require__(76);module.exports=(send=>{return{get:promisify((args,opts,callback)=>{return args&&CID.isCID(args)&&(args=multihash.toB58String(args.multihash)),"function"==typeof opts&&(callback=opts,opts={}),send({path:"block/get",args:args,qs:opts},(err,res)=>{return err?callback(err):void(Buffer.isBuffer(res)?callback(null,new Block(res)):res.pipe(bl((err,data)=>{return err?callback(err):void callback(null,new Block(data))})))})}),stat:promisify((args,opts,callback)=>{return args&&CID.isCID(args)&&(args=multihash.toB58String(args.multihash)),"function"==typeof opts&&(callback=opts,opts={}),send({path:"block/stat",args:args,qs:opts},(err,stats)=>{return err?callback(err):void callback(null,{key:stats.Key,size:stats.Size})})}),put:promisify((block,cid,callback)=>{if("function"==typeof cid&&(callback=cid,cid={}),Array.isArray(block)){const err=new Error("block.put() only accepts 1 file");return callback(err)}return"object"==typeof block&&block.data&&(block=block.data),send({path:"block/put",files:block},(err,blockInfo)=>{return err?callback(err):void callback(null,new Block(block))})})}})}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{add:promisify((args,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),args&&"object"==typeof args&&(opts=args,args=void 0),send({path:"bootstrap/add",args:args,qs:opts},callback)}),rm:promisify((args,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),args&&"object"==typeof args&&(opts=args,args=void 0),send({path:"bootstrap/rm",args:args,qs:opts},callback)}),list:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"bootstrap/list",qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return promisify(callback=>{send({path:"commands"},callback)})})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const streamifier=__webpack_require__(296),promisify=__webpack_require__(4);module.exports=(send=>{return{get:promisify((key,callback)=>{return"function"==typeof key&&(callback=key,key=void 0),key?void send({path:"config",args:key,buffer:!0},(err,response)=>{return err?callback(err):void callback(null,response.Value)}):void send({path:"config/show",buffer:!0},callback)}),set:promisify((key,value,opts,callback)=>{return"function"==typeof opts&&(callback=opts,opts={}),"string"!=typeof key?callback(new Error("Invalid key type")):"object"!=typeof value&&"boolean"!=typeof value&&"string"!=typeof value?callback(new Error("Invalid value type")):("object"==typeof value&&(value=JSON.stringify(value),opts={json:!0}),"boolean"==typeof value&&(value=value.toString(),opts={bool:!0}),void send({path:"config",args:[key,value],qs:opts,files:void 0,buffer:!0},callback))}),replace:promisify((config,callback)=>{"object"==typeof config&&(config=streamifier.createReadStream(new Buffer(JSON.stringify(config)))),send({path:"config/replace",files:config,buffer:!0},callback)})}})}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),streamToValue=__webpack_require__(17);module.exports=(send=>{return{findprovs:promisify((args,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={});const request={path:"dht/findprovs",args:args,qs:opts};send.andTransform(request,streamToValue,callback)}),get:promisify((key,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={});const handleResult=(done,err,res)=>{if(err)return done(err);if(!res)return done(new Error("empty response"));if(0===res.length)return done(new Error("no value returned for key"));if(Array.isArray(res)&&(res=res[0]),5===res.Type)done(null,res.Extra);else{let error=new Error("key was not found (type 6)");done(error)}};send({path:"dht/get",args:key,qs:opts},handleResult.bind(null,callback))}),put:promisify((key,value,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),send({path:"dht/put",args:[key,value],qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{net:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"diag/net",qs:opts},callback)}),sys:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"diag/sys",qs:opts},callback)}),cmds:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"diag/cmds",qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{cp:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"files/cp",args:args,qs:opts},callback)}),ls:promisify((args,opts,callback)=>{return"function"==typeof opts&&(callback=opts,opts={}),send({path:"files/ls",args:args,qs:opts},callback)}),mkdir:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"files/mkdir",args:args,qs:opts},callback)}),stat:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"files/stat",args:args,qs:opts},callback)}),rm:promisify((path,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),send({path:"files/rm",args:path,qs:opts},callback)}),read:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"files/read",args:args,qs:opts},callback)}),write:promisify((pathDst,files,opts,callback)=>{"function"!=typeof opts||callback||(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),send({path:"files/write",args:pathDst,qs:opts,files:files},callback)}),mv:promisify((args,opts,callback)=>{"function"==typeof opts&&void 0===callback&&(callback=opts,opts={}),send({path:"files/mv",args:args,qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts=void 0),send({path:"id",args:opts},(err,result)=>{if(err)return callback(err);const identity={id:result.ID,publicKey:result.PublicKey,addresses:result.Addresses,agentVersion:result.AgentVersion,protocolVersion:result.ProtocolVersion};callback(null,identity)})})})},function(module,exports,__webpack_require__){"use strict";const ndjson=__webpack_require__(92),promisify=__webpack_require__(4);module.exports=(send=>{return{tail:promisify(callback=>{return send({path:"log/tail"},(err,response)=>{return err?callback(err):void callback(null,response.pipe(ndjson.parse()))})})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"ls",args:args,qs:opts},callback)})})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return promisify((ipfs,ipns,callback)=>{"function"==typeof ipfs?(callback=ipfs,ipfs=null):"function"==typeof ipns&&(callback=ipns,ipns=null);const opts={};ipfs&&(opts.f=ipfs),ipns&&(opts.n=ipns),send({path:"mount",qs:opts},callback)})})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{publish:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"name/publish",args:args,qs:opts},callback)}),resolve:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"name/resolve",args:args,qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const dagPB=__webpack_require__(81),DAGNode=dagPB.DAGNode,DAGLink=dagPB.DAGLink,promisify=__webpack_require__(4),bs58=__webpack_require__(10),bl=__webpack_require__(47),cleanMultihash=__webpack_require__(61),LRU=__webpack_require__(228),lruOptions={max:128},cache=LRU(lruOptions);module.exports=(send=>{const api={get:promisify((multihash,options,callback)=>{"function"==typeof options&&(callback=options,options={}),options||(options={});try{multihash=cleanMultihash(multihash,options)}catch(err){return callback(err)}const node=cache.get(multihash);return node?callback(null,node):void send({path:"object/get",args:multihash},(err,result)=>{if(err)return callback(err);const links=result.Links.map(l=>{return new DAGLink(l.Name,l.Size,new Buffer(bs58.decode(l.Hash)))});DAGNode.create(result.Data,links,(err,node)=>{return err?callback(err):(cache.set(multihash,node),void callback(null,node))})})}),put:promisify((obj,options,callback)=>{"function"==typeof options&&(callback=options,options={}),options||(options={});let tmpObj={Data:null,Links:[]};if(Buffer.isBuffer(obj))options.enc||(tmpObj={Data:obj.toString(),Links:[]});else if(obj.multihash)tmpObj={Data:obj.data.toString(),Links:obj.links.map(l=>{const link=l.toJSON();return link.hash=link.multihash,link})};else{if("object"!=typeof obj)return callback(new Error("obj not recognized"));tmpObj.Data=obj.Data.toString()}let buf;buf=Buffer.isBuffer(obj)&&options.enc?obj:new Buffer(JSON.stringify(tmpObj));const enc=options.enc||"json";send({path:"object/put",qs:{inputenc:enc},files:buf},(err,result)=>{function next(){const nodeJSON=node.toJSON();if(nodeJSON.multihash!==result.Hash){const err=new Error("multihashes do not match");return callback(err)}cache.set(result.Hash,node),callback(null,node)}if(err)return callback(err);Buffer.isBuffer(obj)&&(options.enc?"json"===options.enc&&(obj=JSON.parse(obj.toString())):obj={Data:obj,Links:[]});let node;return obj.multihash?(node=obj,void next()):"protobuf"===options.enc?void dagPB.util.deserialize(obj,(err,_node)=>{return err?callback(err):(node=_node,void next())}):void DAGNode.create(new Buffer(obj.Data),obj.Links,(err,_node)=>{return err?callback(err):(node=_node,void next())})})}),data:promisify((multihash,options,callback)=>{"function"==typeof options&&(callback=options,options={}),options||(options={});try{multihash=cleanMultihash(multihash,options)}catch(err){return callback(err)}const node=cache.get(multihash);return node?callback(null,node.data):void send({path:"object/data",args:multihash},(err,result)=>{return err?callback(err):void("function"==typeof result.pipe?result.pipe(bl(callback)):callback(null,result))})}),links:promisify((multihash,options,callback)=>{"function"==typeof options&&(callback=options,options={}),options||(options={});try{multihash=cleanMultihash(multihash,options)}catch(err){return callback(err)}const node=cache.get(multihash);return node?callback(null,node.links):void send({path:"object/links",args:multihash},(err,result)=>{if(err)return callback(err);let links=[];result.Links&&(links=result.Links.map(l=>{return new DAGLink(l.Name,l.Size,new Buffer(bs58.decode(l.Hash)))})),callback(null,links)})}),stat:promisify((multihash,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),opts||(opts={});try{multihash=cleanMultihash(multihash,opts)}catch(err){return callback(err)}send({path:"object/stat",args:multihash},callback)}),new:promisify(callback=>{send({path:"object/new"},(err,result)=>{return err?callback(err):void DAGNode.create(new Buffer(0),(err,node)=>{return err?callback(err):node.toJSON().multihash!==result.Hash?(console.log(node.toJSON()),console.log(result),callback(new Error("multihashes do not match"))):void callback(null,node)})})}),patch:{addLink:promisify((multihash,dLink,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),opts||(opts={});try{multihash=cleanMultihash(multihash,opts)}catch(err){return callback(err)}send({path:"object/patch/add-link",args:[multihash,dLink.name,bs58.encode(dLink.multihash).toString()]},(err,result)=>{return err?callback(err):void api.get(result.Hash,{enc:"base58"},callback)})}),rmLink:promisify((multihash,dLink,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),opts||(opts={});try{multihash=cleanMultihash(multihash,opts)}catch(err){return callback(err)}send({path:"object/patch/rm-link",args:[multihash,dLink.name]},(err,result)=>{return err?callback(err):void api.get(result.Hash,{enc:"base58"},callback)})}),setData:promisify((multihash,data,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),opts||(opts={});try{multihash=cleanMultihash(multihash,opts)}catch(err){return callback(err)}send({path:"object/patch/set-data",args:[multihash],files:data},(err,result)=>{return err?callback(err):void api.get(result.Hash,{enc:"base58"},callback)})}),appendData:promisify((multihash,data,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),opts||(opts={});try{multihash=cleanMultihash(multihash,opts)}catch(err){return callback(err)}send({path:"object/patch/append-data",args:[multihash],files:data},(err,result)=>{return err?callback(err):void api.get(result.Hash,{enc:"base58"},callback)})})}};return api})}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{add:promisify((hash,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts=null),send({path:"pin/add",args:hash,qs:opts},(err,res)=>{return err?callback(err):void callback(null,res.Pins)})}),rm:promisify((hash,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts=null),send({path:"pin/rm",args:hash,qs:opts},(err,res)=>{return err?callback(err):void callback(null,res.Pins)})}),ls:promisify((hash,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),"object"==typeof hash&&(opts=hash,hash=void 0),"function"==typeof hash&&(callback=hash,hash=void 0,opts={}),send({path:"pin/ls",args:hash,qs:opts},(err,res)=>{return err?callback(err):void callback(null,res.Keys)})})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),streamToValue=__webpack_require__(17);module.exports=(send=>{return promisify((id,callback)=>{const request={path:"ping",args:id,qs:{n:1}},transform=(res,callback)=>{streamToValue(res,(err,res)=>{if(err)return callback(err);const pingResult={Success:res[1].Success,Time:res[1].Time,Text:res[2].Text};callback(null,pingResult)})};send.andTransform(request,transform,callback)})})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const promisify=__webpack_require__(4),PubsubMessageStream=__webpack_require__(341),stringlistToArray=__webpack_require__(346);let subscriptions={};const addSubscription=(topic,request)=>{subscriptions[topic]={request:request}},removeSubscription=promisify((topic,callback)=>{return subscriptions[topic]?(subscriptions[topic].request.abort(),delete subscriptions[topic],void(callback&&callback(null))):callback(new Error(`Not subscribed to ${topic}`))});module.exports=(send=>{return{subscribe:promisify((topic,options,callback)=>{const defaultOptions={discover:!1};if("function"==typeof options&&(callback=options,options=defaultOptions),options||(options=defaultOptions),subscriptions[topic])return callback(new Error(`Already subscribed to '${topic}'`));const request={path:"pubsub/sub",args:[topic],qs:{discover:options.discover}},req=send.andTransform(request,PubsubMessageStream.from,(err,stream)=>{return err?callback(err):(stream.cancel=promisify(cb=>removeSubscription(topic,cb)),addSubscription(topic,req),void callback(null,stream))})}),publish:promisify((topic,data,callback)=>{const buf=Buffer.isBuffer(data)?data:new Buffer(data),request={path:"pubsub/pub",args:[topic,buf]};send(request,callback)}),ls:promisify(callback=>{const request={path:"pubsub/ls"};send.andTransform(request,stringlistToArray,callback)}),peers:promisify((topic,callback)=>{if(!subscriptions[topic])return callback(new Error(`Not subscribed to '${topic}'`));const request={path:"pubsub/peers",args:[topic]};send.andTransform(request,stringlistToArray,callback)})}})}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),streamToValue=__webpack_require__(17);module.exports=(send=>{const refs=promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={});const request={path:"refs",args:args,qs:opts};send.andTransform(request,streamToValue,callback)});return refs.local=promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={});const request={path:"refs",qs:opts};send.andTransform(request,streamToValue,callback)}),refs})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{gc:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"repo/gc",qs:opts},callback)}),stat:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"repo/stat",qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),multiaddr=__webpack_require__(56),PeerId=__webpack_require__(96),PeerInfo=__webpack_require__(250);module.exports=(send=>{return{peers:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={});const verbose=opts.v||opts.verbose;send({path:"swarm/peers",qs:opts},(err,result)=>{return err?callback(err):void(result.Strings?callback(null,result.Strings.map(p=>{const res={};if(verbose){const parts=p.split(" ");res.addr=multiaddr(parts[0]),res.latency=parts[1]}else res.addr=multiaddr(p);return res.peer=PeerId.createFromB58String(res.addr.decapsulate("ipfs")),res})):result.Peers&&callback(null,result.Peers.map(p=>{const res={addr:multiaddr(p.Addr),peer:PeerId.createFromB58String(p.Peer),muxer:p.Muxer +};return p.Latency&&(res.latency=p.Latency),p.Streams&&(res.streams=p.Streams),res})))})}),connect:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"swarm/connect",args:args,qs:opts},callback)}),disconnect:promisify((args,opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"swarm/disconnect",args:args,qs:opts},callback)}),addrs:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"swarm/addrs",qs:opts},(err,result)=>{if(err)return callback(err);const peers=Object.keys(result.Addrs).map(id=>{const info=new PeerInfo(PeerId.createFromB58String(id));return result.Addrs[id].forEach(addr=>{info.multiaddr.add(multiaddr(addr))}),info});callback(null,peers)})}),localAddrs:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"swarm/addrs/local",qs:opts},(err,result)=>{return err?callback(err):void callback(null,result.Strings.map(addr=>{return multiaddr(addr)}))})})}})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return{apply:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"update",qs:opts},callback)}),check:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"update/check",qs:opts},callback)}),log:promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"update/log",qs:opts},callback)})}})},function(module,exports,__webpack_require__){"use strict";const isNode=__webpack_require__(49),promisify=__webpack_require__(4),DAGNodeStream=__webpack_require__(62);module.exports=(send=>{return promisify((path,opts,callback)=>{if("function"==typeof opts&&void 0===callback&&(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),!isNode)return callback(new Error("fsAdd does not work in the browser"));if("string"!=typeof path)return callback(new Error('"path" must be a string'));const request={path:"add",qs:opts,files:path},transform=(res,callback)=>DAGNodeStream.streamToValue(send,res,callback);send.andTransform(request,transform,callback)})})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4),once=__webpack_require__(94),parseUrl=__webpack_require__(116).parse,request=__webpack_require__(122),DAGNodeStream=__webpack_require__(62);module.exports=(send=>{return promisify((url,opts,callback)=>{return"function"==typeof opts&&void 0===callback&&(callback=opts,opts={}),"function"==typeof opts&&"function"==typeof callback&&(callback=opts,opts={}),"string"==typeof url&&url.startsWith("http")?(callback=once(callback),void request(parseUrl(url).protocol)(url,res=>{if(res.once("error",callback),res.statusCode>=400)return callback(new Error(`Failed to download with ${res.statusCode}`));const params={path:"add",qs:opts,files:res},transform=(res,callback)=>DAGNodeStream.streamToValue(send,res,callback);send.andTransform(params,transform,callback)}).end()):callback(new Error('"url" param must be an http(s) url'))})})},function(module,exports,__webpack_require__){"use strict";const promisify=__webpack_require__(4);module.exports=(send=>{return promisify((opts,callback)=>{"function"==typeof opts&&(callback=opts,opts={}),send({path:"version",qs:opts},(err,result)=>{if(err)return callback(err);const version={version:result.Version,commit:result.Commit,repo:result.Repo};callback(null,version)})})})},function(module,exports,__webpack_require__){"use strict";const pkg=__webpack_require__(184);exports=module.exports=(()=>{return{"api-path":"/api/v0/","user-agent":`/node-${pkg.name}/${pkg.version}/`,host:"localhost",port:"5001",protocol:"http"}})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){const DAGNode=__webpack_require__(81).DAGNode,parallel=__webpack_require__(141),streamToValue=__webpack_require__(17);module.exports=function(send,hash,callback){parallel([function(done){send({path:"object/get",args:hash},done)},function(done){send({path:"object/data",args:hash},done)}],function(err,res){if(err)return callback(err);var object=res[0],stream=res[1];Buffer.isBuffer(stream)?DAGNode.create(stream,object.Links,callback):streamToValue(stream,(err,data)=>{return err?callback(err):void DAGNode.create(data,object.Links,callback)})})}}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";function headers(file){const name=file.path||"",header={"Content-Disposition":`file; filename="${name}"`};return file.dir||!file.content?header["Content-Type"]="application/x-directory":file.symlink?header["Content-Type"]="application/symlink":header["Content-Type"]="application/octet-stream",header}function strip(name,base){const smallBase=base.split("/").slice(0,-1).join("/")+"/";return name.replace(smallBase,"")}function loadPaths(opts,file){const path=__webpack_require__(249),fs=__webpack_require__(354),glob=__webpack_require__(355),followSymlinks=null==opts.followSymlinks||opts.followSymlinks;file=path.resolve(file);const stats=fs.statSync(file);if(stats.isDirectory()&&!opts.recursive)throw new Error("Can only add directories using --recursive");if(stats.isDirectory()&&opts.recursive){const mg=new glob.sync.GlobSync(`${file}/**/*`,{follow:followSymlinks});return mg.found.map(name=>{return mg.symlinks[name]===!0?{path:strip(name,file),symlink:!0,dir:!1,content:fs.readlinkSync(name)}:"FILE"===mg.cache[name]?{path:strip(name,file),symlink:!1,dir:!1,content:fs.createReadStream(name)}:"DIR"===mg.cache[name]||mg.cache[name]instanceof Array?{path:strip(name,file),symlink:!1,dir:!0}:void 0}).filter(Boolean)}return{path:file,content:fs.createReadStream(file)}}function getFilesStream(files,opts){if(!files)return null;const mp=new Multipart;return flatmap(files,file=>{if("string"==typeof file){if(!isNode)throw new Error("Can not add paths in node");return loadPaths(opts,file)}return file.path&&!file.content?(file.dir=!0,file):file.path&&(file.content||file.dir)?file:{path:"",symlink:!1,dir:!1,content:file}}).forEach(file=>{mp.addPart({headers:headers(file),body:file.content})}),mp}const isNode=__webpack_require__(49),Multipart=__webpack_require__(242),flatmap=__webpack_require__(164);exports=module.exports=getFilesStream},function(module,exports,__webpack_require__){"use strict";function requireCommands(){const cmds={add:__webpack_require__(44),cat:__webpack_require__(119),createAddStream:__webpack_require__(120),bitswap:__webpack_require__(313),block:__webpack_require__(314),bootstrap:__webpack_require__(315),commands:__webpack_require__(316),config:__webpack_require__(317),dht:__webpack_require__(318),diag:__webpack_require__(319),id:__webpack_require__(321),get:__webpack_require__(121),log:__webpack_require__(322),ls:__webpack_require__(323),mount:__webpack_require__(324),name:__webpack_require__(325),object:__webpack_require__(326),pin:__webpack_require__(327),ping:__webpack_require__(328),refs:__webpack_require__(330),repo:__webpack_require__(331),swarm:__webpack_require__(332),pubsub:__webpack_require__(329),update:__webpack_require__(333),version:__webpack_require__(336)};return cmds.files=function(send){const files=__webpack_require__(320)(send);return files.add=__webpack_require__(44)(send),files.createAddStream=__webpack_require__(120)(send),files.get=__webpack_require__(121)(send),files.cat=__webpack_require__(119)(send),files},cmds.util=function(send){const util={addFromFs:__webpack_require__(334)(send),addFromStream:__webpack_require__(44)(send),addFromURL:__webpack_require__(335)(send)};return util},cmds}function loadCommands(send){const files=requireCommands(),cmds={};return Object.keys(files).forEach(file=>{cmds[file]=files[file](send)}),cmds}module.exports=loadCommands},function(module,exports,__webpack_require__){"use strict";const TransformStream=__webpack_require__(42).Transform,PubsubMessage=__webpack_require__(342);class PubsubMessageStream extends TransformStream{constructor(options){const opts=Object.assign(options||{},{objectMode:!0});super(opts)}static from(inputStream,callback){let outputStream=inputStream.pipe(new PubsubMessageStream);inputStream.on("end",()=>outputStream.emit("end")),callback(null,outputStream)}_transform(obj,enc,callback){try{const message=PubsubMessage.deserialize(obj,"base64");this.push(message)}catch(e){}callback()}}module.exports=PubsubMessageStream},function(module,exports,__webpack_require__){"use strict";const Base58=__webpack_require__(10),Base64=__webpack_require__(182).Base64,PubsubMessage=__webpack_require__(343);class PubsubMessageUtils{static create(senderId,data,seqNo,topics){return new PubsubMessage(senderId,data,seqNo,topics)}static deserialize(data,enc="json"){if(enc=enc?enc.toLowerCase():null,"json"===enc)return PubsubMessageUtils._deserializeFromJson(data);if("base64"===enc)return PubsubMessageUtils._deserializeFromBase64(data);throw new Error(`Unsupported encoding: '${enc}'`)}static _deserializeFromJson(data){const json=JSON.parse(data);return PubsubMessageUtils._deserializeFromBase64(json)}static _deserializeFromBase64(obj){if(!PubsubMessageUtils._isPubsubMessage(obj))throw new Error(`Not a pubsub message`);const senderId=Base58.encode(obj.from),payload=Base64.decode(obj.data),seqno=Base64.decode(obj.seqno),topics=obj.topicIDs;return PubsubMessageUtils.create(senderId,payload,seqno,topics)}static _isPubsubMessage(obj){return obj&&obj.from&&obj.seqno&&obj.data&&obj.topicIDs}}module.exports=PubsubMessageUtils},function(module,exports){"use strict";class PubsubMessage{constructor(senderId,data,seqNo,topics){this._senderId=senderId,this._data=data,this._seqNo=seqNo,this._topics=topics}get from(){return this._senderId}get data(){return this._data}get seqno(){return this._seqNo}get topicIDs(){return this._topics}}module.exports=PubsubMessage},function(module,exports,__webpack_require__){"use strict";function parseError(res,cb){const error=new Error(`Server responded with ${res.statusCode}`);streamToJsonValue(res,(err,payload)=>{return err?cb(err):(payload&&(error.code=payload.Code,error.message=payload.Message||payload.toString()),void cb(error))})}function onRes(buffer,cb){return res=>{const stream=Boolean(res.headers["x-stream-output"]),chunkedObjects=Boolean(res.headers["x-chunked-output"]),isJson=res.headers["content-type"]&&0===res.headers["content-type"].indexOf("application/json");return res.statusCode>=400||!res.statusCode?parseError(res,cb):stream&&!buffer?cb(null,res):chunkedObjects&&isJson?cb(null,res.pipe(ndjson.parse())):isJson?streamToJsonValue(res,cb):streamToValue(res,cb)}}function requestAPI(config,options,callback){options.qs=options.qs||{},callback=once(callback),Array.isArray(options.files)&&(options.qs.recursive=!0),Array.isArray(options.path)&&(options.path=options.path.join("/")),options.args&&!Array.isArray(options.args)&&(options.args=[options.args]),options.args&&(options.qs.arg=options.args),options.files&&!Array.isArray(options.files)&&(options.files=[options.files]),options.qs.r&&(options.qs.recursive=options.qs.r,delete options.qs.r),options.qs["stream-channels"]=!0;let stream;options.files&&(stream=getFilesStream(options.files,options.qs)),delete options.qs.followSymlinks;const method="POST",headers={};if(isNode&&(headers["User-Agent"]=config["user-agent"]),options.files){if(!stream.boundary)return callback(new Error("No boundary in multipart stream"));headers["Content-Type"]=`multipart/form-data; boundary=${stream.boundary}`}const qs=Qs.stringify(options.qs,{arrayFormat:"repeat"}),req=request(config.protocol)({hostname:config.host,path:`${config["api-path"]}${options.path}?${qs}`,port:config.port,method:method,headers:headers},onRes(options.buffer,callback));return req.on("error",err=>{callback(err)}),options.files?stream.pipe(req):req.end(),req}const Qs=__webpack_require__(264),isNode=__webpack_require__(49),ndjson=__webpack_require__(92),once=__webpack_require__(94),getFilesStream=__webpack_require__(339),streamToValue=__webpack_require__(17),streamToJsonValue=__webpack_require__(345),request=__webpack_require__(122);exports=module.exports=(config=>{const send=(options,callback)=>{return"object"!=typeof options?callback(new Error("no options were passed")):requestAPI(config,options,callback)};return send.andTransform=((options,transform,callback)=>{return send(options,(err,res)=>{return err?callback(err):void transform(res,callback)})}),send})},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function streamToJsonValue(res,cb){streamToValue(res,(err,data)=>{if(err)return cb(err);if(!data||0===data.length)return cb();Buffer.isBuffer(data)&&(data=data.toString());let res;try{res=JSON.parse(data)}catch(err){return cb(err)}cb(null,res)})}const streamToValue=__webpack_require__(17);module.exports=streamToJsonValue}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function stringlistToArray(res,cb){cb(null,res.Strings||[])}module.exports=stringlistToArray},function(module,exports,__webpack_require__){"use strict";const tar=__webpack_require__(298),ReadableStream=__webpack_require__(42).Readable;class TarStreamToObjects extends ReadableStream{constructor(options){const opts=Object.assign(options||{},{objectMode:!0});super(opts)}static from(inputStream,callback){let outputStream=new TarStreamToObjects;inputStream.pipe(tar.extract()).on("entry",(header,stream,next)=>{stream.on("end",next),"directory"!==header.type?outputStream.push({path:header.name,content:stream}):(outputStream.push({path:header.name}),stream.resume())}).on("finish",()=>outputStream.push(null)),callback(null,outputStream)}_read(){}}module.exports=TarStreamToObjects},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports){},function(module,exports,__webpack_require__){module.exports=__webpack_require__(123)}]); \ No newline at end of file diff --git a/js/orbit.min.js b/js/orbit.min.js new file mode 100644 index 00000000..5abd5e13 --- /dev/null +++ b/js/orbit.min.js @@ -0,0 +1,60 @@ +var Orbit=function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var installedModules={};return __webpack_require__.m=modules,__webpack_require__.c=installedModules,__webpack_require__.i=function(value){return value},__webpack_require__.d=function(exports,name,getter){Object.defineProperty(exports,name,{configurable:!1,enumerable:!0,get:getter})},__webpack_require__.n=function(module){var getter=module&&module.__esModule?function(){return module.default}:function(){return module};return __webpack_require__.d(getter,"a",getter),getter},__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)},__webpack_require__.p="",__webpack_require__(__webpack_require__.s=160)}([function(module,exports,__webpack_require__){"use strict";(function(Buffer,global){function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()&&"function"==typeof arr.subarray&&0===arr.subarray(1,1).byteLength}catch(e){return!1}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function createBuffer(that,length){if(kMaxLength()=kMaxLength())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+kMaxLength().toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(string)||string instanceof ArrayBuffer))return string.byteLength;"string"!=typeof string&&(string=""+string);var len=string.length;if(0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":case void 0:return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if(end>>>=0,start>>>=0,end<=start)return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),byteOffset=+byteOffset,isNaN(byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,Buffer.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}var indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&(encoding=String(encoding).toLowerCase(),"ucs2"===encoding||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining)):length=remaining;var strLen=string.length;if(strLen%2!==0)throw new TypeError("Invalid hex string");length>strLen/2&&(length=strLen/2);for(var i=0;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:secondByte=buf[i+1],128===(192&secondByte)&&(tempCodePoint=(31&firstByte)<<6|63&secondByte,tempCodePoint>127&&(codePoint=tempCodePoint));break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128===(192&secondByte)&&128===(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte,tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint));break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128===(192&secondByte)&&128===(192&thirdByte)&&128===(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte,tempCodePoint>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint))}}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return decodeCodePointsArray(res)}function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,codePoints);for(var res="",i=0;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function objectWriteUInt16(buf,value,offset,littleEndian){value<0&&(value=65535+value+1);for(var i=0,j=Math.min(buf.length-offset,2);i>>8*(littleEndian?i:1-i)}function objectWriteUInt32(buf,value,offset,littleEndian){value<0&&(value=4294967295+value+1);for(var i=0,j=Math.min(buf.length-offset,4);i>>8*(littleEndian?i:3-i)&255}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return noAssert||checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}function base64clean(str){if(str=stringtrim(str).replace(INVALID_BASE64_RE,""),str.length<2)return"";for(;str.length%4!==0;)str+="=";return str}function stringtrim(str){return str.trim?str.trim():str.replace(/^\s+|\s+$/g,"")}function toHex(n){return n<16?"0"+n.toString(16):n.toString(16)}function utf8ToBytes(string,units){units=units||1/0;for(var codePoint,length=string.length,leadSurrogate=null,bytes=[],i=0;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function asciiToBytes(str){for(var byteArray=[],i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isnan(val){return val!==val}var base64=__webpack_require__(117),ieee754=__webpack_require__(141),isArray=__webpack_require__(44);exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50,Buffer.TYPED_ARRAY_SUPPORT=void 0!==global.TYPED_ARRAY_SUPPORT?global.TYPED_ARRAY_SUPPORT:typedArraySupport(),exports.kMaxLength=kMaxLength(),Buffer.poolSize=8192,Buffer._augment=function(arr){return arr.__proto__=Buffer.prototype,arr},Buffer.from=function(value,encodingOrOffset,length){return from(null,value,encodingOrOffset,length)},Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0})),Buffer.alloc=function(size,fill,encoding){return alloc(null,size,fill,encoding)},Buffer.allocUnsafe=function(size){return allocUnsafe(null,size)},Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size)},Buffer.isBuffer=function(b){return!(null==b||!b._isBuffer)},Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i0&&(str=this.toString("hex",0,max).match(/.{2}/g).join(" "),this.length>max&&(str+=" ... ")),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target))throw new TypeError("Argument must be a Buffer");if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(start>>>=0,end>>>=0,thisStart>>>=0,thisEnd>>>=0,this===target)return 0;for(var x=thisEnd-thisStart,y=end-start,len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;iremaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start,end=void 0===end?len:~~end,start<0?(start+=len,start<0&&(start=0)):start>len&&(start=len),end<0?(end+=len,end<0&&(end=0)):end>len&&(end=len),end0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset|=0,byteLength|=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return mul*=128,val>=mul&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return noAssert||checkOffset(offset,1,this.length),128&this[offset]?(255-this[offset]+1)*-1:this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,byteLength|=0,!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1,i=0;for(this[offset]=255&value;++i=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,255,0),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,65535,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,4294967295,0),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset|=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,1,127,-128),Buffer.TYPED_ARRAY_SUPPORT||(value=Math.floor(value)),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8):objectWriteUInt16(this,value,offset,!0),offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,2,32767,-32768),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>8,this[offset+1]=255&value):objectWriteUInt16(this,value,offset,!1),offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24):objectWriteUInt32(this,value,offset,!0),offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset|=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),Buffer.TYPED_ARRAY_SUPPORT?(this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value):objectWriteUInt32(this,value,offset,!1),offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,end=void 0===end?this.length:end>>>0,val||(val=0);var i;if("number"==typeof val)for(i=start;i1)for(var i=1;i0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())),this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else if(listeners)for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;if(evlistener)return evlistener.length}return 0},EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)}},function(module,exports,__webpack_require__){(function(module){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){return BN.isBN(number)?number:(this.negative=0,this.words=null,this.length=0,this.red=null,void(null!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))))}function parseHex(str,start,end){for(var r=0,len=Math.min(str.length,end),i=start;i=49&&c<=54?c-49+10:c>=17&&c<=22?c-17+10:15&c}return r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i=49?c-49+10:c>=17?c-17+10:c}return r}function toBitArray(num){for(var w=new Array(num.bitLength()),bit=0;bit>>wbit}return w}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;var a=0|self.words[0],b=0|num.words[0],r=a*b,lo=67108863&r,carry=r/67108864|0;out.words[0]=lo;for(var k=1;k>>26,rword=67108863&carry,maxJ=Math.min(k,num.length-1),j=Math.max(0,k-self.length+1);j<=maxJ;j++){var i=k-j|0;a=0|self.words[i],b=0|num.words[j],r=a*b+rword,ncarry+=r/67108864|0,rword=67108863&r}out.words[k]=0|rword,carry=0|ncarry}return 0!==carry?out.words[k]=0|carry:out.length--,out.strip()}function bigMulTo(self,num,out){out.negative=num.negative^self.negative,out.length=self.length+num.length;for(var carry=0,hncarry=0,k=0;k>>26)|0,hncarry+=ncarry>>>26,ncarry&=67108863}out.words[k]=rword,carry=ncarry,ncarry=hncarry}return 0!==carry?out.words[k]=carry:out.length--,out.strip()}function jumboMulTo(self,num,out){var fftm=new FFTM;return fftm.mulp(self,num,out)}function FFTM(x,y){this.x=x,this.y=y}function MPrime(name,p){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()}function K256(){MPrime.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function P224(){MPrime.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function P192(){MPrime.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function P25519(){MPrime.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function Red(m){if("string"==typeof m){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}function Mont(m){Red.call(this,m),this.shift=this.m.bitLength(),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)}"object"==typeof module?module.exports=BN:exports.BN=BN,BN.BN=BN,BN.wordSize=26;var Buffer;try{Buffer=__webpack_require__(0).Buffer}catch(e){}BN.isBN=function(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return left.cmp(right)>0?left:right},BN.min=function(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);"hex"===base&&(base=16),assert(base===(0|base)&&base>=2&&base<=36),number=number.toString().replace(/\s+/g,"");var start=0;"-"===number[0]&&start++,16===base?this._parseHex(number,start):this._parseBase(number,base,start),"-"===number[0]&&(this.negative=1),this.strip(),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initNumber=function(number,base,endian){number<0&&(this.negative=1,number=-number),number<67108864?(this.words=[67108863&number],this.length=1):number<4503599627370496?(this.words=[67108863&number,number/67108864&67108863],this.length=2):(assert(number<9007199254740992),this.words=[67108863&number,number/67108864&67108863,1],this.length=3),"le"===endian&&this._initArray(this.toArray(),base,endian)},BN.prototype._initArray=function(number,base,endian){if(assert("number"==typeof number.length),number.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(number.length/3),this.words=new Array(this.length);for(var i=0;i=0;i-=3)w=number[i]|number[i-1]<<8|number[i-2]<<16,this.words[j]|=w<>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);else if("le"===endian)for(i=0,j=0;i>>26-off&67108863,off+=24,off>=26&&(off-=26,j++);return this.strip()},BN.prototype._parseHex=function(number,start){this.length=Math.ceil((number.length-start)/6),this.words=new Array(this.length);for(var i=0;i=start;i-=6)w=parseHex(number,i,i+6),this.words[j]|=w<>>26-off&4194303,off+=24,off>=26&&(off-=26,j++);i+6!==start&&(w=parseHex(number,start,i+6),this.words[j]|=w<>>26-off&4194303),this.strip()},BN.prototype._parseBase=function(number,base,start){this.words=[0],this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;limbPow*=base)limbLen++;limbLen--,limbPow=limbPow/base|0;for(var total=number.length-start,mod=total%limbLen,end=Math.min(total,total-mod)+start,word=0,i=start;i1&&0===this.words[this.length-1];)this.length--;return this._normSign()},BN.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},BN.prototype.inspect=function(){return(this.red?""};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"],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],groupBases=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];BN.prototype.toString=function(base,padding){base=base||10,padding=0|padding||1;var out;if(16===base||"hex"===base){out="";for(var off=0,carry=0,i=0;i>>24-off&16777215,out=0!==carry||i!==this.length-1?zeros[6-word.length]+word+out:word+out,off+=2,off>=26&&(off-=26,i--)}for(0!==carry&&(out=carry.toString(16)+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}if(base===(0|base)&&base>=2&&base<=36){var groupSize=groupSizes[base],groupBase=groupBases[base];out="";var c=this.clone();for(c.negative=0;!c.isZero();){var r=c.modn(groupBase).toString(base);c=c.idivn(groupBase),out=c.isZero()?r+out:zeros[groupSize-r.length]+r+out}for(this.isZero()&&(out="0"+out);out.length%padding!==0;)out="0"+out;return 0!==this.negative&&(out="-"+out),out}assert(!1,"Base should be between 2 and 36")},BN.prototype.toNumber=function(){var ret=this.words[0];return 2===this.length?ret+=67108864*this.words[1]:3===this.length&&1===this.words[2]?ret+=4503599627370496+67108864*this.words[1]:this.length>2&&assert(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-ret:ret},BN.prototype.toJSON=function(){return this.toString(16)},BN.prototype.toBuffer=function(endian,length){return assert("undefined"!=typeof Buffer),this.toArrayLike(Buffer,endian,length)},BN.prototype.toArray=function(endian,length){return this.toArrayLike(Array,endian,length)},BN.prototype.toArrayLike=function(ArrayType,endian,length){var byteLength=this.byteLength(),reqLength=length||Math.max(1,byteLength);assert(byteLength<=reqLength,"byte array longer than desired length"),assert(reqLength>0,"Requested array length <= 0"),this.strip();var b,i,littleEndian="le"===endian,res=new ArrayType(reqLength),q=this.clone();if(littleEndian){for(i=0;!q.isZero();i++)b=q.andln(255),q.iushrn(8),res[i]=b;for(;i=4096&&(r+=13,t>>>=13),t>=64&&(r+=7,t>>>=7),t>=8&&(r+=4,t>>>=4),t>=2&&(r+=2,t>>>=2),r+t},BN.prototype._zeroBits=function(w){if(0===w)return 26;var t=w,r=0;return 0===(8191&t)&&(r+=13,t>>>=13),0===(127&t)&&(r+=7,t>>>=7),0===(15&t)&&(r+=4,t>>>=4),0===(3&t)&&(r+=2,t>>>=2),0===(1&t)&&r++,r},BN.prototype.bitLength=function(){var w=this.words[this.length-1],hi=this._countBits(w);return 26*(this.length-1)+hi},BN.prototype.zeroBits=function(){if(this.isZero())return 0;for(var r=0,i=0;inum.length?this.clone().ior(num):num.clone().ior(this)},BN.prototype.uor=function(num){return this.length>num.length?this.clone().iuor(num):num.clone().iuor(this)},BN.prototype.iuand=function(num){var b;b=this.length>num.length?num:this;for(var i=0;inum.length?this.clone().iand(num):num.clone().iand(this)},BN.prototype.uand=function(num){return this.length>num.length?this.clone().iuand(num):num.clone().iuand(this)},BN.prototype.iuxor=function(num){var a,b;this.length>num.length?(a=this,b=num):(a=num,b=this);for(var i=0;inum.length?this.clone().ixor(num):num.clone().ixor(this)},BN.prototype.uxor=function(num){return this.length>num.length?this.clone().iuxor(num):num.clone().iuxor(this)},BN.prototype.inotn=function(width){assert("number"==typeof width&&width>=0);var bytesNeeded=0|Math.ceil(width/26),bitsLeft=width%26;this._expand(bytesNeeded),bitsLeft>0&&bytesNeeded--;for(var i=0;i0&&(this.words[i]=~this.words[i]&67108863>>26-bitsLeft),this.strip()},BN.prototype.notn=function(width){return this.clone().inotn(width)},BN.prototype.setn=function(bit,val){assert("number"==typeof bit&&bit>=0);var off=bit/26|0,wbit=bit%26;return this._expand(off+1),val?this.words[off]=this.words[off]|1<num.length?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>>26;for(;0!==carry&&i>>26;if(this.length=a.length,0!==carry)this.words[this.length]=carry,this.length++;else if(a!==this)for(;inum.length?this.clone().iadd(num):num.clone().iadd(this)},BN.prototype.isub=function(num){if(0!==num.negative){num.negative=0;var r=this.iadd(num);return num.negative=1,r._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(num),this.negative=1,this._normSign();var cmp=this.cmp(num);if(0===cmp)return this.negative=0,this.length=1,this.words[0]=0,this;var a,b;cmp>0?(a=this,b=num):(a=num,b=this);for(var carry=0,i=0;i>26,this.words[i]=67108863&r;for(;0!==carry&&i>26,this.words[i]=67108863&r;if(0===carry&&i>>13,a1=0|a[1],al1=8191&a1,ah1=a1>>>13,a2=0|a[2],al2=8191&a2,ah2=a2>>>13,a3=0|a[3],al3=8191&a3,ah3=a3>>>13,a4=0|a[4],al4=8191&a4,ah4=a4>>>13,a5=0|a[5],al5=8191&a5,ah5=a5>>>13,a6=0|a[6],al6=8191&a6,ah6=a6>>>13,a7=0|a[7],al7=8191&a7,ah7=a7>>>13,a8=0|a[8],al8=8191&a8,ah8=a8>>>13,a9=0|a[9],al9=8191&a9,ah9=a9>>>13,b0=0|b[0],bl0=8191&b0,bh0=b0>>>13,b1=0|b[1],bl1=8191&b1,bh1=b1>>>13,b2=0|b[2],bl2=8191&b2,bh2=b2>>>13,b3=0|b[3],bl3=8191&b3,bh3=b3>>>13,b4=0|b[4],bl4=8191&b4,bh4=b4>>>13,b5=0|b[5],bl5=8191&b5,bh5=b5>>>13,b6=0|b[6],bl6=8191&b6,bh6=b6>>>13,b7=0|b[7],bl7=8191&b7,bh7=b7>>>13,b8=0|b[8],bl8=8191&b8,bh8=b8>>>13,b9=0|b[9],bl9=8191&b9,bh9=b9>>>13;out.negative=self.negative^num.negative,out.length=19,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0,w0&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0,w1&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0,w2&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0,w3&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0,w4&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0,w5&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0,w6&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0,w7&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0,w8&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0,w9&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0,w10&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0,w11&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0,w12&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0,w13&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0,w14&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0,w15&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0,w16&=67108863,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)+((8191&mid)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0,w17&=67108863,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)+((8191&mid)<<13)|0;return c=(hi+(mid>>>13)|0)+(w18>>>26)|0,w18&=67108863,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,0!==c&&(o[19]=c,out.length++),out};Math.imul||(comb10MulTo=smallMulTo),BN.prototype.mulTo=function(num,out){var res,len=this.length+num.length;return res=10===this.length&&10===num.length?comb10MulTo(this,num,out):len<63?smallMulTo(this,num,out):len<1024?bigMulTo(this,num,out):jumboMulTo(this,num,out)},FFTM.prototype.makeRBT=function(N){for(var t=new Array(N),l=BN.prototype._countBits(N)-1,i=0;i>=1;return rb},FFTM.prototype.permute=function(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>=1)i++;return 1<>>=13,rws[2*i+1]=8191&carry,carry>>>=13;for(i=2*len;i>=26,carry+=w/67108864|0,carry+=lo>>>26,this.words[i]=67108863&lo}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.muln=function(num){return this.clone().imuln(num)},BN.prototype.sqr=function(){return this.mul(this)},BN.prototype.isqr=function(){return this.imul(this.clone())},BN.prototype.pow=function(num){var w=toBitArray(num);if(0===w.length)return new BN(1);for(var res=this,i=0;i=0);var i,r=bits%26,s=(bits-r)/26,carryMask=67108863>>>26-r<<26-r;if(0!==r){var carry=0;for(i=0;i>>26-r}carry&&(this.words[i]=carry,this.length++)}if(0!==s){for(i=this.length-1;i>=0;i--)this.words[i+s]=this.words[i];for(i=0;i=0);var h;h=hint?(hint-hint%26)/26:0;var r=bits%26,s=Math.min((bits-r)/26,this.length),mask=67108863^67108863>>>r<s)for(this.length-=s,i=0;i=0&&(0!==carry||i>=h);i--){var word=0|this.words[i];this.words[i]=carry<<26-r|word>>>r,carry=word&mask}return maskedWords&&0!==carry&&(maskedWords.words[maskedWords.length++]=carry),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},BN.prototype.ishrn=function(bits,hint,extended){return assert(0===this.negative),this.iushrn(bits,hint,extended)},BN.prototype.shln=function(bits){return this.clone().ishln(bits)},BN.prototype.ushln=function(bits){return this.clone().iushln(bits)},BN.prototype.shrn=function(bits){return this.clone().ishrn(bits)},BN.prototype.ushrn=function(bits){return this.clone().iushrn(bits)},BN.prototype.testn=function(bit){assert("number"==typeof bit&&bit>=0);var r=bit%26,s=(bit-r)/26,q=1<=0);var r=bits%26,s=(bits-r)/26;if(assert(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==r&&s++,this.length=Math.min(s,this.length),0!==r){var mask=67108863^67108863>>>r<=67108864;i++)this.words[i]-=67108864,i===this.length-1?this.words[i+1]=1:this.words[i+1]++;return this.length=Math.max(this.length,i+1),this},BN.prototype.isubn=function(num){if(assert("number"==typeof num),assert(num<67108864),num<0)return this.iaddn(-num);if(0!==this.negative)return this.negative=0,this.iaddn(num),this.negative=1,this;if(this.words[0]-=num,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var i=0;i>26)-(right/67108864|0),this.words[i+shift]=67108863&w}for(;i>26,this.words[i+shift]=67108863&w;if(0===carry)return this.strip();for(assert(carry===-1),carry=0,i=0;i>26,this.words[i]=67108863&w;return this.negative=1,this.strip()},BN.prototype._wordDiv=function(num,mode){var shift=this.length-num.length,a=this.clone(),b=num,bhi=0|b.words[b.length-1],bhiBits=this._countBits(bhi);shift=26-bhiBits,0!==shift&&(b=b.ushln(shift),a.iushln(shift),bhi=0|b.words[b.length-1]);var q,m=a.length-b.length;if("mod"!==mode){q=new BN(null),q.length=m+1,q.words=new Array(q.length);for(var i=0;i=0;j--){var qj=67108864*(0|a.words[b.length+j])+(0|a.words[b.length+j-1]);for(qj=Math.min(qj/bhi|0,67108863),a._ishlnsubmul(b,qj,j);0!==a.negative;)qj--,a.negative=0,a._ishlnsubmul(b,1,j),a.isZero()||(a.negative^=1);q&&(q.words[j]=qj)}return q&&q.strip(),a.strip(),"div"!==mode&&0!==shift&&a.iushrn(shift),{div:q||null,mod:a}},BN.prototype.divmod=function(num,mode,positive){if(assert(!num.isZero()),this.isZero())return{div:new BN(0),mod:new BN(0)};var div,mod,res;return 0!==this.negative&&0===num.negative?(res=this.neg().divmod(num,mode),"mod"!==mode&&(div=res.div.neg()),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.iadd(num)),{div:div,mod:mod}):0===this.negative&&0!==num.negative?(res=this.divmod(num.neg(),mode),"mod"!==mode&&(div=res.div.neg()),{div:div,mod:res.mod}):0!==(this.negative&num.negative)?(res=this.neg().divmod(num.neg(),mode),"div"!==mode&&(mod=res.mod.neg(),positive&&0!==mod.negative&&mod.isub(num)),{div:res.div,mod:mod}):num.length>this.length||this.cmp(num)<0?{div:new BN(0),mod:this}:1===num.length?"div"===mode?{div:this.divn(num.words[0]),mod:null}:"mod"===mode?{div:null,mod:new BN(this.modn(num.words[0]))}:{div:this.divn(num.words[0]),mod:new BN(this.modn(num.words[0]))}:this._wordDiv(num,mode)},BN.prototype.div=function(num){return this.divmod(num,"div",!1).div},BN.prototype.mod=function(num){return this.divmod(num,"mod",!1).mod},BN.prototype.umod=function(num){return this.divmod(num,"mod",!0).mod},BN.prototype.divRound=function(num){var dm=this.divmod(num);if(dm.mod.isZero())return dm.div;var mod=0!==dm.div.negative?dm.mod.isub(num):dm.mod,half=num.ushrn(1),r2=num.andln(1),cmp=mod.cmp(half);return cmp<0||1===r2&&0===cmp?dm.div:0!==dm.div.negative?dm.div.isubn(1):dm.div.iaddn(1)},BN.prototype.modn=function(num){assert(num<=67108863);for(var p=(1<<26)%num,acc=0,i=this.length-1;i>=0;i--)acc=(p*acc+(0|this.words[i]))%num;return acc},BN.prototype.idivn=function(num){assert(num<=67108863);for(var carry=0,i=this.length-1;i>=0;i--){var w=(0|this.words[i])+67108864*carry;this.words[i]=w/num|0,carry=w%num}return this.strip()},BN.prototype.divn=function(num){return this.clone().idivn(num)},BN.prototype.egcd=function(p){assert(0===p.negative),assert(!p.isZero());var x=this,y=p.clone();x=0!==x.negative?x.umod(p):x.clone();for(var A=new BN(1),B=new BN(0),C=new BN(0),D=new BN(1),g=0;x.isEven()&&y.isEven();)x.iushrn(1),y.iushrn(1),++g;for(var yp=y.clone(),xp=x.clone();!x.isZero();){for(var i=0,im=1;0===(x.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(x.iushrn(i);i-- >0;)(A.isOdd()||B.isOdd())&&(A.iadd(yp),B.isub(xp)),A.iushrn(1),B.iushrn(1);for(var j=0,jm=1;0===(y.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(y.iushrn(j);j-- >0;)(C.isOdd()||D.isOdd())&&(C.iadd(yp),D.isub(xp)),C.iushrn(1),D.iushrn(1);x.cmp(y)>=0?(x.isub(y),A.isub(C),B.isub(D)):(y.isub(x),C.isub(A),D.isub(B))}return{a:C,b:D,gcd:y.iushln(g)}},BN.prototype._invmp=function(p){assert(0===p.negative),assert(!p.isZero());var a=this,b=p.clone();a=0!==a.negative?a.umod(p):a.clone();for(var x1=new BN(1),x2=new BN(0),delta=b.clone();a.cmpn(1)>0&&b.cmpn(1)>0;){for(var i=0,im=1;0===(a.words[0]&im)&&i<26;++i,im<<=1);if(i>0)for(a.iushrn(i);i-- >0;)x1.isOdd()&&x1.iadd(delta),x1.iushrn(1);for(var j=0,jm=1;0===(b.words[0]&jm)&&j<26;++j,jm<<=1);if(j>0)for(b.iushrn(j);j-- >0;)x2.isOdd()&&x2.iadd(delta),x2.iushrn(1);a.cmp(b)>=0?(a.isub(b),x1.isub(x2)):(b.isub(a),x2.isub(x1))}var res;return res=0===a.cmpn(1)?x1:x2,res.cmpn(0)<0&&res.iadd(p),res},BN.prototype.gcd=function(num){if(this.isZero())return num.abs();if(num.isZero())return this.abs();var a=this.clone(),b=num.clone();a.negative=0,b.negative=0;for(var shift=0;a.isEven()&&b.isEven();shift++)a.iushrn(1),b.iushrn(1);for(;;){for(;a.isEven();)a.iushrn(1);for(;b.isEven();)b.iushrn(1);var r=a.cmp(b);if(r<0){var t=a;a=b,b=t}else if(0===r||0===b.cmpn(1))break;a.isub(b)}return b.iushln(shift)},BN.prototype.invm=function(num){return this.egcd(num).a.umod(num)},BN.prototype.isEven=function(){return 0===(1&this.words[0])},BN.prototype.isOdd=function(){return 1===(1&this.words[0])},BN.prototype.andln=function(num){return this.words[0]&num},BN.prototype.bincn=function(bit){assert("number"==typeof bit);var r=bit%26,s=(bit-r)/26,q=1<>>26,w&=67108863,this.words[i]=w}return 0!==carry&&(this.words[i]=carry,this.length++),this},BN.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},BN.prototype.cmpn=function(num){var negative=num<0;if(0!==this.negative&&!negative)return-1;if(0===this.negative&&negative)return 1;this.strip();var res;if(this.length>1)res=1;else{negative&&(num=-num),assert(num<=67108863,"Number is too big");var w=0|this.words[0];res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=0|this.words[i],b=0|num.words[i];if(a!==b){ab&&(res=1);break}}return res},BN.prototype.gtn=function(num){return 1===this.cmpn(num)},BN.prototype.gt=function(num){return 1===this.cmp(num)},BN.prototype.gten=function(num){return this.cmpn(num)>=0},BN.prototype.gte=function(num){return this.cmp(num)>=0},BN.prototype.ltn=function(num){return this.cmpn(num)===-1},BN.prototype.lt=function(num){return this.cmp(num)===-1},BN.prototype.lten=function(num){return this.cmpn(num)<=0},BN.prototype.lte=function(num){return this.cmp(num)<=0},BN.prototype.eqn=function(num){return 0===this.cmpn(num)},BN.prototype.eq=function(num){return 0===this.cmp(num)},BN.red=function(num){return new Red(num)},BN.prototype.toRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),assert(0===this.negative,"red works only with positives"),ctx.convertTo(this)._forceRed(ctx)},BN.prototype.fromRed=function(){return assert(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},BN.prototype._forceRed=function(ctx){return this.red=ctx,this},BN.prototype.forceRed=function(ctx){return assert(!this.red,"Already a number in reduction context"),this._forceRed(ctx)},BN.prototype.redAdd=function(num){return assert(this.red,"redAdd works only with red numbers"),this.red.add(this,num)},BN.prototype.redIAdd=function(num){return assert(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,num)},BN.prototype.redSub=function(num){return assert(this.red,"redSub works only with red numbers"),this.red.sub(this,num)},BN.prototype.redISub=function(num){return assert(this.red,"redISub works only with red numbers"),this.red.isub(this,num)},BN.prototype.redShl=function(num){return assert(this.red,"redShl works only with red numbers"),this.red.shl(this,num)},BN.prototype.redMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.mul(this,num)},BN.prototype.redIMul=function(num){return assert(this.red,"redMul works only with red numbers"),this.red._verify2(this,num),this.red.imul(this,num)},BN.prototype.redSqr=function(){return assert(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},BN.prototype.redISqr=function(){return assert(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},BN.prototype.redSqrt=function(){return assert(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},BN.prototype.redInvm=function(){return assert(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},BN.prototype.redNeg=function(){return assert(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},BN.prototype.redPow=function(num){return assert(this.red&&!num.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,num)};var primes={k256:null,p224:null,p192:null,p25519:null};MPrime.prototype._tmp=function(){var tmp=new BN(null);return tmp.words=new Array(Math.ceil(this.n/13)),tmp},MPrime.prototype.ireduce=function(num){var rlen,r=num;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),rlen=r.bitLength();while(rlen>this.n);var cmp=rlen0?r.isub(this.p):r.strip(),r},MPrime.prototype.split=function(input,out){input.iushrn(this.n,0,out)},MPrime.prototype.imulK=function(num){return num.imul(this.k)},inherits(K256,MPrime),K256.prototype.split=function(input,output){for(var mask=4194303,outLen=Math.min(input.length,9),i=0;i>>22,prev=next}prev>>>=22,input.words[i-10]=prev,0===prev&&input.length>10?input.length-=10:input.length-=9},K256.prototype.imulK=function(num){num.words[num.length]=0,num.words[num.length+1]=0,num.length+=2;for(var lo=0,i=0;i>>=26,num.words[i]=lo,carry=hi}return 0!==carry&&(num.words[num.length++]=carry),num},BN._prime=function prime(name){if(primes[name])return primes[name];var prime;if("k256"===name)prime=new K256;else if("p224"===name)prime=new P224;else if("p192"===name)prime=new P192;else{if("p25519"!==name)throw new Error("Unknown prime "+name);prime=new P25519}return primes[name]=prime,prime},Red.prototype._verify1=function(a){assert(0===a.negative,"red works only with positives"),assert(a.red,"red works only with red numbers")},Red.prototype._verify2=function(a,b){assert(0===(a.negative|b.negative),"red works only with positives"),assert(a.red&&a.red===b.red,"red works only with red numbers")},Red.prototype.imod=function(a){return this.prime?this.prime.ireduce(a)._forceRed(this):a.umod(this.m)._forceRed(this)},Red.prototype.neg=function(a){return a.isZero()?a.clone():this.m.sub(a)._forceRed(this)},Red.prototype.add=function(a,b){this._verify2(a,b);var res=a.add(b);return res.cmp(this.m)>=0&&res.isub(this.m),res._forceRed(this)},Red.prototype.iadd=function(a,b){this._verify2(a,b);var res=a.iadd(b);return res.cmp(this.m)>=0&&res.isub(this.m),res},Red.prototype.sub=function(a,b){this._verify2(a,b);var res=a.sub(b);return res.cmpn(0)<0&&res.iadd(this.m),res._forceRed(this)},Red.prototype.isub=function(a,b){this._verify2(a,b);var res=a.isub(b);return res.cmpn(0)<0&&res.iadd(this.m),res},Red.prototype.shl=function(a,num){return this._verify1(a),this.imod(a.ushln(num))},Red.prototype.imul=function(a,b){return this._verify2(a,b),this.imod(a.imul(b))},Red.prototype.mul=function(a,b){return this._verify2(a,b),this.imod(a.mul(b))},Red.prototype.isqr=function(a){return this.imul(a,a.clone())},Red.prototype.sqr=function(a){return this.mul(a,a)},Red.prototype.sqrt=function(a){if(a.isZero())return a.clone();var mod3=this.m.andln(3);if(assert(mod3%2===1),3===mod3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}for(var q=this.m.subn(1),s=0;!q.isZero()&&0===q.andln(1);)s++,q.iushrn(1);assert(!q.isZero());var one=new BN(1).toRed(this),nOne=one.redNeg(),lpow=this.m.subn(1).iushrn(1),z=this.m.bitLength();for(z=new BN(2*z*z).toRed(this);0!==this.pow(z,lpow).cmp(nOne);)z.redIAdd(nOne);for(var c=this.pow(z,q),r=this.pow(a,q.addn(1).iushrn(1)),t=this.pow(a,q),m=s;0!==t.cmp(one);){for(var tmp=t,i=0;0!==tmp.cmp(one);i++)tmp=tmp.redSqr();assert(i=0;i--){for(var word=num.words[i],j=start-1;j>=0;j--){var bit=word>>j&1;res!==wnd[0]&&(res=this.sqr(res)),0!==bit||0!==current?(current<<=1,current|=bit,currentLen++,(currentLen===windowSize||0===i&&0===j)&&(res=this.mul(res,wnd[current]),currentLen=0,current=0)):currentLen=0}start=26}return res},Red.prototype.convertTo=function(num){var r=num.umod(this.m);return r===num?r.clone():r},Red.prototype.convertFrom=function(num){var res=num.clone();return res.red=null,res},BN.mont=function(num){return new Mont(num)},inherits(Mont,Red),Mont.prototype.convertTo=function(num){return this.imod(num.ushln(this.shift))},Mont.prototype.convertFrom=function(num){var r=this.imod(num.mul(this.rinv));return r.red=null,r},Mont.prototype.imul=function(a,b){if(a.isZero()||b.isZero())return a.words[0]=0,a.length=1,a;var t=a.imul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.mul=function(a,b){if(a.isZero()||b.isZero())return new BN(0)._forceRed(this);var t=a.mul(b),c=t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),u=t.isub(c).iushrn(this.shift),res=u;return u.cmp(this.m)>=0?res=u.isub(this.m):u.cmpn(0)<0&&(res=u.iadd(this.m)),res._forceRed(this)},Mont.prototype.invm=function(a){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}}("undefined"==typeof module||module,this)}).call(exports,__webpack_require__(50)(module))},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var Post=function Post(type){_classCallCheck(this,Post),this.type=type};module.exports=Post},function(module,exports,__webpack_require__){var hash=exports;hash.utils=__webpack_require__(140),hash.common=__webpack_require__(136),hash.sha=__webpack_require__(139),hash.ripemd=__webpack_require__(138),hash.hmac=__webpack_require__(137),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},function(module,exports,__webpack_require__){"use strict";function Duplex(options){return this instanceof Duplex?(Readable.call(this,options),Writable.call(this,options),options&&options.readable===!1&&(this.readable=!1),options&&options.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,options&&options.allowHalfOpen===!1&&(this.allowHalfOpen=!1),void this.once("end",onend)):new Duplex(options)}function onend(){this.allowHalfOpen||this._writableState.ended||processNextTick(onEndNT,this)}function onEndNT(self){self.end()}var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};module.exports=Duplex;var processNextTick=__webpack_require__(26),util=__webpack_require__(13);util.inherits=__webpack_require__(3);var Readable=__webpack_require__(47),Writable=__webpack_require__(28);util.inherits(Duplex,Readable);for(var keys=objectKeys(Writable.prototype),v=0;v=0&&(item._idleTimeoutId=setTimeout(function(){item._onTimeout&&item._onTimeout()},msecs))},exports.setImmediate="function"==typeof setImmediate?setImmediate:function(fn){var id=nextImmediateId++,args=!(arguments.length<2)&&slice.call(arguments,1);return immediateIds[id]=!0,nextTick(function(){immediateIds[id]&&(args?fn.apply(null,args):fn.call(null),exports.clearImmediate(id))}),id},exports.clearImmediate="function"==typeof clearImmediate?clearImmediate:function(id){delete immediateIds[id]}}).call(exports,__webpack_require__(10).setImmediate,__webpack_require__(10).clearImmediate)},function(module,exports){"use strict";module.exports=function(op,done){function sink(_read){return read=_read,abort?sink.abort():void function next(){for(var loop=!0,cbed=!1;loop;)if(cbed=!1,read(null,function(end,data){if(cbed=!0,end=end||abort){if(loop=!1,done)done(end===!0?null:end);else if(end&&end!==!0)throw end}else op&&!1===op(data)||abort?(loop=!1,read(abort||!0,done||function(){})):loop||next()}),!cbed)return void(loop=!1)}()}var read,abort;return sink.abort=function(err,cb){if("function"==typeof err&&(cb=err,err=!0),abort=err||!0,read)return read(abort,cb||function(){})},sink}},function(module,exports){"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};module.exports=function(key){return key&&("string"==typeof key?function(data){return data[key]}:"object"===("undefined"==typeof key?"undefined":_typeof(key))&&"function"==typeof key.exec?function(data){var v=key.exec(data);return v&&v[0]}:key)}},function(module,exports,__webpack_require__){(function(Buffer){function isArray(arg){return Array.isArray?Array.isArray(arg):"[object Array]"===objectToString(arg)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return"[object Date]"===objectToString(d)} +function isError(e){return"[object Error]"===objectToString(e)||e instanceof Error}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}exports.isArray=isArray,exports.isBoolean=isBoolean,exports.isNull=isNull,exports.isNullOrUndefined=isNullOrUndefined,exports.isNumber=isNumber,exports.isString=isString,exports.isSymbol=isSymbol,exports.isUndefined=isUndefined,exports.isRegExp=isRegExp,exports.isObject=isObject,exports.isDate=isDate,exports.isError=isError,exports.isFunction=isFunction,exports.isPrimitive=isPrimitive,exports.isBuffer=Buffer.isBuffer}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){(function(global,process){function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};return arguments.length>=3&&(ctx.depth=arguments[2]),arguments.length>=4&&(ctx.colors=arguments[3]),isBoolean(opts)?ctx.showHidden=opts:opts&&exports._extend(ctx,opts),isUndefined(ctx.showHidden)&&(ctx.showHidden=!1),isUndefined(ctx.depth)&&(ctx.depth=2),isUndefined(ctx.colors)&&(ctx.colors=!1),isUndefined(ctx.customInspect)&&(ctx.customInspect=!0),ctx.colors&&(ctx.stylize=stylizeWithColor),formatValue(ctx,obj,ctx.depth)}function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];return style?"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m":str}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};return array.forEach(function(val,idx){hash[val]=!0}),hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&(!value.constructor||value.constructor.prototype!==value)){var ret=value.inspect(recurseTimes,ctx);return isString(ret)||(ret=formatValue(ctx,ret,recurseTimes)),ret}var primitive=formatPrimitive(ctx,value);if(primitive)return primitive;var keys=Object.keys(value),visibleKeys=arrayToHash(keys);if(ctx.showHidden&&(keys=Object.getOwnPropertyNames(value)),isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0))return formatError(value);if(0===keys.length){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)}var base="",array=!1,braces=["{","}"];if(isArray(value)&&(array=!0,braces=["[","]"]),isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)&&(base=" "+RegExp.prototype.toString.call(value)),isDate(value)&&(base=" "+Date.prototype.toUTCString.call(value)),isError(value)&&(base=" "+formatError(value)),0===keys.length&&(!array||0==value.length))return braces[0]+base+braces[1];if(recurseTimes<0)return isRegExp(value)?ctx.stylize(RegExp.prototype.toString.call(value),"regexp"):ctx.stylize("[Object]","special");ctx.seen.push(value);var output;return output=array?formatArray(ctx,value,recurseTimes,visibleKeys,keys):keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}),ctx.seen.pop(),reduceToSingleString(output,base,braces)}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")}return isNumber(value)?ctx.stylize(""+value,"number"):isBoolean(value)?ctx.stylize(""+value,"boolean"):isNull(value)?ctx.stylize("null","null"):void 0}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){for(var output=[],i=0,l=value.length;i-1&&(str=array?str.split("\n").map(function(line){return" "+line}).join("\n").substr(2):"\n"+str.split("\n").map(function(line){return" "+line}).join("\n"))):str=ctx.stylize("[Circular]","special")),isUndefined(name)){if(array&&key.match(/^\d+$/))return str;name=JSON.stringify(""+key),name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(name=name.substr(1,name.length-2),name=ctx.stylize(name,"name")):(name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),name=ctx.stylize(name,"string"))}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0,length=output.reduce(function(prev,cur){return numLinesEst++,cur.indexOf("\n")>=0&&numLinesEst++,prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);return length>60?braces[0]+(""===base?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]:braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}function isBoolean(arg){return"boolean"==typeof arg}function isNull(arg){return null===arg}function isNullOrUndefined(arg){return null==arg}function isNumber(arg){return"number"==typeof arg}function isString(arg){return"string"==typeof arg}function isSymbol(arg){return"symbol"==typeof arg}function isUndefined(arg){return void 0===arg}function isRegExp(re){return isObject(re)&&"[object RegExp]"===objectToString(re)}function isObject(arg){return"object"==typeof arg&&null!==arg}function isDate(d){return isObject(d)&&"[object Date]"===objectToString(d)}function isError(e){return isObject(e)&&("[object Error]"===objectToString(e)||e instanceof Error)}function isFunction(arg){return"function"==typeof arg}function isPrimitive(arg){return null===arg||"boolean"==typeof arg||"number"==typeof arg||"string"==typeof arg||"symbol"==typeof arg||"undefined"==typeof arg}function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}function timestamp(){var d=new Date,time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){for(var objects=[],i=0;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}}),x=args[i];i0&&void 0!==arguments[0]?arguments[0]:"./";if("undefined"==typeof localStorage||null===localStorage){var _LocalStorage=__webpack_require__(45).LocalStorage;keystore=new _LocalStorage(directory)}else keystore=localStorage}},{key:"importKeyFromIpfs",value:function(ipfs,hash){var cached=cache.get(hash);return cached?Promise.resolve(cached):ipfs.object.get(hash,{enc:"base58"}).then(function(obj){return JSON.parse(obj.toJSON().data)}).then(function(key){return cache.set(hash,ec.keyFromPublic(key,"hex")),OrbitCrypto.importPublicKey(key)})}},{key:"exportKeyToIpfs",value:function(ipfs,key){var k=key.getPublic("hex"),cached=cache.get(k);return cached?Promise.resolve(cached):OrbitCrypto.exportPublicKey(key).then(function(k){return JSON.stringify(k,null,2)}).then(function(s){return new Buffer(s)}).then(function(buffer){return ipfs.object.put(buffer)}).then(function(res){return cache.set(k,res.toJSON().multihash),res.toJSON().multihash})}},{key:"getKey",value:function(){var id=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default",savedKeys=JSON.parse(keystore.getItem(id)),key=void 0,publicKey=void 0,privateKey=void 0;return savedKeys?OrbitCrypto.importPrivateKey(savedKeys.privateKey).then(function(privKey){return privateKey=privKey}).then(function(){return OrbitCrypto.importPublicKey(savedKeys.publicKey)}).then(function(pubKey){return publicKey=pubKey}).then(function(){return{publicKey:publicKey,privateKey:privateKey}}):OrbitCrypto.generateKey().then(function(keyPair){return key=keyPair}).then(function(){return OrbitCrypto.exportPrivateKey(key)}).then(function(privKey){return privateKey=privKey}).then(function(){return OrbitCrypto.exportPublicKey(key)}).then(function(pubKey){return publicKey=pubKey}).then(function(){return keystore.setItem(id,JSON.stringify({publicKey:publicKey,privateKey:privateKey})),{publicKey:key,privateKey:key}})}},{key:"generateKey",value:function(){return Promise.resolve(ec.genKeyPair())}},{key:"exportPublicKey",value:function(key){return Promise.resolve(key.getPublic("hex"))}},{key:"exportPrivateKey",value:function(key){return Promise.resolve(key.getPrivate("hex"))}},{key:"importPublicKey",value:function(key){return Promise.resolve(ec.keyFromPublic(key,"hex"))}},{key:"importPrivateKey",value:function(key){return Promise.resolve(ec.keyFromPrivate(key,"hex"))}},{key:"sign",value:function(key,data){var sig=ec.sign(data,key);return Promise.resolve(sig.toDER("hex"))}},{key:"verify",value:function(signature,key,data){return Promise.resolve(ec.verify(data,signature,key))}}]),OrbitCrypto}();module.exports=OrbitCrypto}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(process){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=levelIdx}}]),Logger}();module.exports={Colors:Colors,LogLevels:LogLevels,setLogLevel:function(level){GlobalLogLevel=level},setLogfile:function(filename){GlobalLogfile=filename},create:function(category,options){var logger=new Logger(category,options);return logger},forceBrowserMode:function(force){return isNodejs=!force}}}).call(exports,__webpack_require__(1))},function(module,exports){"use strict";function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index3&&void 0!==arguments[3]?arguments[3]:{};_classCallCheck(this,Store),this.id=id,this.dbname=dbname,this.events=new EventEmitter;var opts=Object.assign({},DefaultOptions);Object.assign(opts,options),this.options=opts,this._ipfs=ipfs,this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options),this._lastWrite=[]}return _createClass(Store,[{key:"loadHistory",value:function(hash){var _this=this;return this._lastWrite.includes(hash)?Promise.resolve([]):(hash&&this._lastWrite.push(hash),this.events.emit("load",this.dbname,hash),hash&&this.options.maxHistory>0?Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this._oplog.join(log)}).then(function(merged){_this._index.updateIndex(_this._oplog,merged),_this.events.emit("history",_this.dbname,merged)}).then(function(){return _this.events.emit("ready",_this.dbname)}).then(function(){return _this}):(this.events.emit("ready",this.dbname),Promise.resolve(this)))}},{key:"sync",value:function(hash){var _this2=this;if(!hash||this._lastWrite.includes(hash))return Promise.resolve([]);var newItems=[];hash&&this._lastWrite.push(hash),this.events.emit("sync",this.dbname);(new Date).getTime();return Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this2._oplog.join(log)}).then(function(merged){return newItems=merged}).then(function(){return _this2._index.updateIndex(_this2._oplog,newItems)}).then(function(){newItems.reverse().forEach(function(e){return _this2.events.emit("data",_this2.dbname,e)})}).then(function(){return newItems})}},{key:"close",value:function(){this.delete(),this.events.emit("close",this.dbname)}},{key:"delete",value:function(){this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options)}},{key:"_addOperation",value:function(data){var _this3=this,result=void 0,logHash=void 0;if(this._oplog)return this._oplog.add(data).then(function(res){return result=res}).then(function(){return Log.getIpfsHash(_this3._ipfs,_this3._oplog)}).then(function(hash){return logHash=hash}).then(function(){return _this3._lastWrite.push(logHash)}).then(function(){return _this3._index.updateIndex(_this3._oplog,[result])}).then(function(){return _this3.events.emit("write",_this3.dbname,logHash)}).then(function(){return _this3.events.emit("data",_this3.dbname,result)}).then(function(){return result.hash})}}]),Store}();module.exports=Store},function(module,exports,__webpack_require__){"use strict";var drain=__webpack_require__(11);module.exports=function(reducer,acc,cb){cb||(cb=acc,acc=null);var sink=drain(function(data){acc=reducer(acc,data)},function(err){cb(err,acc)});return 2===arguments.length?function(source){source(null,function(end,data){return end?cb(end===!0?null:end):(acc=data,void sink(source))})}:sink}},function(module,exports,__webpack_require__){"use strict";var abortCb=__webpack_require__(41);module.exports=function(array,onAbort){if(!array)return function(abort,cb){return abort?abortCb(cb,abort,onAbort):cb(!0)};Array.isArray(array)||(array=Object.keys(array).map(function(k){return array[k]}));var i=0;return function(abort,cb){return abort?abortCb(cb,abort,onAbort):void(i>=array.length?cb(!0):cb(null,array[i++]))}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(42);module.exports=function(test){return test=tester(test),function(read){return function next(end,cb){for(var sync,loop=!0;loop;)loop=!1,sync=!0,read(end,function(end,data){return end||test(data)?void cb(end,data):sync?loop=!0:next(end,cb)}),sync=!1}}}},function(module,exports,__webpack_require__){"use strict";(function(global){var buffer=__webpack_require__(0),Buffer=buffer.Buffer,SlowBuffer=buffer.SlowBuffer,MAX_LEN=buffer.kMaxLength||2147483647;exports.alloc=function(size,fill,encoding){if("function"==typeof Buffer.alloc)return Buffer.alloc(size,fill,encoding);if("number"==typeof encoding)throw new TypeError("encoding must not be number");if("number"!=typeof size)throw new TypeError("size must be a number");if(size>MAX_LEN)throw new RangeError("size is too large");var enc=encoding,_fill=fill;void 0===_fill&&(enc=void 0,_fill=0);var buf=new Buffer(size);if("string"==typeof _fill)for(var fillBuf=new Buffer(_fill,enc),flen=fillBuf.length,i=-1;++iMAX_LEN)throw new RangeError("size is too large");return new Buffer(size)},exports.from=function(value,encodingOrOffset,length){if("function"==typeof Buffer.from&&(!global.Uint8Array||Uint8Array.from!==Buffer.from))return Buffer.from(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError('"value" argument must not be a number');if("string"==typeof value)return new Buffer(value,encodingOrOffset);if("undefined"!=typeof ArrayBuffer&&value instanceof ArrayBuffer){var offset=encodingOrOffset;if(1===arguments.length)return new Buffer(value);"undefined"==typeof offset&&(offset=0);var len=length;if("undefined"==typeof len&&(len=value.byteLength-offset),offset>=value.byteLength)throw new RangeError("'offset' is out of bounds");if(len>value.byteLength-offset)throw new RangeError("'length' is out of bounds");return new Buffer(value.slice(offset,offset+len))}if(Buffer.isBuffer(value)){var out=new Buffer(value.length);return value.copy(out,0,0,value.length),out}if(value){if(Array.isArray(value)||"undefined"!=typeof ArrayBuffer&&value.buffer instanceof ArrayBuffer||"length"in value)return new Buffer(value);if("Buffer"===value.type&&Array.isArray(value.data))return new Buffer(value.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},exports.allocUnsafeSlow=function(size){if("function"==typeof Buffer.allocUnsafeSlow)return Buffer.allocUnsafeSlow(size);if("number"!=typeof size)throw new TypeError("size must be a number");if(size>=MAX_LEN)throw new RangeError("size is too large");return new SlowBuffer(size)}}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(process){function nextTick(fn,arg1,arg2,arg3){if("function"!=typeof fn)throw new TypeError('"callback" argument must be a function');var args,i,len=arguments.length;switch(len){case 0:case 1:return process.nextTick(fn);case 2:return process.nextTick(function(){fn.call(null,arg1)});case 3:return process.nextTick(function(){fn.call(null,arg1,arg2)});case 4:return process.nextTick(function(){fn.call(null,arg1,arg2,arg3)});default:for(args=new Array(len-1),i=0;i-1?setImmediate:processNextTick;Writable.WritableState=WritableState;var util=__webpack_require__(13);util.inherits=__webpack_require__(3);var Stream,internalUtil={deprecate:__webpack_require__(154)};!function(){try{Stream=__webpack_require__(17)}catch(_){}finally{Stream||(Stream=__webpack_require__(5).EventEmitter)}}();var Buffer=__webpack_require__(0).Buffer,bufferShim=__webpack_require__(25);util.inherits(Writable,Stream),WritableState.prototype.getBuffer=function(){for(var current=this.bufferedRequest,out=[];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.")})}catch(_){}}();var realHasInstance;"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(realHasInstance=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){return!!realHasInstance.call(this,object)||object&&object._writableState instanceof WritableState}})):realHasInstance=function(object){return object instanceof this},Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState,ret=!1;return"function"==typeof encoding&&(cb=encoding,encoding=null),Buffer.isBuffer(chunk)?encoding="buffer":encoding||(encoding=state.defaultEncoding),"function"!=typeof cb&&(cb=nop),state.ended?writeAfterEnd(this,cb):validChunk(this,state,chunk,cb)&&(state.pendingcb++,ret=writeOrBuffer(this,state,chunk,encoding,cb)),ret},Writable.prototype.cork=function(){var state=this._writableState;state.corked++},Writable.prototype.uncork=function(){var state=this._writableState;state.corked&&(state.corked--,state.writing||state.corked||state.finished||state.bufferProcessing||!state.bufferedRequest||clearBuffer(this,state))},Writable.prototype.setDefaultEncoding=function(encoding){if("string"==typeof encoding&&(encoding=encoding.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);return this._writableState.defaultEncoding=encoding,this},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;"function"==typeof chunk?(cb=chunk,chunk=null,encoding=null):"function"==typeof encoding&&(cb=encoding,encoding=null),null!==chunk&&void 0!==chunk&&this.write(chunk,encoding),state.corked&&(state.corked=1,this.uncork()),state.ending||state.finished||endWritable(this,state,cb)}}).call(exports,__webpack_require__(1),__webpack_require__(10).setImmediate)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var OrbitUser=function OrbitUser(keys,profileData){_classCallCheck(this,OrbitUser),this._keys=keys,this.profile=profileData};module.exports=OrbitUser},function(module,exports,__webpack_require__){function LRU(opts){return this instanceof LRU?("number"==typeof opts&&(opts={max:opts}),opts||(opts={}),events.EventEmitter.call(this),this.cache={},this.head=this.tail=null,this.length=0,this.max=opts.max||1e3,void(this.maxAge=opts.maxAge||0)):new LRU(opts)}var events=__webpack_require__(5),inherits=__webpack_require__(3);module.exports=LRU,inherits(LRU,events.EventEmitter),Object.defineProperty(LRU.prototype,"keys",{get:function(){return Object.keys(this.cache)}}),LRU.prototype.clear=function(){this.cache={},this.head=this.tail=null,this.length=0},LRU.prototype.remove=function(key){if("string"!=typeof key&&(key=""+key),this.cache.hasOwnProperty(key)){var element=this.cache[key];return delete this.cache[key],this._unlink(key,element.prev,element.next),element.value}},LRU.prototype._unlink=function(key,prev,next){this.length--,0===this.length?this.head=this.tail=null:this.head===key?(this.head=prev,this.cache[this.head].next=null):this.tail===key?(this.tail=next,this.cache[this.tail].prev=null):(this.cache[prev].next=next,this.cache[next].prev=prev)},LRU.prototype.peek=function(key){if(this.cache.hasOwnProperty(key)){var element=this.cache[key];if(this._checkAge(key,element))return element.value}},LRU.prototype.set=function(key,value){"string"!=typeof key&&(key=""+key);var element;if(this.cache.hasOwnProperty(key)){if(element=this.cache[key],element.value=value,this.maxAge&&(element.modified=Date.now()),key===this.head)return value;this._unlink(key,element.prev,element.next)}else element={value:value,modified:0,next:null,prev:null},this.maxAge&&(element.modified=Date.now()),this.cache[key]=element,this.length===this.max&&this.evict();return this.length++,element.next=null,element.prev=this.head,this.head&&(this.cache[this.head].next=key),this.head=key,this.tail||(this.tail=key),value},LRU.prototype._checkAge=function(key,element){return!(this.maxAge&&Date.now()-element.modified>this.maxAge)||(this.remove(key),this.emit("evict",{key:key,value:element.value}),!1)},LRU.prototype.get=function(key){if("string"!=typeof key&&(key=""+key),this.cache.hasOwnProperty(key)){var element=this.cache[key];if(this._checkAge(key,element))return this.head!==key&&(key===this.tail?(this.tail=element.next,this.cache[this.tail].prev=null):this.cache[element.prev].next=element.next,this.cache[element.next].prev=element.prev,this.cache[this.head].next=key,element.prev=this.head,element.next=null,this.head=key),element.value}},LRU.prototype.evict=function(){if(this.tail){var key=this.tail,value=this.remove(this.tail);this.emit("evict",{key:key,value:value})}}},function(module,exports,__webpack_require__){(function(process){function normalizeArray(parts,allowAboveRoot){for(var up=0,i=parts.length-1;i>=0;i--){var last=parts[i];"."===last?parts.splice(i,1):".."===last?(parts.splice(i,1),up++):up&&(parts.splice(i,1),up--)}if(allowAboveRoot)for(;up--;up)parts.unshift("..");return parts}function filter(xs,f){if(xs.filter)return xs.filter(f);for(var res=[],i=0;i=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if("string"!=typeof path)throw new TypeError("Arguments to path.resolve must be strings");path&&(resolvedPath=path+"/"+resolvedPath,resolvedAbsolute="/"===path.charAt(0))}return resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/"),(resolvedAbsolute?"/":"")+resolvedPath||"."},exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash="/"===substr(path,-1);return path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/"),path||isAbsolute||(path="."),path&&trailingSlash&&(path+="/"),(isAbsolute?"/":"")+path},exports.isAbsolute=function(path){return"/"===path.charAt(0)},exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if("string"!=typeof p)throw new TypeError("Arguments to path.join must be strings");return p}).join("/"))},exports.relative=function(from,to){function trim(arr){for(var start=0;start=0&&""===arr[end];end--);return start>end?[]:arr.slice(start,end-start+1)}from=exports.resolve(from).substr(1),to=exports.resolve(to).substr(1);for(var fromParts=trim(from.split("/")),toParts=trim(to.split("/")),length=Math.min(fromParts.length,toParts.length),samePartsLength=length,i=0;i0;){var fn=queue.shift();if("function"==typeof fn){var receiver=queue.shift(),arg=queue.shift();fn.call(receiver,arg)}else fn._settlePromises()}},Async.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},Async.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},Async.prototype._reset=function(){this._isTickUsed=!1},module.exports=Async,module.exports.firstLineError=firstLineError},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,tryConvertToPromise,debug){var calledBind=!1,rejectThis=function(_,e){this._reject(e)},targetRejected=function(e,context){context.promiseRejectionQueued=!0,context.bindingPromise._then(rejectThis,rejectThis,null,this,e)},bindingResolved=function(thisArg,context){0===(50397184&this._bitField)&&this._resolveCallback(context.target)},bindingRejected=function(e,context){context.promiseRejectionQueued||this._reject(e)};Promise.prototype.bind=function(thisArg){calledBind||(calledBind=!0,Promise.prototype._propagateFrom=debug.propagateFromFunction(),Promise.prototype._boundValue=debug.boundValueFunction());var maybePromise=tryConvertToPromise(thisArg),ret=new Promise(INTERNAL);ret._propagateFrom(this,1);var target=this._target();if(ret._setBoundTo(maybePromise),maybePromise instanceof Promise){var context={promiseRejectionQueued:!1,promise:ret,target:target,bindingPromise:maybePromise};target._then(INTERNAL,targetRejected,void 0,ret,context),maybePromise._then(bindingResolved,bindingRejected,void 0,ret,context),ret._setOnCancel(maybePromise)}else ret._resolveCallback(target);return ret},Promise.prototype._setBoundTo=function(obj){void 0!==obj?(this._bitField=2097152|this._bitField,this._boundTo=obj):this._bitField=this._bitField&-2097153},Promise.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},Promise.bind=function(thisArg,value){return Promise.resolve(value).bind(thisArg)}}},{}],4:[function(_dereq_,module,exports){function noConflict(){try{Promise===bluebird&&(Promise=old)}catch(e){}return bluebird}var old;"undefined"!=typeof Promise&&(old=Promise);var bluebird=_dereq_("./promise")();bluebird.noConflict=noConflict,module.exports=bluebird},{"./promise":22}],5:[function(_dereq_,module,exports){var cr=Object.create;if(cr){var callerCache=cr(null),getterCache=cr(null);callerCache[" size"]=getterCache[" size"]=0}module.exports=function(Promise){function ensureMethod(obj,methodName){var fn;if(null!=obj&&(fn=obj[methodName]),"function"!=typeof fn){var message="Object "+util.classString(obj)+" has no method '"+util.toString(methodName)+"'";throw new Promise.TypeError(message)}return fn}function caller(obj){var methodName=this.pop(),fn=ensureMethod(obj,methodName);return fn.apply(obj,this)}function namedGetter(obj){return obj[this]}function indexedGetter(obj){var index=+this;return index<0&&(index=Math.max(0,index+obj.length)),obj[index]}var getGetter,util=_dereq_("./util"),canEvaluate=util.canEvaluate;util.isIdentifier;Promise.prototype.call=function(methodName){var args=[].slice.call(arguments,1);return args.push(methodName),this._then(caller,void 0,void 0,args,void 0)},Promise.prototype.get=function(propertyName){var getter,isIndex="number"==typeof propertyName;if(isIndex)getter=indexedGetter;else if(canEvaluate){var maybeGetter=getGetter(propertyName);getter=null!==maybeGetter?maybeGetter:namedGetter}else getter=namedGetter;return this._then(getter,void 0,void 0,propertyName,void 0)}}},{"./util":36}],6:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection,debug){var util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;Promise.prototype.break=Promise.prototype.cancel=function(){if(!debug.cancellation())return this._warn("cancellation is disabled");for(var promise=this,child=promise;promise._isCancellable();){if(!promise._cancelBy(child)){child._isFollowing()?child._followee().cancel():child._cancelBranched();break}var parent=promise._cancellationParent;if(null==parent||!parent._isCancellable()){promise._isFollowing()?promise._followee().cancel():promise._cancelBranched();break}promise._isFollowing()&&promise._followee().cancel(),promise._setWillBeCancelled(),child=promise,promise=parent}},Promise.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},Promise.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},Promise.prototype._cancelBy=function(canceller){return canceller===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},Promise.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},Promise.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),async.invoke(this._cancelPromises,this,void 0))},Promise.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},Promise.prototype._unsetOnCancel=function(){this._onCancelField=void 0},Promise.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},Promise.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},Promise.prototype._doInvokeOnCancel=function(onCancelCallback,internalOnly){if(util.isArray(onCancelCallback))for(var i=0;i=0)return contextStack[lastIndex]}var longStackTraces=!1,contextStack=[];return Promise.prototype._promiseCreated=function(){},Promise.prototype._pushContext=function(){},Promise.prototype._popContext=function(){return null},Promise._peekContext=Promise.prototype._peekContext=function(){},Context.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,contextStack.push(this._trace))},Context.prototype._popContext=function(){if(void 0!==this._trace){var trace=contextStack.pop(),ret=trace._promiseCreated;return trace._promiseCreated=null,ret}return null},Context.CapturedTrace=null,Context.create=createContext,Context.deactivateLongStackTraces=function(){},Context.activateLongStackTraces=function(){var Promise_pushContext=Promise.prototype._pushContext,Promise_popContext=Promise.prototype._popContext,Promise_PeekContext=Promise._peekContext,Promise_peekContext=Promise.prototype._peekContext,Promise_promiseCreated=Promise.prototype._promiseCreated;Context.deactivateLongStackTraces=function(){Promise.prototype._pushContext=Promise_pushContext,Promise.prototype._popContext=Promise_popContext,Promise._peekContext=Promise_PeekContext,Promise.prototype._peekContext=Promise_peekContext,Promise.prototype._promiseCreated=Promise_promiseCreated,longStackTraces=!1},longStackTraces=!0,Promise.prototype._pushContext=Context.prototype._pushContext,Promise.prototype._popContext=Context.prototype._popContext,Promise._peekContext=Promise.prototype._peekContext=peekContext,Promise.prototype._promiseCreated=function(){var ctx=this._peekContext();ctx&&null==ctx._promiseCreated&&(ctx._promiseCreated=this)}},Context}},{}],9:[function(_dereq_,module,exports){module.exports=function(Promise,Context){function generatePromiseLifecycleEventObject(name,promise){return{promise:promise}}function defaultFireEvent(){return!1}function cancellationExecute(executor,resolve,reject){var promise=this;try{executor(resolve,reject,function(onCancel){if("function"!=typeof onCancel)throw new TypeError("onCancel must be a function, got: "+util.toString(onCancel));promise._attachCancellationCallback(onCancel)})}catch(e){return e}}function cancellationAttachCancellationCallback(onCancel){if(!this._isCancellable())return this;var previousOnCancel=this._onCancel();void 0!==previousOnCancel?util.isArray(previousOnCancel)?previousOnCancel.push(onCancel):this._setOnCancel([previousOnCancel,onCancel]):this._setOnCancel(onCancel)}function cancellationOnCancel(){return this._onCancelField}function cancellationSetOnCancel(onCancel){this._onCancelField=onCancel}function cancellationClearCancellationData(){this._cancellationParent=void 0,this._onCancelField=void 0}function cancellationPropagateFrom(parent,flags){if(0!==(1&flags)){this._cancellationParent=parent;var branchesRemainingToCancel=parent._branchesRemainingToCancel;void 0===branchesRemainingToCancel&&(branchesRemainingToCancel=0),parent._branchesRemainingToCancel=branchesRemainingToCancel+1}0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function bindingPropagateFrom(parent,flags){0!==(2&flags)&&parent._isBound()&&this._setBoundTo(parent._boundTo)}function _boundValueFunction(){var ret=this._boundTo;return void 0!==ret&&ret instanceof Promise?ret.isFulfilled()?ret.value():void 0:ret}function longStackTracesCaptureStackTrace(){this._trace=new CapturedTrace(this._peekContext())}function longStackTracesAttachExtraTrace(error,ignoreSelf){if(canAttachTrace(error)){var trace=this._trace;if(void 0!==trace&&ignoreSelf&&(trace=trace._parent),void 0!==trace)trace.attachExtraTrace(error);else if(!error.__stackCleaned__){var parsed=parseStackAndMessage(error);util.notEnumerableProp(error,"stack",parsed.message+"\n"+parsed.stack.join("\n")),util.notEnumerableProp(error,"__stackCleaned__",!0)}}}function checkForgottenReturns(returnValue,promiseCreated,name,promise,parent){if(void 0===returnValue&&null!==promiseCreated&&wForgottenReturn){if(void 0!==parent&&parent._returnedNonUndefined())return;if(0===(65535&promise._bitField))return;name&&(name+=" ");var handlerLine="",creatorLine="";if(promiseCreated._trace){for(var traceLines=promiseCreated._trace.stack.split("\n"),stack=cleanStack(traceLines),i=stack.length-1;i>=0;--i){var line=stack[i];if(!nodeFramePattern.test(line)){var lineMatches=line.match(parseLinePattern);lineMatches&&(handlerLine="at "+lineMatches[1]+":"+lineMatches[2]+":"+lineMatches[3]+" ");break}}if(stack.length>0)for(var firstUserLine=stack[0],i=0;i0&&(creatorLine="\n"+traceLines[i-1]);break}}var msg="a promise was created in a "+name+"handler "+handlerLine+"but was not returned from it, see http://goo.gl/rRqMUw"+creatorLine;promise._warn(msg,!0,promiseCreated)}}function deprecated(name,replacement){var message=name+" is deprecated and will be removed in a future version.";return replacement&&(message+=" Use "+replacement+" instead."),warn(message)}function warn(message,shouldUseOwnTrace,promise){if(config.warnings){var ctx,warning=new Warning(message);if(shouldUseOwnTrace)promise._attachExtraTrace(warning);else if(config.longStackTraces&&(ctx=Promise._peekContext()))ctx.attachExtraTrace(warning);else{var parsed=parseStackAndMessage(warning);warning.stack=parsed.message+"\n"+parsed.stack.join("\n")}activeFireEvent("warning",warning)||formatAndLogError(warning,"",!0)}}function reconstructStack(message,stacks){for(var i=0;i=0;--j)if(prev[j]===currentLastLine){commonRootMeetPoint=j;break}for(var j=commonRootMeetPoint;j>=0;--j){var line=prev[j];if(current[currentLastIndex]!==line)break;current.pop(),currentLastIndex--}current=prev}}function cleanStack(stack){for(var ret=[],i=0;i0&&(stack=stack.slice(i)),stack}function parseStackAndMessage(error){var stack=error.stack,message=error.toString();return stack="string"==typeof stack&&stack.length>0?stackFramesAsArray(error):[" (No stack trace)"],{message:message,stack:cleanStack(stack)}}function formatAndLogError(error,title,isSoft){if("undefined"!=typeof console){var message;if(util.isObject(error)){var stack=error.stack;message=title+formatStack(stack,error)}else message=title+String(error);"function"==typeof printWarning?printWarning(message,isSoft):"function"!=typeof console.log&&"object"!==_typeof(console.log)||console.log(message)}}function fireRejectionEvent(name,localHandler,reason,promise){var localEventFired=!1;try{"function"==typeof localHandler&&(localEventFired=!0,"rejectionHandled"===name?localHandler(promise):localHandler(reason,promise))}catch(e){async.throwLater(e)}"unhandledRejection"===name?activeFireEvent(name,reason,promise)||localEventFired||formatAndLogError(reason,"Unhandled rejection "):activeFireEvent(name,promise)}function formatNonError(obj){var str;if("function"==typeof obj)str="[function "+(obj.name||"anonymous")+"]";else{str=obj&&"function"==typeof obj.toString?obj.toString():util.toString(obj);var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str))try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}0===str.length&&(str="(empty array)")}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;return str.length=lastIndex||(shouldIgnore=function(line){if(bluebirdFramePattern.test(line))return!0;var info=parseLineInfo(line);return!!(info&&info.fileName===firstFileName&&firstIndex<=info.line&&info.line<=lastIndex)})}}function CapturedTrace(parent){this._parent=parent,this._promisesCreated=0;var length=this._length=1+(void 0===parent?0:parent._length);captureStackTrace(this,CapturedTrace),length>32&&this.uncycle()}var unhandledRejectionHandled,possiblyUnhandledRejection,printWarning,getDomain=Promise._getDomain,async=Promise._async,Warning=_dereq_("./errors").Warning,util=_dereq_("./util"),canAttachTrace=util.canAttachTrace,bluebirdFramePattern=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,nodeFramePattern=/\((?:timers\.js):\d+:\d+\)/,parseLinePattern=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,stackFramePattern=null,formatStack=null,indentStackFrames=!1,debugging=!(0==util.env("BLUEBIRD_DEBUG")),warnings=!(0==util.env("BLUEBIRD_WARNINGS")||!debugging&&!util.env("BLUEBIRD_WARNINGS")),longStackTraces=!(0==util.env("BLUEBIRD_LONG_STACK_TRACES")||!debugging&&!util.env("BLUEBIRD_LONG_STACK_TRACES")),wForgottenReturn=0!=util.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(warnings||!!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));Promise.prototype.suppressUnhandledRejections=function(){var target=this._target();target._bitField=target._bitField&-1048577|524288},Promise.prototype._ensurePossibleRejectionHandled=function(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),async.invokeLater(this._notifyUnhandledRejection,this,void 0))},Promise.prototype._notifyUnhandledRejectionIsHandled=function(){fireRejectionEvent("rejectionHandled",unhandledRejectionHandled,void 0,this)},Promise.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},Promise.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},Promise.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var reason=this._settledValue();this._setUnhandledRejectionIsNotified(),fireRejectionEvent("unhandledRejection",possiblyUnhandledRejection,reason,this)}},Promise.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},Promise.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=this._bitField&-262145},Promise.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},Promise.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},Promise.prototype._unsetRejectionIsUnhandled=function(){this._bitField=this._bitField&-1048577,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},Promise.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},Promise.prototype._warn=function(message,shouldUseOwnTrace,promise){return warn(message,shouldUseOwnTrace,promise||this)},Promise.onPossiblyUnhandledRejection=function(fn){var domain=getDomain();possiblyUnhandledRejection="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0},Promise.onUnhandledRejectionHandled=function(fn){var domain=getDomain();unhandledRejectionHandled="function"==typeof fn?null===domain?fn:util.domainBind(domain,fn):void 0};var disableLongStackTraces=function(){};Promise.longStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!config.longStackTraces&&longStackTracesIsSupported()){var Promise_captureStackTrace=Promise.prototype._captureStackTrace,Promise_attachExtraTrace=Promise.prototype._attachExtraTrace;config.longStackTraces=!0,disableLongStackTraces=function(){if(async.haveItemsQueued()&&!config.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");Promise.prototype._captureStackTrace=Promise_captureStackTrace,Promise.prototype._attachExtraTrace=Promise_attachExtraTrace,Context.deactivateLongStackTraces(),async.enableTrampoline(),config.longStackTraces=!1},Promise.prototype._captureStackTrace=longStackTracesCaptureStackTrace,Promise.prototype._attachExtraTrace=longStackTracesAttachExtraTrace,Context.activateLongStackTraces(),async.disableTrampolineIfNecessary()}},Promise.hasLongStackTraces=function(){return config.longStackTraces&&longStackTracesIsSupported()};var fireDomEvent=function(){try{if("function"==typeof CustomEvent){var event=new CustomEvent("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new CustomEvent(name.toLowerCase(),{detail:event,cancelable:!0});return!util.global.dispatchEvent(domEvent)}}if("function"==typeof Event){var event=new Event("CustomEvent");return util.global.dispatchEvent(event),function(name,event){var domEvent=new Event(name.toLowerCase(),{cancelable:!0});return domEvent.detail=event,!util.global.dispatchEvent(domEvent)}}var event=document.createEvent("CustomEvent");return event.initCustomEvent("testingtheevent",!1,!0,{}),util.global.dispatchEvent(event),function(name,event){var domEvent=document.createEvent("CustomEvent");return domEvent.initCustomEvent(name.toLowerCase(),!1,!0,event),!util.global.dispatchEvent(domEvent)}}catch(e){}return function(){return!1}}(),fireGlobalEvent=function(){return util.isNode?function(){return process.emit.apply(process,arguments)}:util.global?function(name){var methodName="on"+name.toLowerCase(),method=util.global[methodName];return!!method&&(method.apply(util.global,[].slice.call(arguments,1)),!0)}:function(){return!1}}(),eventToObjectGenerator={promiseCreated:generatePromiseLifecycleEventObject,promiseFulfilled:generatePromiseLifecycleEventObject,promiseRejected:generatePromiseLifecycleEventObject,promiseResolved:generatePromiseLifecycleEventObject,promiseCancelled:generatePromiseLifecycleEventObject,promiseChained:function(name,promise,child){return{promise:promise,child:child}},warning:function(name,_warning){return{warning:_warning}},unhandledRejection:function(name,reason,promise){return{reason:reason,promise:promise}},rejectionHandled:generatePromiseLifecycleEventObject},activeFireEvent=function(name){var globalEventFired=!1;try{globalEventFired=fireGlobalEvent.apply(null,arguments)}catch(e){async.throwLater(e),globalEventFired=!0}var domEventFired=!1;try{domEventFired=fireDomEvent(name,eventToObjectGenerator[name].apply(null,arguments))}catch(e){async.throwLater(e),domEventFired=!0}return domEventFired||globalEventFired};Promise.config=function(opts){if(opts=Object(opts),"longStackTraces"in opts&&(opts.longStackTraces?Promise.longStackTraces():!opts.longStackTraces&&Promise.hasLongStackTraces()&&disableLongStackTraces()),"warnings"in opts){var warningsOption=opts.warnings;config.warnings=!!warningsOption,wForgottenReturn=config.warnings,util.isObject(warningsOption)&&"wForgottenReturn"in warningsOption&&(wForgottenReturn=!!warningsOption.wForgottenReturn)}if("cancellation"in opts&&opts.cancellation&&!config.cancellation){if(async.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");Promise.prototype._clearCancellationData=cancellationClearCancellationData,Promise.prototype._propagateFrom=cancellationPropagateFrom,Promise.prototype._onCancel=cancellationOnCancel,Promise.prototype._setOnCancel=cancellationSetOnCancel,Promise.prototype._attachCancellationCallback=cancellationAttachCancellationCallback,Promise.prototype._execute=cancellationExecute,_propagateFromFunction=cancellationPropagateFrom,config.cancellation=!0}"monitoring"in opts&&(opts.monitoring&&!config.monitoring?(config.monitoring=!0,Promise.prototype._fireEvent=activeFireEvent):!opts.monitoring&&config.monitoring&&(config.monitoring=!1,Promise.prototype._fireEvent=defaultFireEvent))},Promise.prototype._fireEvent=defaultFireEvent,Promise.prototype._execute=function(executor,resolve,reject){try{executor(resolve,reject)}catch(e){return e}},Promise.prototype._onCancel=function(){},Promise.prototype._setOnCancel=function(handler){},Promise.prototype._attachCancellationCallback=function(onCancel){},Promise.prototype._captureStackTrace=function(){},Promise.prototype._attachExtraTrace=function(){},Promise.prototype._clearCancellationData=function(){},Promise.prototype._propagateFrom=function(parent,flags){};var _propagateFromFunction=bindingPropagateFrom,shouldIgnore=function(){return!1},parseLineInfoRegex=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;util.inherits(CapturedTrace,Error),Context.CapturedTrace=CapturedTrace,CapturedTrace.prototype.uncycle=function(){var length=this._length;if(!(length<2)){for(var nodes=[],stackToIndex={},i=0,node=this;void 0!==node;++i)nodes.push(node),node=node._parent;length=this._length=i;for(var i=length-1;i>=0;--i){var stack=nodes[i].stack;void 0===stackToIndex[stack]&&(stackToIndex[stack]=i)}for(var i=0;i0&&(nodes[index-1]._parent=void 0,nodes[index-1]._length=1),nodes[i]._parent=void 0,nodes[i]._length=1;var cycleEdgeNode=i>0?nodes[i-1]:this;index=0;--j)nodes[j]._length=currentChildLength,currentChildLength++;return}}}},CapturedTrace.prototype.attachExtraTrace=function(error){if(!error.__stackCleaned__){this.uncycle();for(var parsed=parseStackAndMessage(error),message=parsed.message,stacks=[parsed.stack],trace=this;void 0!==trace;)stacks.push(cleanStack(trace.stack.split("\n"))),trace=trace._parent;removeCommonRoots(stacks),removeDuplicateOrEmptyJumps(stacks),util.notEnumerableProp(error,"stack",reconstructStack(message,stacks)),util.notEnumerableProp(error,"__stackCleaned__",!0)}};var captureStackTrace=function(){var v8stackFramePattern=/^\s*at\s*/,v8stackFormatter=function(stack,error){return"string"==typeof stack?stack:void 0!==error.name&&void 0!==error.message?error.toString():formatNonError(error)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter;var captureStackTrace=Error.captureStackTrace;return shouldIgnore=function(line){return bluebirdFramePattern.test(line)},function(receiver,ignoreUntil){Error.stackTraceLimit+=6,captureStackTrace(receiver,ignoreUntil),Error.stackTraceLimit-=6}}var err=new Error;if("string"==typeof err.stack&&err.stack.split("\n")[0].indexOf("stackDetection@")>=0)return stackFramePattern=/@/,formatStack=v8stackFormatter,indentStackFrames=!0,function(o){o.stack=(new Error).stack};var hasStackAfterThrow;try{throw new Error}catch(e){hasStackAfterThrow="stack"in e}return"stack"in err||!hasStackAfterThrow||"number"!=typeof Error.stackTraceLimit?(formatStack=function(stack,error){return"string"==typeof stack?stack:"object"!==("undefined"==typeof error?"undefined":_typeof(error))&&"function"!=typeof error||void 0===error.name||void 0===error.message?formatNonError(error):error.toString()},null):(stackFramePattern=v8stackFramePattern,formatStack=v8stackFormatter,function(o){Error.stackTraceLimit+=6;try{throw new Error}catch(e){o.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(printWarning=function(message){console.warn(message)},util.isNode&&process.stderr.isTTY?printWarning=function(message,isSoft){ +var color=isSoft?"":"";console.warn(color+message+"\n")}:util.isNode||"string"!=typeof(new Error).stack||(printWarning=function(message,isSoft){console.warn("%c"+message,isSoft?"color: darkorange":"color: red")}));var config={warnings:warnings,longStackTraces:!1,cancellation:!1,monitoring:!1};return longStackTraces&&Promise.longStackTraces(),{longStackTraces:function(){return config.longStackTraces},warnings:function(){return config.warnings},cancellation:function(){return config.cancellation},monitoring:function(){return config.monitoring},propagateFromFunction:function(){return _propagateFromFunction},boundValueFunction:function(){return _boundValueFunction},checkForgottenReturns:checkForgottenReturns,setBounds:setBounds,warn:warn,deprecated:deprecated,CapturedTrace:CapturedTrace,fireDomEvent:fireDomEvent,fireGlobalEvent:fireGlobalEvent}}},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){module.exports=function(Promise){function returner(){return this.value}function thrower(){throw this.reason}Promise.prototype.return=Promise.prototype.thenReturn=function(value){return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(returner,void 0,void 0,{value:value},void 0)},Promise.prototype.throw=Promise.prototype.thenThrow=function(reason){return this._then(thrower,void 0,void 0,{reason:reason},void 0)},Promise.prototype.catchThrow=function(reason){if(arguments.length<=1)return this._then(void 0,thrower,void 0,{reason:reason},void 0);var _reason=arguments[1],handler=function(){throw _reason};return this.caught(reason,handler)},Promise.prototype.catchReturn=function(value){if(arguments.length<=1)return value instanceof Promise&&value.suppressUnhandledRejections(),this._then(void 0,returner,void 0,{value:value},void 0);var _value=arguments[1];_value instanceof Promise&&_value.suppressUnhandledRejections();var handler=function(){return _value};return this.caught(value,handler)}}},{}],11:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL){function promiseAllThis(){return PromiseAll(this)}function PromiseMapSeries(promises,fn){return PromiseReduce(promises,fn,INTERNAL,INTERNAL)}var PromiseReduce=Promise.reduce,PromiseAll=Promise.all;Promise.prototype.each=function(fn){return PromiseReduce(this,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,this,void 0)},Promise.prototype.mapSeries=function(fn){return PromiseReduce(this,fn,INTERNAL,INTERNAL)},Promise.each=function(promises,fn){return PromiseReduce(promises,fn,INTERNAL,0)._then(promiseAllThis,void 0,void 0,promises,void 0)},Promise.mapSeries=PromiseMapSeries}},{}],12:[function(_dereq_,module,exports){function subError(nameProperty,defaultMessage){function SubError(message){return this instanceof SubError?(notEnumerableProp(this,"message","string"==typeof message?message:defaultMessage),notEnumerableProp(this,"name",nameProperty),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new SubError(message)}return inherits(SubError,Error),SubError}function OperationalError(message){return this instanceof OperationalError?(notEnumerableProp(this,"name","OperationalError"),notEnumerableProp(this,"message",message),this.cause=message,this.isOperational=!0,void(message instanceof Error?(notEnumerableProp(this,"message",message.message),notEnumerableProp(this,"stack",message.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new OperationalError(message)}var _TypeError,_RangeError,es5=_dereq_("./es5"),Objectfreeze=es5.freeze,util=_dereq_("./util"),inherits=util.inherits,notEnumerableProp=util.notEnumerableProp,Warning=subError("Warning","warning"),CancellationError=subError("CancellationError","cancellation error"),TimeoutError=subError("TimeoutError","timeout error"),AggregateError=subError("AggregateError","aggregate error");try{_TypeError=TypeError,_RangeError=RangeError}catch(e){_TypeError=subError("TypeError","type error"),_RangeError=subError("RangeError","range error")}for(var methods="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),i=0;i1?ctx.cancelPromise._reject(reason):ctx.cancelPromise._cancel(),ctx.cancelPromise=null,!0)}function succeed(){return finallyHandler.call(this,this.promise._target()._settledValue())}function fail(reason){if(!checkCancel(this,reason))return errorObj.e=reason,errorObj}function finallyHandler(reasonOrValue){var promise=this.promise,handler=this.handler;if(!this.called){this.called=!0;var ret=this.isFinallyHandler()?handler.call(promise._boundValue()):handler.call(promise._boundValue(),reasonOrValue);if(void 0!==ret){promise._setReturnedNonUndefined();var maybePromise=tryConvertToPromise(ret,promise);if(maybePromise instanceof Promise){if(null!=this.cancelPromise){if(maybePromise._isCancelled()){var reason=new CancellationError("late cancellation observer");return promise._attachExtraTrace(reason),errorObj.e=reason,errorObj}maybePromise.isPending()&&maybePromise._attachCancellationCallback(new FinallyHandlerCancelReaction(this))}return maybePromise._then(succeed,fail,void 0,this,void 0)}}}return promise.isRejected()?(checkCancel(this),errorObj.e=reasonOrValue,errorObj):(checkCancel(this),reasonOrValue)}var util=_dereq_("./util"),CancellationError=Promise.CancellationError,errorObj=util.errorObj;return PassThroughHandlerContext.prototype.isFinallyHandler=function(){return 0===this.type},FinallyHandlerCancelReaction.prototype._resultCancelled=function(){checkCancel(this.finallyHandler)},Promise.prototype._passThrough=function(handler,type,success,fail){return"function"!=typeof handler?this.then():this._then(success,fail,void 0,new PassThroughHandlerContext(this,type,handler),void 0)},Promise.prototype.lastly=Promise.prototype.finally=function(handler){return this._passThrough(handler,0,finallyHandler,finallyHandler)},Promise.prototype.tap=function(handler){return this._passThrough(handler,1,finallyHandler)},PassThroughHandlerContext}},{"./util":36}],16:[function(_dereq_,module,exports){module.exports=function(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug){function promiseFromYieldHandler(value,yieldHandlers,traceParent){for(var i=0;i0&&"function"==typeof arguments[last]){fn=arguments[last];var ret}var args=[].slice.call(arguments);fn&&args.pop();var ret=new PromiseArray(args).promise();return void 0!==fn?ret.spread(fn):ret}}},{"./util":36}],18:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug){function MappingPromiseArray(promises,fn,limit,_filter){this.constructor$(promises),this._promise._captureStackTrace();var domain=getDomain();this._callback=null===domain?fn:util.domainBind(domain,fn),this._preservedValues=_filter===INTERNAL?new Array(this.length()):null,this._limit=limit,this._inFlight=0,this._queue=[],async.invoke(this._asyncInit,this,void 0)}function map(promises,fn,options,_filter){if("function"!=typeof fn)return apiRejection("expecting a function but got "+util.classString(fn));var limit=0;if(void 0!==options){if("object"!==("undefined"==typeof options?"undefined":_typeof(options))||null===options)return Promise.reject(new TypeError("options argument must be an object but it is "+util.classString(options)));if("number"!=typeof options.concurrency)return Promise.reject(new TypeError("'concurrency' must be a number but it is "+util.classString(options.concurrency)));limit=options.concurrency}return limit="number"==typeof limit&&isFinite(limit)&&limit>=1?limit:0,new MappingPromiseArray(promises,fn,limit,_filter).promise()}var getDomain=Promise._getDomain,util=_dereq_("./util"),tryCatch=util.tryCatch,errorObj=util.errorObj,async=Promise._async;util.inherits(MappingPromiseArray,PromiseArray),MappingPromiseArray.prototype._asyncInit=function(){this._init$(void 0,-2)},MappingPromiseArray.prototype._init=function(){},MappingPromiseArray.prototype._promiseFulfilled=function(value,index){var values=this._values,length=this.length(),preservedValues=this._preservedValues,limit=this._limit;if(index<0){if(index=index*-1-1,values[index]=value,limit>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(limit>=1&&this._inFlight>=limit)return values[index]=value,this._queue.push(index),!1;null!==preservedValues&&(preservedValues[index]=value);var promise=this._promise,callback=this._callback,receiver=promise._boundValue();promise._pushContext();var ret=tryCatch(callback).call(receiver,value,index,length),promiseCreated=promise._popContext();if(debug.checkForgottenReturns(ret,promiseCreated,null!==preservedValues?"Promise.filter":"Promise.map",promise),ret===errorObj)return this._reject(ret.e),!0;var maybePromise=tryConvertToPromise(ret,this._promise);if(maybePromise instanceof Promise){maybePromise=maybePromise._target();var bitField=maybePromise._bitField;if(0===(50397184&bitField))return limit>=1&&this._inFlight++,values[index]=maybePromise,maybePromise._proxy(this,(index+1)*-1),!1;if(0===(33554432&bitField))return 0!==(16777216&bitField)?(this._reject(maybePromise._reason()),!0):(this._cancel(),!0);ret=maybePromise._value()}values[index]=ret}var totalResolved=++this._totalResolved;return totalResolved>=length&&(null!==preservedValues?this._filter(values,preservedValues):this._resolve(values),!0)},MappingPromiseArray.prototype._drainQueue=function(){for(var queue=this._queue,limit=this._limit,values=this._values;queue.length>0&&this._inFlight1){debug.deprecated("calling Promise.try with more than 1 argument");var arg=arguments[1],ctx=arguments[2];value=util.isArray(arg)?tryCatch(fn).apply(ctx,arg):tryCatch(fn).call(ctx,arg)}else value=tryCatch(fn)();var promiseCreated=ret._popContext();return debug.checkForgottenReturns(value,promiseCreated,"Promise.try",ret),ret._resolveFromSyncValue(value),ret},Promise.prototype._resolveFromSyncValue=function(value){value===util.errorObj?this._rejectCallback(value.e,!1):this._resolveCallback(value,!0)}}},{"./util":36}],20:[function(_dereq_,module,exports){function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}function wrapAsOperationalError(obj){var ret;if(isUntypedError(obj)){ret=new OperationalError(obj),ret.name=obj.name,ret.message=obj.message,ret.stack=obj.stack;for(var keys=es5.keys(obj),i=0;i1){var i,catchInstances=new Array(len-1),j=0;for(i=0;i0&&"function"!=typeof didFulfill&&"function"!=typeof didReject){var msg=".then() only accepts functions but was passed: "+util.classString(didFulfill);arguments.length>1&&(msg+=", "+util.classString(didReject)),this._warn(msg)}return this._then(didFulfill,didReject,void 0,void 0,void 0)},Promise.prototype.done=function(didFulfill,didReject){var promise=this._then(didFulfill,didReject,void 0,void 0,void 0);promise._setIsFinal()},Promise.prototype.spread=function(fn){return"function"!=typeof fn?apiRejection("expecting a function but got "+util.classString(fn)):this.all()._then(fn,void 0,void 0,APPLY,void 0)},Promise.prototype.toJSON=function(){var ret={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(ret.fulfillmentValue=this.value(),ret.isFulfilled=!0):this.isRejected()&&(ret.rejectionReason=this.reason(),ret.isRejected=!0),ret},Promise.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new PromiseArray(this).promise()},Promise.prototype.error=function(fn){return this.caught(util.originatesFromRejection,fn)},Promise.getNewLibraryCopy=module.exports,Promise.is=function(val){return val instanceof Promise},Promise.fromNode=Promise.fromCallback=function(fn){var ret=new Promise(INTERNAL);ret._captureStackTrace();var multiArgs=arguments.length>1&&!!Object(arguments[1]).multiArgs,result=tryCatch(fn)(nodebackForPromise(ret,multiArgs));return result===errorObj&&ret._rejectCallback(result.e,!0),ret._isFateSealed()||ret._setAsyncGuaranteed(),ret},Promise.all=function(promises){return new PromiseArray(promises).promise()},Promise.cast=function(obj){var ret=tryConvertToPromise(obj);return ret instanceof Promise||(ret=new Promise(INTERNAL),ret._captureStackTrace(),ret._setFulfilled(),ret._rejectionHandler0=obj),ret},Promise.resolve=Promise.fulfilled=Promise.cast,Promise.reject=Promise.rejected=function(reason){var ret=new Promise(INTERNAL);return ret._captureStackTrace(),ret._rejectCallback(reason,!0),ret},Promise.setScheduler=function(fn){if("function"!=typeof fn)throw new TypeError("expecting a function but got "+util.classString(fn));return async.setScheduler(fn)},Promise.prototype._then=function(didFulfill,didReject,_,receiver,internalData){var haveInternalData=void 0!==internalData,promise=haveInternalData?internalData:new Promise(INTERNAL),target=this._target(),bitField=target._bitField;haveInternalData||(promise._propagateFrom(this,3),promise._captureStackTrace(),void 0===receiver&&0!==(2097152&this._bitField)&&(receiver=0!==(50397184&bitField)?this._boundValue():target===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,promise));var domain=getDomain();if(0!==(50397184&bitField)){var handler,value,settler=target._settlePromiseCtx;0!==(33554432&bitField)?(value=target._rejectionHandler0,handler=didFulfill):0!==(16777216&bitField)?(value=target._fulfillmentHandler0,handler=didReject,target._unsetRejectionIsUnhandled()):(settler=target._settlePromiseLateCancellationObserver,value=new CancellationError("late cancellation observer"),target._attachExtraTrace(value),handler=didReject),async.invoke(settler,target,{handler:null===domain?handler:"function"==typeof handler&&util.domainBind(domain,handler),promise:promise,receiver:receiver,value:value})}else target._addCallbacks(didFulfill,didReject,promise,receiver,domain);return promise},Promise.prototype._length=function(){return 65535&this._bitField},Promise.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},Promise.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},Promise.prototype._setLength=function(len){this._bitField=this._bitField&-65536|65535&len},Promise.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},Promise.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},Promise.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},Promise.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},Promise.prototype._isFinal=function(){return(4194304&this._bitField)>0},Promise.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},Promise.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},Promise.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},Promise.prototype._setAsyncGuaranteed=function(){async.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},Promise.prototype._receiverAt=function(index){var ret=0===index?this._receiver0:this[4*index-4+3];if(ret!==UNDEFINED_BINDING)return void 0===ret&&this._isBound()?this._boundValue():ret},Promise.prototype._promiseAt=function(index){return this[4*index-4+2]},Promise.prototype._fulfillmentHandlerAt=function(index){return this[4*index-4+0]},Promise.prototype._rejectionHandlerAt=function(index){return this[4*index-4+1]},Promise.prototype._boundValue=function(){},Promise.prototype._migrateCallback0=function(follower){var fulfill=(follower._bitField,follower._fulfillmentHandler0),reject=follower._rejectionHandler0,promise=follower._promise0,receiver=follower._receiverAt(0);void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,promise,receiver,null)},Promise.prototype._migrateCallbackAt=function(follower,index){var fulfill=follower._fulfillmentHandlerAt(index),reject=follower._rejectionHandlerAt(index),promise=follower._promiseAt(index),receiver=follower._receiverAt(index);void 0===receiver&&(receiver=UNDEFINED_BINDING),this._addCallbacks(fulfill,reject,promise,receiver,null)},Promise.prototype._addCallbacks=function(fulfill,reject,promise,receiver,domain){var index=this._length();if(index>=65531&&(index=0,this._setLength(0)),0===index)this._promise0=promise,this._receiver0=receiver,"function"==typeof fulfill&&(this._fulfillmentHandler0=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this._rejectionHandler0=null===domain?reject:util.domainBind(domain,reject));else{ +var base=4*index-4;this[base+2]=promise,this[base+3]=receiver,"function"==typeof fulfill&&(this[base+0]=null===domain?fulfill:util.domainBind(domain,fulfill)),"function"==typeof reject&&(this[base+1]=null===domain?reject:util.domainBind(domain,reject))}return this._setLength(index+1),index},Promise.prototype._proxy=function(proxyable,arg){this._addCallbacks(void 0,void 0,arg,proxyable,null)},Promise.prototype._resolveCallback=function(value,shouldBind){if(0===(117506048&this._bitField)){if(value===this)return this._rejectCallback(makeSelfResolutionError(),!1);var maybePromise=tryConvertToPromise(value,this);if(!(maybePromise instanceof Promise))return this._fulfill(value);shouldBind&&this._propagateFrom(maybePromise,2);var promise=maybePromise._target();if(promise===this)return void this._reject(makeSelfResolutionError());var bitField=promise._bitField;if(0===(50397184&bitField)){var len=this._length();len>0&&promise._migrateCallback0(this);for(var i=1;i>>16)){if(value===this){var err=makeSelfResolutionError();return this._attachExtraTrace(err),this._reject(err)}this._setFulfilled(),this._rejectionHandler0=value,(65535&bitField)>0&&(0!==(134217728&bitField)?this._settlePromises():async.settlePromises(this))}},Promise.prototype._reject=function(reason){var bitField=this._bitField;if(!((117506048&bitField)>>>16))return this._setRejected(),this._fulfillmentHandler0=reason,this._isFinal()?async.fatalError(reason,util.isNode):void((65535&bitField)>0?async.settlePromises(this):this._ensurePossibleRejectionHandled())},Promise.prototype._fulfillPromises=function(len,value){for(var i=1;i0){if(0!==(16842752&bitField)){var reason=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,reason,bitField),this._rejectPromises(len,reason)}else{var value=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,value,bitField),this._fulfillPromises(len,value)}this._setLength(0)}this._clearCancellationData()},Promise.prototype._settledValue=function(){var bitField=this._bitField;return 0!==(33554432&bitField)?this._rejectionHandler0:0!==(16777216&bitField)?this._fulfillmentHandler0:void 0},Promise.defer=Promise.pending=function(){debug.deprecated("Promise.defer","new Promise");var promise=new Promise(INTERNAL);return{promise:promise,resolve:deferResolve,reject:deferReject}},util.notEnumerableProp(Promise,"_makeSelfResolutionError",makeSelfResolutionError),_dereq_("./method")(Promise,INTERNAL,tryConvertToPromise,apiRejection,debug),_dereq_("./bind")(Promise,INTERNAL,tryConvertToPromise,debug),_dereq_("./cancel")(Promise,PromiseArray,apiRejection,debug),_dereq_("./direct_resolve")(Promise),_dereq_("./synchronous_inspection")(Promise),_dereq_("./join")(Promise,PromiseArray,tryConvertToPromise,INTERNAL,async,getDomain),Promise.Promise=Promise,Promise.version="3.4.6",_dereq_("./map.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./call_get.js")(Promise),_dereq_("./using.js")(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug),_dereq_("./timers.js")(Promise,INTERNAL,debug),_dereq_("./generators.js")(Promise,apiRejection,INTERNAL,tryConvertToPromise,Proxyable,debug),_dereq_("./nodeify.js")(Promise),_dereq_("./promisify.js")(Promise,INTERNAL),_dereq_("./props.js")(Promise,PromiseArray,tryConvertToPromise,apiRejection),_dereq_("./race.js")(Promise,INTERNAL,tryConvertToPromise,apiRejection),_dereq_("./reduce.js")(Promise,PromiseArray,apiRejection,tryConvertToPromise,INTERNAL,debug),_dereq_("./settle.js")(Promise,PromiseArray,debug),_dereq_("./some.js")(Promise,PromiseArray,apiRejection),_dereq_("./filter.js")(Promise,INTERNAL),_dereq_("./each.js")(Promise,INTERNAL),_dereq_("./any.js")(Promise),util.toFastProperties(Promise),util.toFastProperties(Promise.prototype),fillTypes({a:1}),fillTypes({b:2}),fillTypes({c:3}),fillTypes(1),fillTypes(function(){}),fillTypes(void 0),fillTypes(!1),fillTypes(new Promise(INTERNAL)),debug.setBounds(Async.firstLineError,util.lastLineError),Promise}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,tryConvertToPromise,apiRejection,Proxyable){function toResolutionValue(val){switch(val){case-2:return[];case-3:return{}}}function PromiseArray(values){var promise=this._promise=new Promise(INTERNAL);values instanceof Promise&&promise._propagateFrom(values,3),promise._setOnCancel(this),this._values=values,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var util=_dereq_("./util");util.isArray;return util.inherits(PromiseArray,Proxyable),PromiseArray.prototype.length=function(){return this._length},PromiseArray.prototype.promise=function(){return this._promise},PromiseArray.prototype._init=function init(_,resolveValueIfEmpty){var values=tryConvertToPromise(this._values,this._promise);if(values instanceof Promise){values=values._target();var bitField=values._bitField;if(this._values=values,0===(50397184&bitField))return this._promise._setAsyncGuaranteed(),values._then(init,this._reject,void 0,this,resolveValueIfEmpty);if(0===(33554432&bitField))return 0!==(16777216&bitField)?this._reject(values._reason()):this._cancel();values=values._value()}if(values=util.asArray(values),null===values){var err=apiRejection("expecting an array or an iterable object but got "+util.classString(values)).reason();return void this._promise._rejectCallback(err,!1)}return 0===values.length?void(resolveValueIfEmpty===-5?this._resolveEmptyArray():this._resolve(toResolutionValue(resolveValueIfEmpty))):void this._iterate(values)},PromiseArray.prototype._iterate=function(values){var len=this.getActualLength(values.length);this._length=len,this._values=this.shouldCopyValues()?new Array(len):this._values;for(var result=this._promise,isResolved=!1,bitField=null,i=0;i=this._length&&(this._resolve(this._values),!0)},PromiseArray.prototype._promiseCancelled=function(){return this._cancel(),!0},PromiseArray.prototype._promiseRejected=function(reason){return this._totalResolved++,this._reject(reason),!0},PromiseArray.prototype._resultCancelled=function(){if(!this._isResolved()){var values=this._values;if(this._cancel(),values instanceof Promise)values.cancel();else for(var i=0;i=this._length){var val;if(this._isMap)val=entriesToMap(this._values);else{val={};for(var keyOffset=this.length(),i=0,len=this.length();i>1},Promise.prototype.props=function(){return props(this)},Promise.props=function(promises){return props(promises)}}},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j=this._length&&(this._resolve(this._values),!0)},SettledPromiseArray.prototype._promiseFulfilled=function(value,index){var ret=new PromiseInspection;return ret._bitField=33554432,ret._settledValueField=value,this._promiseResolved(index,ret)},SettledPromiseArray.prototype._promiseRejected=function(reason,index){var ret=new PromiseInspection;return ret._bitField=16777216,ret._settledValueField=reason,this._promiseResolved(index,ret)},Promise.settle=function(promises){return debug.deprecated(".settle()",".reflect()"),new SettledPromiseArray(promises).promise()},Promise.prototype.settle=function(){return Promise.settle(this)}}},{"./util":36}],31:[function(_dereq_,module,exports){module.exports=function(Promise,PromiseArray,apiRejection){function SomePromiseArray(values){this.constructor$(values),this._howMany=0,this._unwrap=!1,this._initialized=!1}function some(promises,howMany){if((0|howMany)!==howMany||howMany<0)return apiRejection("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var ret=new SomePromiseArray(promises),promise=ret.promise();return ret.setHowMany(howMany),ret.init(),promise}var util=_dereq_("./util"),RangeError=_dereq_("./errors").RangeError,AggregateError=_dereq_("./errors").AggregateError,isArray=util.isArray,CANCELLATION={};util.inherits(SomePromiseArray,PromiseArray),SomePromiseArray.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var isArrayResolved=isArray(this._values);!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},SomePromiseArray.prototype.init=function(){this._initialized=!0,this._init()},SomePromiseArray.prototype.setUnwrap=function(){this._unwrap=!0},SomePromiseArray.prototype.howMany=function(){return this._howMany},SomePromiseArray.prototype.setHowMany=function(count){this._howMany=count},SomePromiseArray.prototype._promiseFulfilled=function(value){return this._addFulfilled(value),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},SomePromiseArray.prototype._promiseRejected=function(reason){return this._addRejected(reason),this._checkOutcome()},SomePromiseArray.prototype._promiseCancelled=function(){return this._values instanceof Promise||null==this._values?this._cancel():(this._addRejected(CANCELLATION),this._checkOutcome())},SomePromiseArray.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new AggregateError,i=this.length();i0?this._reject(e):this._cancel(),!0}return!1},SomePromiseArray.prototype._fulfilled=function(){return this._totalResolved},SomePromiseArray.prototype._rejected=function(){return this._values.length-this.length()},SomePromiseArray.prototype._addRejected=function(reason){this._values.push(reason)},SomePromiseArray.prototype._addFulfilled=function(value){this._values[this._totalResolved++]=value},SomePromiseArray.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},SomePromiseArray.prototype._getRangeError=function(count){var message="Input array must contain at least "+this._howMany+" items but contains only "+count+" items";return new RangeError(message)},SomePromiseArray.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},Promise.some=function(promises,howMany){return some(promises,howMany)},Promise.prototype.some=function(howMany){return some(this,howMany)},Promise._SomePromiseArray=SomePromiseArray}},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){module.exports=function(Promise){function PromiseInspection(promise){void 0!==promise?(promise=promise._target(),this._bitField=promise._bitField,this._settledValueField=promise._isFateSealed()?promise._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0); +}PromiseInspection.prototype._settledValue=function(){return this._settledValueField};var value=PromiseInspection.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},reason=PromiseInspection.prototype.error=PromiseInspection.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},isFulfilled=PromiseInspection.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},isRejected=PromiseInspection.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},isPending=PromiseInspection.prototype.isPending=function(){return 0===(50397184&this._bitField)},isResolved=PromiseInspection.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};PromiseInspection.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},Promise.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},Promise.prototype._isCancelled=function(){return this._target().__isCancelled()},Promise.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},Promise.prototype.isPending=function(){return isPending.call(this._target())},Promise.prototype.isRejected=function(){return isRejected.call(this._target())},Promise.prototype.isFulfilled=function(){return isFulfilled.call(this._target())},Promise.prototype.isResolved=function(){return isResolved.call(this._target())},Promise.prototype.value=function(){return value.call(this._target())},Promise.prototype.reason=function(){var target=this._target();return target._unsetRejectionIsUnhandled(),reason.call(target)},Promise.prototype._value=function(){return this._settledValue()},Promise.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},Promise.PromiseInspection=PromiseInspection}},{}],33:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL){function tryConvertToPromise(obj,context){if(isObject(obj)){if(obj instanceof Promise)return obj;var then=getThen(obj);if(then===errorObj){context&&context._pushContext();var ret=Promise.reject(then.e);return context&&context._popContext(),ret}if("function"==typeof then){if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);return obj._then(ret._fulfill,ret._reject,void 0,ret,null),ret}return doThenable(obj,then,context)}}return obj}function doGetThen(obj){return obj.then}function getThen(obj){try{return doGetThen(obj)}catch(e){return errorObj.e=e,errorObj}}function isAnyBluebirdPromise(obj){try{return hasProp.call(obj,"_promise0")}catch(e){return!1}}function doThenable(x,then,context){function resolve(value){promise&&(promise._resolveCallback(value),promise=null)}function reject(reason){promise&&(promise._rejectCallback(reason,synchronous,!0),promise=null)}var promise=new Promise(INTERNAL),ret=promise;context&&context._pushContext(),promise._captureStackTrace(),context&&context._popContext();var synchronous=!0,result=util.tryCatch(then).call(x,resolve,reject);return synchronous=!1,promise&&result===errorObj&&(promise._rejectCallback(result.e,!0,!0),promise=null),ret}var util=_dereq_("./util"),errorObj=util.errorObj,isObject=util.isObject,hasProp={}.hasOwnProperty;return tryConvertToPromise}},{"./util":36}],34:[function(_dereq_,module,exports){module.exports=function(Promise,INTERNAL,debug){function HandleWrapper(handle){this.handle=handle}function successClear(value){return clearTimeout(this.handle),value}function failureClear(reason){throw clearTimeout(this.handle),reason}var util=_dereq_("./util"),TimeoutError=Promise.TimeoutError;HandleWrapper.prototype._resultCancelled=function(){clearTimeout(this.handle)};var afterValue=function(value){return delay(+this).thenReturn(value)},delay=Promise.delay=function(ms,value){var ret,handle;return void 0!==value?(ret=Promise.resolve(value)._then(afterValue,null,null,ms,void 0),debug.cancellation()&&value instanceof Promise&&ret._setOnCancel(value)):(ret=new Promise(INTERNAL),handle=setTimeout(function(){ret._fulfill()},+ms),debug.cancellation()&&ret._setOnCancel(new HandleWrapper(handle)),ret._captureStackTrace()),ret._setAsyncGuaranteed(),ret};Promise.prototype.delay=function(ms){return delay(ms,this)};var afterTimeout=function(promise,message,parent){var err;err="string"!=typeof message?message instanceof Error?message:new TimeoutError("operation timed out"):new TimeoutError(message),util.markAsOriginatingFromRejection(err),promise._attachExtraTrace(err),promise._reject(err),null!=parent&&parent.cancel()};Promise.prototype.timeout=function(ms,message){ms=+ms;var ret,parent,handleWrapper=new HandleWrapper(setTimeout(function(){ret.isPending()&&afterTimeout(ret,message,parent)},ms));return debug.cancellation()?(parent=this.then(),ret=parent._then(successClear,failureClear,void 0,handleWrapper,void 0),ret._setOnCancel(handleWrapper)):ret=this._then(successClear,failureClear,void 0,handleWrapper,void 0),ret}}},{"./util":36}],35:[function(_dereq_,module,exports){module.exports=function(Promise,apiRejection,tryConvertToPromise,createContext,INTERNAL,debug){function thrower(e){setTimeout(function(){throw e},0)}function castPreservingDisposable(thenable){var maybePromise=tryConvertToPromise(thenable);return maybePromise!==thenable&&"function"==typeof thenable._isDisposable&&"function"==typeof thenable._getDisposer&&thenable._isDisposable()&&maybePromise._setDisposable(thenable._getDisposer()),maybePromise}function dispose(resources,inspection){function iterator(){if(i>=len)return ret._fulfill();var maybePromise=castPreservingDisposable(resources[i++]);if(maybePromise instanceof Promise&&maybePromise._isDisposable()){try{maybePromise=tryConvertToPromise(maybePromise._getDisposer().tryDispose(inspection),resources.promise)}catch(e){return thrower(e)}if(maybePromise instanceof Promise)return maybePromise._then(iterator,thrower,null,null,null)}iterator()}var i=0,len=resources.length,ret=new Promise(INTERNAL);return iterator(),ret}function Disposer(data,promise,context){this._data=data,this._promise=promise,this._context=context}function FunctionDisposer(fn,promise,context){this.constructor$(fn,promise,context)}function maybeUnwrapDisposer(value){return Disposer.isDisposer(value)?(this.resources[this.index]._setDisposable(value),value.promise()):value}function ResourceList(length){this.length=length,this.promise=null,this[length-1]=null}var util=_dereq_("./util"),TypeError=_dereq_("./errors").TypeError,inherits=_dereq_("./util").inherits,errorObj=util.errorObj,tryCatch=util.tryCatch,NULL={};Disposer.prototype.data=function(){return this._data},Disposer.prototype.promise=function(){return this._promise},Disposer.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():NULL},Disposer.prototype.tryDispose=function(inspection){var resource=this.resource(),context=this._context;void 0!==context&&context._pushContext();var ret=resource!==NULL?this.doDispose(resource,inspection):null;return void 0!==context&&context._popContext(),this._promise._unsetDisposable(),this._data=null,ret},Disposer.isDisposer=function(d){return null!=d&&"function"==typeof d.resource&&"function"==typeof d.tryDispose},inherits(FunctionDisposer,Disposer),FunctionDisposer.prototype.doDispose=function(resource,inspection){var fn=this.data();return fn.call(resource,resource,inspection)},ResourceList.prototype._resultCancelled=function(){for(var len=this.length,i=0;i0},Promise.prototype._getDisposer=function(){return this._disposer},Promise.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},Promise.prototype.disposer=function(fn){if("function"==typeof fn)return new FunctionDisposer(fn,this,createContext());throw new TypeError}}},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){function tryCatcher(){try{var target=tryCatchTarget;return tryCatchTarget=null,target.apply(this,arguments)}catch(e){return errorObj.e=e,errorObj}}function tryCatch(fn){return tryCatchTarget=fn,tryCatcher}function isPrimitive(val){return null==val||val===!0||val===!1||"string"==typeof val||"number"==typeof val}function isObject(value){return"function"==typeof value||"object"===("undefined"==typeof value?"undefined":_typeof(value))&&null!==value}function maybeWrapAsError(maybeError){return isPrimitive(maybeError)?new Error(safeToString(maybeError)):maybeError}function withAppended(target,appendee){var i,len=target.length,ret=new Array(len+1);for(i=0;i1,hasMethodsOtherThanConstructor=keys.length>0&&!(1===keys.length&&"constructor"===keys[0]),hasThisAssignmentAndStaticMethods=thisAssignmentPattern.test(fn+"")&&es5.names(fn).length>0;if(hasMethods||hasMethodsOtherThanConstructor||hasThisAssignmentAndStaticMethods)return!0}return!1}catch(e){return!1}}function toFastProperties(obj){function FakeConstructor(){}FakeConstructor.prototype=obj;for(var l=8;l--;)new FakeConstructor;return obj}function isIdentifier(str){return rident.test(str)}function filledRange(count,prefix,suffix){for(var ret=new Array(count),i=0;i10||version[0]>0}(),ret.isNode&&ret.toFastProperties(process);try{throw new Error}catch(e){ret.lastLineError=e}module.exports=ret},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(exports,__webpack_require__(1),__webpack_require__(4),__webpack_require__(10).setImmediate)},function(module,exports,__webpack_require__){"use strict";(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index=LARGE_ARRAY_SIZE&&(includes=cacheHas,isCommon=!1,values=new SetCache(values));outer:for(;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var differenceWith=baseRest(function(array,values){var comparator=last(values);return isArrayLikeObject(comparator)&&(comparator=void 0),isArrayLikeObject(array)?baseDifference(array,baseFlatten(values,1,isArrayLikeObject,!0),void 0,comparator):[]}),isArray=Array.isArray;module.exports=differenceWith}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(global){function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function isFlattenable(value){return isArray(value)||isArguments(value)||!!(spreadableSymbol&&value&&value[spreadableSymbol])}function flatten(array){var length=array?array.length:0;return length?baseFlatten(array,1):[]}function isArguments(value){return isArrayLikeObject(value)&&hasOwnProperty.call(value,"callee")&&(!propertyIsEnumerable.call(value,"callee")||objectToString.call(value)==argsTag)}function isArrayLike(value){return null!=value&&isLength(value.length)&&!isFunction(value)}function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value)}function isFunction(value){var tag=isObject(value)?objectToString.call(value):"";return tag==funcTag||tag==genTag}function isLength(value){return"number"==typeof value&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,isArray=Array.isArray;module.exports=flatten}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";(function(global){function apply(func,thisArg,args){switch(args.length){case 0:return func.call(thisArg);case 1:return func.call(thisArg,args[0]);case 2:return func.call(thisArg,args[0],args[1]);case 3:return func.call(thisArg,args[0],args[1],args[2])}return func.apply(thisArg,args)}function arrayIncludes(array,value){var length=array?array.length:0;return!!length&&baseIndexOf(array,value,0)>-1}function arrayIncludesWith(array,value,comparator){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++index0&&predicate(value)?depth>1?baseFlatten(value,depth-1,predicate,isStrict,result):arrayPush(result,value):isStrict||(result[result.length]=value)}return result}function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)||isHostObject(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}function baseRest(func,start){return start=nativeMax(void 0===start?func.length-1:start,0),function(){for(var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set)return setToArray(set);isCommon=!1,includes=cacheHas,seen=new SetCache}else seen=iteratee?[]:result;outer:for(;++index-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function noop(){}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,HASH_UNDEFINED="__lodash_hash_undefined__",INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,argsTag="[object Arguments]",funcTag="[object Function]",genTag="[object GeneratorFunction]",reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,spreadableSymbol=_Symbol?_Symbol.isConcatSpreadable:void 0,nativeMax=Math.max,Map=getNative(root,"Map"),Set=getNative(root,"Set"),nativeCreate=getNative(Object,"create");Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas;var createSet=Set&&1/setToArray(new Set([,-0]))[1]==INFINITY?function(values){return new Set(values)}:noop,unionWith=baseRest(function(arrays){var comparator=last(arrays);return isArrayLikeObject(comparator)&&(comparator=void 0),baseUniq(baseFlatten(arrays,1,isArrayLikeObject,!0),void 0,comparator)}),isArray=Array.isArray;module.exports=unionWith}).call(exports,__webpack_require__(4))},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};return _classCallCheck(this,EventStore),void 0===options.Index&&Object.assign(options,{Index:EventIndex}),_possibleConstructorReturn(this,(EventStore.__proto__||Object.getPrototypeOf(EventStore)).call(this,ipfs,id,dbname,options))}return _inherits(EventStore,_Store),_createClass(EventStore,[{key:"add",value:function(data){return this._addOperation({op:"ADD",key:null,value:data,meta:{ts:(new Date).getTime()}})}},{key:"get",value:function(hash){return this.iterator({gte:hash,limit:1}).collect()[0]}},{key:"iterator",value:function iterator(options){var _iterator,messages=this._query(options),currentIndex=0,iterator=(_iterator={},_defineProperty(_iterator,Symbol.iterator,function(){return this}),_defineProperty(_iterator,"next",function(){var item={value:null,done:!0};return currentIndex-1?opts.limit:this._index.get().length:1,events=this._index.get(),result=[];return result=opts.gt||opts.gte?this._read(events,opts.gt?opts.gt:opts.gte,amount,!!opts.gte):this._read(events.reverse(),opts.lt?opts.lt:opts.lte,amount,opts.lte||!opts.lt).reverse()}},{key:"_read",value:function(ops,hash,amount,inclusive){var startIndex=Math.max(findIndex(ops,function(e){return e.hash===hash}),0);return startIndex+=inclusive?0:1,take(ops.slice(startIndex),amount)}}]),EventStore}(Store);module.exports=EventStore},function(module,exports,__webpack_require__){"use strict";var sources=__webpack_require__(101),sinks=__webpack_require__(95),throughs=__webpack_require__(107);exports=module.exports=__webpack_require__(91);for(var k in sources)exports[k]=sources[k];for(var k in throughs)exports[k]=throughs[k];for(var k in sinks)exports[k]=sinks[k]},function(module,exports,__webpack_require__){"use strict";var abortCb=__webpack_require__(41);module.exports=function(value,onAbort){return function(abort,cb){if(abort)return abortCb(cb,abort,onAbort);if(null!=value){var _value=value;value=null,cb(null,_value)}else cb(!0)}}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12),filter=__webpack_require__(24);module.exports=function(field,invert){field=prop(field)||id;var seen={};return filter(function(data){var key=field(data);return seen[key]?!!invert:(seen[key]=!0,!invert)})}},function(module,exports){"use strict";module.exports=function(cb,abort,onAbort){cb(abort),onAbort&&onAbort(abort===!0?null:abort)}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},prop=__webpack_require__(12);module.exports=function(test){return"object"===("undefined"==typeof test?"undefined":_typeof(test))&&"function"==typeof test.test?function(data){return test.test(data)}:prop(test)||id}},function(module,exports,__webpack_require__){"use strict";function clone(obj){if(null===obj||"object"!=typeof obj)return obj;if(obj instanceof Object)var copy={__proto__:obj.__proto__};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}var fs=__webpack_require__(15);module.exports=clone(fs)},function(module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return"[object Array]"==toString.call(arr)}},function(module,exports,__webpack_require__){(function(process){(function(){var JSONStorage,KEY_FOR_EMPTY_STRING,LocalStorage,MetaKey,QUOTA_EXCEEDED_ERR,StorageEvent,_emptyDirectory,_escapeKey,_rm,createMap,events,fs,path,writeSync,extend=function(child,parent){function ctor(){this.constructor=child}for(var key in parent)hasProp.call(parent,key)&&(child[key]=parent[key]);return ctor.prototype=parent.prototype,child.prototype=new ctor,child.__super__=parent.prototype,child},hasProp={}.hasOwnProperty;path=__webpack_require__(31),fs=__webpack_require__(15),events=__webpack_require__(5),writeSync=__webpack_require__(157).sync,KEY_FOR_EMPTY_STRING="---.EMPTY_STRING.---",_emptyDirectory=function(target){var i,len,p,ref,results;for(ref=fs.readdirSync(target),results=[],i=0,len=ref.length;ithis.quota)throw new QUOTA_EXCEEDED_ERR;if(writeSync(filename,valueString,"utf8"),existsBeforeSet||(metaKey=new MetaKey(encodedKey,this._keys.push(key)-1),metaKey.size=valueStringLength,this._metaKeyMap[key]=metaKey,this.length+=1,this._bytesInUse+=valueStringLength),hasListeners)return evnt=new StorageEvent(key,oldValue,value,this._eventUrl),this.emit("storage",evnt)},LocalStorage.prototype.getItem=function(key){var filename,metaKey;return key=_escapeKey(key),metaKey=this._metaKeyMap[key],metaKey?(filename=path.join(this._location,metaKey.key),fs.readFileSync(filename,"utf8")):null},LocalStorage.prototype._getStat=function(key){var filename;key=_escapeKey(key),filename=path.join(this._location,encodeURIComponent(key));try{return fs.statSync(filename)}catch(error){return null}},LocalStorage.prototype.removeItem=function(key){var evnt,filename,hasListeners,k,meta,metaKey,oldValue,ref,v;if(key=_escapeKey(key),metaKey=this._metaKeyMap[key]){hasListeners=events.EventEmitter.listenerCount(this,"storage"),oldValue=null,hasListeners&&(oldValue=this.getItem(key)),delete this._metaKeyMap[key],this.length-=1,this._bytesInUse-=metaKey.size,filename=path.join(this._location,metaKey.key),this._keys.splice(metaKey.index,1),ref=this._metaKeyMap;for(k in ref)v=ref[k],meta=this._metaKeyMap[k],meta.index>metaKey.index&&(meta.index-=1);if(_rm(filename),hasListeners)return evnt=new StorageEvent(key,oldValue,null,this._eventUrl),this.emit("storage",evnt)}},LocalStorage.prototype.key=function(n){return this._keys[n]},LocalStorage.prototype.clear=function(){var evnt;if(_emptyDirectory(this._location),this._metaKeyMap=createMap(),this._keys=[],this.length=0,this._bytesInUse=0,events.EventEmitter.listenerCount(this,"storage"))return evnt=new StorageEvent(null,null,null,this._eventUrl),this.emit("storage",evnt)},LocalStorage.prototype._getBytesInUse=function(){return this._bytesInUse},LocalStorage.prototype._deleteLocation=function(){return delete instanceMap[this._location],_rm(this._location),this._metaKeyMap={},this._keys=[],this.length=0,this._bytesInUse=0},LocalStorage}(events.EventEmitter),JSONStorage=function(superClass){function JSONStorage(){return JSONStorage.__super__.constructor.apply(this,arguments)}return extend(JSONStorage,superClass),JSONStorage.prototype.setItem=function(key,value){var newValue;return newValue=JSON.stringify(value),JSONStorage.__super__.setItem.call(this,key,newValue)},JSONStorage.prototype.getItem=function(key){return JSON.parse(JSONStorage.__super__.getItem.call(this,key))},JSONStorage}(LocalStorage),exports.LocalStorage=LocalStorage,exports.JSONStorage=JSONStorage,exports.QUOTA_EXCEEDED_ERR=QUOTA_EXCEEDED_ERR}).call(this)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){"use strict";function PassThrough(options){return this instanceof PassThrough?void Transform.call(this,options):new PassThrough(options)}module.exports=PassThrough;var Transform=__webpack_require__(27),util=__webpack_require__(13);util.inherits=__webpack_require__(3),util.inherits(PassThrough,Transform),PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},function(module,exports,__webpack_require__){"use strict";(function(process){function prependListener(emitter,event,fn){return"function"==typeof emitter.prependListener?emitter.prependListener(event,fn):void(emitter._events&&emitter._events[event]?isArray(emitter._events[event])?emitter._events[event].unshift(fn):emitter._events[event]=[fn,emitter._events[event]]:emitter.on(event,fn))}function ReadableState(options,stream){Duplex=Duplex||__webpack_require__(9),options=options||{},this.objectMode=!!options.objectMode,stream instanceof Duplex&&(this.objectMode=this.objectMode||!!options.readableObjectMode);var hwm=options.highWaterMark,defaultHwm=this.objectMode?16:16384;this.highWaterMark=hwm||0===hwm?hwm:defaultHwm,this.highWaterMark=~~this.highWaterMark,this.buffer=new BufferList,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=options.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,options.encoding&&(StringDecoder||(StringDecoder=__webpack_require__(49).StringDecoder),this.decoder=new StringDecoder(options.encoding),this.encoding=options.encoding)}function Readable(options){return Duplex=Duplex||__webpack_require__(9),this instanceof Readable?(this._readableState=new ReadableState(options,this),this.readable=!0,options&&"function"==typeof options.read&&(this._read=options.read),void Stream.call(this)):new Readable(options)}function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er)stream.emit("error",er);else if(null===chunk)state.reading=!1,onEofChunk(stream,state);else if(state.objectMode||chunk&&chunk.length>0)if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var _e=new Error("stream.unshift() after end event");stream.emit("error",_e)}else{var skipAdd;!state.decoder||addToFront||encoding||(chunk=state.decoder.write(chunk),skipAdd=!state.objectMode&&0===chunk.length),addToFront||(state.reading=!1),skipAdd||(state.flowing&&0===state.length&&!state.sync?(stream.emit("data",chunk),stream.read(0)):(state.length+=state.objectMode?1:chunk.length,addToFront?state.buffer.unshift(chunk):state.buffer.push(chunk),state.needReadable&&emitReadable(stream))),maybeReadMore(stream,state)}else addToFront||(state.reading=!1);return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length=MAX_HWM?n=MAX_HWM:(n--,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n++),n}function howMuchToRead(n,state){return n<=0||0===state.length&&state.ended?0:state.objectMode?1:n!==n?state.flowing&&state.length?state.buffer.head.data.length:state.length:(n>state.highWaterMark&&(state.highWaterMark=computeNewHighWaterMark(n)),n<=state.length?n:state.ended?state.length:(state.needReadable=!0,0))}function chunkInvalid(state,chunk){var er=null;return Buffer.isBuffer(chunk)||"string"==typeof chunk||null===chunk||void 0===chunk||state.objectMode||(er=new TypeError("Invalid non-string/buffer chunk")),er}function onEofChunk(stream,state){if(!state.ended){if(state.decoder){var chunk=state.decoder.end();chunk&&chunk.length&&(state.buffer.push(chunk),state.length+=state.objectMode?1:chunk.length)}state.ended=!0,emitReadable(stream)}}function emitReadable(stream){var state=stream._readableState;state.needReadable=!1,state.emittedReadable||(debug("emitReadable",state.flowing),state.emittedReadable=!0,state.sync?processNextTick(emitReadable_,stream):emitReadable_(stream))}function emitReadable_(stream){debug("emit readable"),stream.emit("readable"),flow(stream)}function maybeReadMore(stream,state){state.readingMore||(state.readingMore=!0,processNextTick(maybeReadMore_,stream,state))}function maybeReadMore_(stream,state){for(var len=state.length;!state.reading&&!state.flowing&&!state.ended&&state.length=state.length?(ret=state.decoder?state.buffer.join(""):1===state.buffer.length?state.buffer.head.data:state.buffer.concat(state.length),state.buffer.clear()):ret=fromListPartial(n,state.buffer,state.decoder),ret}function fromListPartial(n,list,hasStrings){var ret;return nstr.length?str.length:n;if(ret+=nb===str.length?str:str.slice(0,n),n-=nb,0===n){nb===str.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=str.slice(nb));break}++c}return list.length-=c,ret}function copyFromBuffer(n,list){var ret=bufferShim.allocUnsafe(n),p=list.head,c=1;for(p.data.copy(ret),n-=p.data.length;p=p.next;){var buf=p.data,nb=n>buf.length?buf.length:n;if(buf.copy(ret,ret.length-n,0,nb),n-=nb,0===n){nb===buf.length?(++c,p.next?list.head=p.next:list.head=list.tail=null):(list.head=p,p.data=buf.slice(nb));break}++c}return list.length-=c,ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');state.endEmitted||(state.ended=!0,processNextTick(endReadableNT,state,stream))}function endReadableNT(state,stream){state.endEmitted||0!==state.length||(state.endEmitted=!0,stream.readable=!1,stream.emit("end"))}function forEach(xs,f){for(var i=0,l=xs.length;i=state.highWaterMark||state.ended))return debug("read: emitReadable",state.length,state.ended),0===state.length&&state.ended?endReadable(this):emitReadable(this),null;if(n=howMuchToRead(n,state),0===n&&state.ended)return 0===state.length&&endReadable(this),null;var doRead=state.needReadable;debug("need readable",doRead),(0===state.length||state.length-n0?fromList(n,state):null,null===ret?(state.needReadable=!0,n=0):state.length-=n,0===state.length&&(state.ended||(state.needReadable=!0),nOrig!==n&&state.ended&&endReadable(this)),null!==ret&&this.emit("data",ret),ret},Readable.prototype._read=function(n){this.emit("error",new Error("_read() is not implemented"))},Readable.prototype.pipe=function(dest,pipeOpts){function onunpipe(readable){debug("onunpipe"),readable===src&&cleanup()}function onend(){debug("onend"),dest.end()}function cleanup(){debug("cleanup"),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",cleanup),src.removeListener("data",ondata),cleanedUp=!0,!state.awaitDrain||dest._writableState&&!dest._writableState.needDrain||ondrain()}function ondata(chunk){debug("ondata"),increasedAwaitDrain=!1;var ret=dest.write(chunk);!1!==ret||increasedAwaitDrain||((1===state.pipesCount&&state.pipes===dest||state.pipesCount>1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp&&(debug("false write response, pause",src._readableState.awaitDrain),src._readableState.awaitDrain++,increasedAwaitDrain=!0),src.pause())}function onerror(er){debug("onerror",er),unpipe(),dest.removeListener("error",onerror),0===EElistenerCount(dest,"error")&&dest.emit("error",er)}function onclose(){dest.removeListener("finish",onfinish),unpipe(); +}function onfinish(){debug("onfinish"),dest.removeListener("close",onclose),unpipe()}function unpipe(){debug("unpipe"),src.unpipe(dest)}var src=this,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)}state.pipesCount+=1,debug("pipe count=%d opts=%j",state.pipesCount,pipeOpts);var doEnd=(!pipeOpts||pipeOpts.end!==!1)&&dest!==process.stdout&&dest!==process.stderr,endFn=doEnd?onend:cleanup;state.endEmitted?processNextTick(endFn):src.once("end",endFn),dest.on("unpipe",onunpipe);var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);var cleanedUp=!1,increasedAwaitDrain=!1;return src.on("data",ondata),prependListener(dest,"error",onerror),dest.once("close",onclose),dest.once("finish",onfinish),dest.emit("pipe",src),state.flowing||(debug("pipe resume"),src.resume()),dest},Readable.prototype.unpipe=function(dest){var state=this._readableState;if(0===state.pipesCount)return this;if(1===state.pipesCount)return dest&&dest!==state.pipes?this:(dest||(dest=state.pipes),state.pipes=null,state.pipesCount=0,state.flowing=!1,dest&&dest.emit("unpipe",this),this);if(!dest){var dests=state.pipes,len=state.pipesCount;state.pipes=null,state.pipesCount=0,state.flowing=!1;for(var i=0;i=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;if(buffer.copy(this.charBuffer,this.charReceived,0,available),this.charReceived+=available,this.charReceived=55296&&charCode<=56319)){if(this.charReceived=this.charLength=0,0===buffer.length)return charStr;break}this.charLength+=this.surrogateSize,charStr=""}this.detectIncompleteChar(buffer);var end=buffer.length;this.charLength&&(buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end),end-=this.charReceived),charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1,charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;return this.charLength+=size,this.charReceived+=size,this.charBuffer.copy(this.charBuffer,size,0,size),buffer.copy(this.charBuffer,0,0,size),charStr.substring(0,end)}return charStr},StringDecoder.prototype.detectIncompleteChar=function(buffer){for(var i=buffer.length>=3?3:buffer.length;i>0;i--){var c=buffer[buffer.length-i];if(1==i&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i},StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length&&(res=this.write(buffer)),this.charReceived){var cr=this.charReceived,buf=this.charBuffer,enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res}},function(module,exports){module.exports=function(module){return module.webpackPolyfill||(module.deprecate=function(){},module.paths=[],module.children||(module.children=[]),Object.defineProperty(module,"loaded",{enumerable:!0,configurable:!1,get:function(){return module.l}}),Object.defineProperty(module,"id",{enumerable:!0,configurable:!1,get:function(){return module.i}}),module.webpackPolyfill=1),module}},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:"default",options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};_classCallCheck(this,OrbitDB),this._ipfs=ipfs,this._pubsub=options&&options.broker?new options.broker(ipfs):new Pubsub(ipfs),this.user={id:id},this.network={name:defaultNetworkName},this.events=new EventEmitter,this.stores={}}return _createClass(OrbitDB,[{key:"feed",value:function(dbname,options){return this._createStore(FeedStore,dbname,options)}},{key:"eventlog",value:function(dbname,options){return this._createStore(EventStore,dbname,options)}},{key:"kvstore",value:function(dbname,options){return this._createStore(KeyValueStore,dbname,options)}},{key:"counter",value:function(dbname,options){return this._createStore(CounterStore,dbname,options)}},{key:"docstore",value:function(dbname,options){return this._createStore(DocumentStore,dbname,options)}},{key:"disconnect",value:function(){var _this=this;this._pubsub&&this._pubsub.disconnect(),this.events.removeAllListeners("data"),Object.keys(this.stores).map(function(e){return _this.stores[e]}).forEach(function(store){store.events.removeAllListeners("data"),store.events.removeAllListeners("write"),store.events.removeAllListeners("close")}),this.stores={},this.user=null,this.network=null}},{key:"_createStore",value:function(Store,dbname){var options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{subscribe:!0},store=new Store(this._ipfs,this.user.id,dbname,options);return this.stores[dbname]=store,this._subscribe(store,dbname,options.subscribe,options.cachePath)}},{key:"_subscribe",value:function(store,dbname){var subscribe=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],cachePath=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"./orbit-db";return store.events.on("data",this._onData.bind(this)),store.events.on("write",this._onWrite.bind(this)),store.events.on("close",this._onClose.bind(this)),subscribe&&this._pubsub?this._pubsub.subscribe(dbname,this._onMessage.bind(this),this._onConnected.bind(this),store.options.maxHistory>0):store.loadHistory().catch(function(e){return console.error(e.stack)}),Cache.loadCache(cachePath).then(function(){var hash=Cache.get(dbname);store.loadHistory(hash).catch(function(e){return console.error(e.stack)})}),store}},{key:"_onConnected",value:function(dbname,hash){var store=this.stores[dbname];store.loadHistory(hash).catch(function(e){return console.error(e.stack)})}},{key:"_onMessage",value:function(dbname,hash){var store=this.stores[dbname];store.sync(hash).then(function(res){return Cache.set(dbname,hash)}).catch(function(e){return console.error(e.stack)})}},{key:"_onWrite",value:function(dbname,hash){if(!hash)throw new Error("Hash can't be null!");this._pubsub&&this._pubsub.publish(dbname,hash),Cache.set(dbname,hash)}},{key:"_onData",value:function(dbname,item){this.events.emit("data",dbname,item)}},{key:"_onClose",value:function(dbname){this._pubsub&&this._pubsub.unsubscribe(dbname),delete this.stores[dbname]}}]),OrbitDB}();module.exports=OrbitDB},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if(!credentials.provider)throw new Error("'provider' not specified");var provider=identityProviders[credentials.provider];if(!provider)throw new Error("Provider '"+credentials.provider+"' not found");return provider.authorize(ipfs,credentials)}},{key:"loadProfile",value:function(ipfs){var profile=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!profile.identityProvider)throw new Error("'identityProvider' not specified");if(!profile.identityProvider.provider)throw new Error("'provider' not specified");var provider=identityProviders[profile.identityProvider.provider];if(!provider)throw new Error("Provider '"+profile.identityProvider.provider+"' not found");return provider.load(ipfs,profile)}}]),IdentityProviders}();module.exports=IdentityProviders},function(module,exports,__webpack_require__){"use strict";(function(global){/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a,b){if(a===b)return 0;for(var x=a.length,y=b.length,i=0,len=Math.min(x,y);i=0;i--)if(ka[i]!==kb[i])return!1;for(i=ka.length-1;i>=0;i--)if(key=ka[i],!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return!1;return!0}function notDeepStrictEqual(actual,expected,message){_deepEqual(actual,expected,!0)&&fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}function expectedException(actual,expected){if(!actual||!expected)return!1;if("[object RegExp]"==Object.prototype.toString.call(expected))return expected.test(actual);try{if(actual instanceof expected)return!0}catch(e){}return!Error.isPrototypeOf(expected)&&expected.call({},actual)===!0}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if("function"!=typeof block)throw new TypeError('"block" argument must be a function');"string"==typeof expected&&(message=expected,expected=null),actual=_tryBlock(block),message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:"."),shouldThrow&&!actual&&fail(actual,expected,"Missing expected exception"+message);var userProvidedMessage="string"==typeof message,isUnwantedException=!shouldThrow&&util.isError(actual),isUnexpectedException=!shouldThrow&&actual&&!expected;if((isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException)&&fail(actual,expected,"Got unwanted exception"+message),shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual)throw actual}var util=__webpack_require__(14),hasOwn=Object.prototype.hasOwnProperty,pSlice=Array.prototype.slice,functionsHaveNames=function(){return"foo"===function(){}.name}(),assert=module.exports=ok,regex=/\s*function\s+([^\(\s]*)\s*/;assert.AssertionError=function(options){this.name="AssertionError",this.actual=options.actual,this.expected=options.expected,this.operator=options.operator,options.message?(this.message=options.message,this.generatedMessage=!1):(this.message=getMessage(this),this.generatedMessage=!0);var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace)Error.captureStackTrace(this,stackStartFunction);else{var err=new Error;if(err.stack){var out=err.stack,fn_name=getName(stackStartFunction),idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}},util.inherits(assert.AssertionError,Error),assert.fail=fail,assert.ok=ok,assert.equal=function(actual,expected,message){actual!=expected&&fail(actual,expected,message,"==",assert.equal)},assert.notEqual=function(actual,expected,message){actual==expected&&fail(actual,expected,message,"!=",assert.notEqual)},assert.deepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)||fail(actual,expected,message,"deepEqual",assert.deepEqual)},assert.deepStrictEqual=function(actual,expected,message){_deepEqual(actual,expected,!0)||fail(actual,expected,message,"deepStrictEqual",assert.deepStrictEqual)},assert.notDeepEqual=function(actual,expected,message){_deepEqual(actual,expected,!1)&&fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)},assert.notDeepStrictEqual=notDeepStrictEqual,assert.strictEqual=function(actual,expected,message){actual!==expected&&fail(actual,expected,message,"===",assert.strictEqual)},assert.notStrictEqual=function(actual,expected,message){actual===expected&&fail(actual,expected,message,"!==",assert.notStrictEqual)},assert.throws=function(block,error,message){_throws(!0,block,error,message)},assert.doesNotThrow=function(block,error,message){_throws(!1,block,error,message)},assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)hasOwn.call(obj,key)&&keys.push(key);return keys}}).call(exports,__webpack_require__(4))},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),DirectoryPost=function(_Post){function DirectoryPost(name,hash,size){_classCallCheck(this,DirectoryPost);var _this=_possibleConstructorReturn(this,(DirectoryPost.__proto__||Object.getPrototypeOf(DirectoryPost)).call(this,"directory"));return _this.name=name,_this.hash=hash,_this.size=size,_this}return _inherits(DirectoryPost,_Post),DirectoryPost}(Post);module.exports=DirectoryPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),FilePost=function(_Post){function FilePost(name,hash,size,meta){_classCallCheck(this,FilePost);var _this=_possibleConstructorReturn(this,(FilePost.__proto__||Object.getPrototypeOf(FilePost)).call(this,"file"));return _this.name=name,_this.hash=hash,_this.size=size||-1,_this.meta=meta||{},_this}return _inherits(FilePost,_Post),FilePost}(Post);module.exports=FilePost},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var MetaInfo=function MetaInfo(type,size,ts,from){_classCallCheck(this,MetaInfo),this.type=type,this.size=size,this.ts=ts,this.from=from||""};module.exports=MetaInfo},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),OrbitDBItem=function(_Post){function OrbitDBItem(operation,key,value){_classCallCheck(this,OrbitDBItem);var _this=_possibleConstructorReturn(this,(OrbitDBItem.__proto__||Object.getPrototypeOf(OrbitDBItem)).call(this,"orbit-db-op"));return _this.op=operation,_this.key=key,_this.value=value,_this}return _inherits(OrbitDBItem,_Post),OrbitDBItem}(Post);module.exports=OrbitDBItem},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),PinnedPost=function(_Post){function PinnedPost(pinned){_classCallCheck(this,PinnedPost);var _this=_possibleConstructorReturn(this,(PinnedPost.__proto__||Object.getPrototypeOf(PinnedPost)).call(this,"pin"));return _this.pinned=pinned,_this}return _inherits(PinnedPost,_Post),PinnedPost}(Post);module.exports=PinnedPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),Poll=function(_Post){function Poll(question,options){_classCallCheck(this,Poll);var _this=_possibleConstructorReturn(this,(Poll.__proto__||Object.getPrototypeOf(Poll)).call(this,"poll"));return _this.question=question,_this.options=options,_this}return _inherits(Poll,_Post),Poll}(Post);module.exports=Poll},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _possibleConstructorReturn(self,call){if(!self)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!call||"object"!=typeof call&&"function"!=typeof call?self:call}function _inherits(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:!1,writable:!0,configurable:!0}}),superClass&&(Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass)}var Post=__webpack_require__(7),TextPost=function(_Post){function TextPost(content,replyto){_classCallCheck(this,TextPost);var _this=_possibleConstructorReturn(this,(TextPost.__proto__||Object.getPrototypeOf(TextPost)).call(this,"text"));return _this.content=content,_this.replyto=replyto,_this}return _inherits(TextPost,_Post),TextPost}(Post);module.exports=TextPost},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i0;)for(callbacks=microtickQueue,microtickQueue=[],l=callbacks.length,i=0;i0);isOutsideMicroTick=!0,needsNewPhysicalTick=!0}function finalizePhysicalTick(){var unhandledErrs=unhandledErrors; +unhandledErrors=[],unhandledErrs.forEach(function(p){p._PSD.onunhandled.call(null,p._value,p)});for(var finalizers=tickFinalizers.slice(0),i=finalizers.length;i;)finalizers[--i]()}function run_at_end_of_this_or_next_physical_tick(fn){function finalizer(){fn(),tickFinalizers.splice(tickFinalizers.indexOf(finalizer),1)}tickFinalizers.push(finalizer),++numScheduledCalls,asap$1(function(){0===--numScheduledCalls&&finalizePhysicalTick()},[])}function addPossiblyUnhandledError(promise){unhandledErrors.some(function(p){return p._value===promise._value})||unhandledErrors.push(promise)}function markErrorAsHandled(promise){for(var i=unhandledErrors.length;i;)if(unhandledErrors[--i]._value===promise._value)return void unhandledErrors.splice(i,1)}function defaultErrorHandler(e){console.warn("Unhandled rejection: "+(e.stack||e))}function PromiseReject(reason){return new Promise(INTERNAL,!1,reason)}function wrap(fn,errorCatcher){var psd=PSD;return function(){var wasRootExec=beginMicroTickScope(),outerScope=PSD;try{return outerScope!==psd&&(PSD=psd),fn.apply(this,arguments)}catch(e){errorCatcher&&errorCatcher(e)}finally{outerScope!==psd&&(PSD=outerScope),wasRootExec&&endMicroTickScope()}}}function newScope(fn,a1,a2,a3){var parent=PSD,psd=Object.create(parent);psd.parent=parent,psd.ref=0,psd.global=!1,++parent.ref,psd.finalize=function(){--this.parent.ref||this.parent.finalize()};var rv=usePSD(psd,fn,a1,a2,a3);return 0===psd.ref&&psd.finalize(),rv}function usePSD(psd,fn,a1,a2,a3){var outerScope=PSD;try{return psd!==outerScope&&(PSD=psd),fn(a1,a2,a3)}finally{psd!==outerScope&&(PSD=outerScope)}}function globalError(err,promise){var rv;try{rv=promise.onuncatched(err)}catch(e){}if(rv!==!1)try{var event,eventData={promise:promise,reason:err};if(_global.document&&document.createEvent?(event=document.createEvent("Event"),event.initEvent(UNHANDLEDREJECTION,!0,!0),extend(event,eventData)):_global.CustomEvent&&(event=new CustomEvent(UNHANDLEDREJECTION,{detail:eventData}),extend(event,eventData)),event&&_global.dispatchEvent&&(dispatchEvent(event),!_global.PromiseRejectionEvent&&_global.onunhandledrejection))try{_global.onunhandledrejection(event)}catch(_){}event.defaultPrevented||Promise.on.error.fire(err,promise)}catch(e){}}function rejection(err,uncaughtHandler){var rv=Promise.reject(err);return uncaughtHandler?rv.uncaught(uncaughtHandler):rv}function Dexie(dbName,options){function init(){db.on("versionchange",function(ev){ev.newVersion>0?console.warn("Another connection wants to upgrade database '"+db.name+"'. Closing db now to resume the upgrade."):console.warn("Another connection wants to delete database '"+db.name+"'. Closing db now to resume the delete request."),db.close()}),db.on("blocked",function(ev){!ev.newVersion||ev.newVersionoldVersion});return versToRun.forEach(function(version){queue.push(function(){var oldSchema=globalSchema,newSchema=version._cfg.dbschema;adjustToExistingIndexNames(oldSchema,idbtrans),adjustToExistingIndexNames(newSchema,idbtrans),globalSchema=db._dbSchema=newSchema;var diff=getSchemaDiff(oldSchema,newSchema);if(diff.add.forEach(function(tuple){createTable(idbtrans,tuple[0],tuple[1].primKey,tuple[1].indexes)}),diff.change.forEach(function(change){if(change.recreate)throw new exceptions.Upgrade("Not yet support for changing primary key");var store=idbtrans.objectStore(change.name);change.add.forEach(function(idx){addIndex(store,idx)}),change.change.forEach(function(idx){store.deleteIndex(idx.name),addIndex(store,idx)}),change.del.forEach(function(idxName){store.deleteIndex(idxName)})}),version._cfg.contentUpgrade)return anyContentUpgraderHasRun=!0,Promise.follow(function(){version._cfg.contentUpgrade(trans)})}),queue.push(function(idbtrans){if(!anyContentUpgraderHasRun||!hasIEDeleteObjectStoreBug){var newSchema=version._cfg.dbschema;deleteRemovedTables(newSchema,idbtrans)}})}),runQueue().then(function(){createMissingTables(globalSchema,idbtrans)})}function getSchemaDiff(oldSchema,newSchema){var diff={del:[],add:[],change:[]};for(var table in oldSchema)newSchema[table]||diff.del.push(table);for(table in newSchema){var oldDef=oldSchema[table],newDef=newSchema[table];if(oldDef){var change={name:table,def:newDef,recreate:!1,del:[],add:[],change:[]};if(oldDef.primKey.src!==newDef.primKey.src)change.recreate=!0,diff.change.push(change);else{var oldIndexes=oldDef.idxByName,newIndexes=newDef.idxByName;for(var idxName in oldIndexes)newIndexes[idxName]||change.del.push(idxName);for(idxName in newIndexes){var oldIdx=oldIndexes[idxName],newIdx=newIndexes[idxName];oldIdx?oldIdx.src!==newIdx.src&&change.change.push(newIdx):change.add.push(newIdx)}(change.del.length>0||change.add.length>0||change.change.length>0)&&diff.change.push(change)}}else diff.add.push([table,newDef])}return diff}function createTable(idbtrans,tableName,primKey,indexes){var store=idbtrans.db.createObjectStore(tableName,primKey.keyPath?{keyPath:primKey.keyPath,autoIncrement:primKey.auto}:{autoIncrement:primKey.auto});return indexes.forEach(function(idx){addIndex(store,idx)}),store}function createMissingTables(newSchema,idbtrans){keys(newSchema).forEach(function(tableName){idbtrans.db.objectStoreNames.contains(tableName)||createTable(idbtrans,tableName,newSchema[tableName].primKey,newSchema[tableName].indexes)})}function deleteRemovedTables(newSchema,idbtrans){for(var i=0;i0?a:b}function ascending(a,b){return indexedDB.cmp(a,b)}function descending(a,b){return indexedDB.cmp(b,a)}function simpleCompare(a,b){return ab?-1:a===b?0:1}function combine(filter1,filter2){return filter1?filter2?function(){return filter1.apply(this,arguments)&&filter2.apply(this,arguments)}:filter1:filter2}function readGlobalSchema(){if(db.verno=idbdb.version/10,db._dbSchema=globalSchema={},dbStoreNames=slice(idbdb.objectStoreNames,0),0!==dbStoreNames.length){var trans=idbdb.transaction(safariMultiStoreFix(dbStoreNames),"readonly");dbStoreNames.forEach(function(storeName){for(var store=trans.objectStore(storeName),keyPath=store.keyPath,dotted=keyPath&&"string"==typeof keyPath&&keyPath.indexOf(".")!==-1,primKey=new IndexSpec(keyPath,keyPath||"",!1,!1,!!store.autoIncrement,keyPath&&"string"!=typeof keyPath,dotted),indexes=[],j=0;j0&&(autoSchema=!1),!indexedDB)throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using old Safari versions, make sure to include indexedDB polyfill.");var req=autoSchema?indexedDB.open(dbName):indexedDB.open(dbName,Math.round(10*db.verno));if(!req)throw new exceptions.MissingAPI("IndexedDB API not available");req.onerror=wrap(eventRejectHandler(reject)),req.onblocked=wrap(fireOnBlocked),req.onupgradeneeded=wrap(function(e){if(upgradeTransaction=req.transaction,autoSchema&&!db._allowEmptyDB){req.onerror=preventDefault,upgradeTransaction.abort(),req.result.close();var delreq=indexedDB.deleteDatabase(dbName);delreq.onsuccess=delreq.onerror=wrap(function(){reject(new exceptions.NoSuchDatabase("Database "+dbName+" doesnt exist"))})}else{upgradeTransaction.onerror=wrap(eventRejectHandler(reject));var oldVer=e.oldVersion>Math.pow(2,62)?0:e.oldVersion;runUpgraders(oldVer/10,upgradeTransaction,reject,req)}},reject),req.onsuccess=wrap(function(){if(upgradeTransaction=null,idbdb=req.result,connections.push(db),autoSchema)readGlobalSchema();else if(idbdb.objectStoreNames.length>0)try{adjustToExistingIndexNames(globalSchema,idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames),READONLY))}catch(e){}idbdb.onversionchange=wrap(function(ev){db._vcFired=!0,db.on("versionchange").fire(ev)}),hasNativeGetDatabaseNames||globalDatabaseList(function(databaseNames){if(databaseNames.indexOf(dbName)===-1)return databaseNames.push(dbName)}),resolve()},reject)})]).then(function(){return Dexie.vip(db.on.ready.fire)}).then(function(){return isBeingOpened=!1,db}).catch(function(err){try{upgradeTransaction&&upgradeTransaction.abort()}catch(e){}return isBeingOpened=!1,db.close(),dbOpenError=err,rejection(dbOpenError,dbUncaught)}).finally(function(){openComplete=!0,resolveDbReady()})},this.close=function(){var idx=connections.indexOf(db);if(idx>=0&&connections.splice(idx,1),idbdb){try{idbdb.close()}catch(e){}idbdb=null}autoOpen=!1,dbOpenError=new exceptions.DatabaseClosed,isBeingOpened&&cancelOpen(dbOpenError),dbReadyPromise=new Promise(function(resolve){dbReadyResolve=resolve}),openCanceller=new Promise(function(_,reject){cancelOpen=reject})},this.delete=function(){var hasArguments=arguments.length>0;return new Promise(function(resolve,reject){function doDelete(){db.close();var req=indexedDB.deleteDatabase(dbName);req.onsuccess=wrap(function(){hasNativeGetDatabaseNames||globalDatabaseList(function(databaseNames){var pos=databaseNames.indexOf(dbName);if(pos>=0)return databaseNames.splice(pos,1)}),resolve()}),req.onerror=wrap(eventRejectHandler(reject)),req.onblocked=fireOnBlocked}if(hasArguments)throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()");isBeingOpened?dbReadyPromise.then(doDelete):doDelete()}).uncaught(dbUncaught)},this.backendDB=function(){return idbdb},this.isOpen=function(){return null!==idbdb},this.hasFailed=function(){return null!==dbOpenError},this.dynamicallyOpened=function(){return autoSchema},this.name=dbName,setProp(this,"tables",{get:function(){return keys(allTables).map(function(name){return allTables[name]})}}),this.on=Events(this,"error","populate","blocked","versionchange",{ready:[promisableChain,nop]}),this.on.error.subscribe=deprecated("Dexie.on.error",this.on.error.subscribe),this.on.error.unsubscribe=deprecated("Dexie.on.error.unsubscribe",this.on.error.unsubscribe),this.on.ready.subscribe=override(this.on.ready.subscribe,function(subscribe){return function(subscriber,bSticky){Dexie.vip(function(){openComplete?(dbOpenError||Promise.resolve().then(subscriber),bSticky&&subscribe(subscriber)):(subscribe(subscriber),bSticky||subscribe(function unsubscribe(){db.on.ready.unsubscribe(subscriber),db.on.ready.unsubscribe(unsubscribe)}))})}}),fakeAutoComplete(function(){db.on("populate").fire(db._createTransaction(READWRITE,dbStoreNames,globalSchema)),db.on("error").fire(new Error)}),this.transaction=function(mode,tableInstances,scopeFunc){function enterTransactionScope(resolve){var parentPSD=PSD;resolve(Promise.resolve().then(function(){return newScope(function(){PSD.transless=PSD.transless||parentPSD;var trans=db._createTransaction(mode,storeNames,globalSchema,parentTransaction);PSD.trans=trans,parentTransaction?trans.idbtrans=parentTransaction.idbtrans:trans.create();var tableArgs=storeNames.map(function(name){return allTables[name]});tableArgs.push(trans);var returnValue;return Promise.follow(function(){if(returnValue=scopeFunc.apply(trans,tableArgs))if("function"==typeof returnValue.next&&"function"==typeof returnValue.throw)returnValue=awaitIterator(returnValue);else if("function"==typeof returnValue.then&&!hasOwn(returnValue,"_PSD"))throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: "+scopeFunc.toString())}).uncaught(dbUncaught).then(function(){return parentTransaction&&trans._resolve(),trans._completion}).then(function(){return returnValue}).catch(function(e){return trans._reject(e),rejection(e)})})}))}var i=arguments.length;if(i<2)throw new exceptions.InvalidArgument("Too few arguments");for(var args=new Array(i-1);--i;)args[i-1]=arguments[i];scopeFunc=args.pop();var tables=flatten(args),parentTransaction=PSD.trans;parentTransaction&&parentTransaction.db===db&&mode.indexOf("!")===-1||(parentTransaction=null);var onlyIfCompatible=mode.indexOf("?")!==-1;mode=mode.replace("!","").replace("?","");try{var storeNames=tables.map(function(table){var storeName=table instanceof Table?table.name:table;if("string"!=typeof storeName)throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return storeName});if("r"==mode||mode==READONLY)mode=READONLY;else{if("rw"!=mode&&mode!=READWRITE)throw new exceptions.InvalidArgument("Invalid transaction mode: "+mode);mode=READWRITE}if(parentTransaction){if(parentTransaction.mode===READONLY&&mode===READWRITE){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");parentTransaction=null}parentTransaction&&storeNames.forEach(function(storeName){if(parentTransaction&&parentTransaction.storeNames.indexOf(storeName)===-1){if(!onlyIfCompatible)throw new exceptions.SubTransaction("Table "+storeName+" not included in parent transaction.");parentTransaction=null}})}}catch(e){return parentTransaction?parentTransaction._promise(null,function(_,reject){reject(e)}):rejection(e,dbUncaught)}return parentTransaction?parentTransaction._promise(mode,enterTransactionScope,"lock"):db._whenReady(enterTransactionScope)},this.table=function(tableName){if(fake&&autoSchema)return new WriteableTable(tableName);if(!hasOwn(allTables,tableName))throw new exceptions.InvalidTable("Table "+tableName+" does not exist");return allTables[tableName]},props(Table.prototype,{_trans:function(mode,fn,writeLocked){var trans=PSD.trans;return trans&&trans.db===db?trans._promise(mode,fn,writeLocked):tempTransaction(mode,[this.name],fn)},_idbstore:function(mode,fn,writeLocked){function supplyIdbStore(resolve,reject,trans){fn(resolve,reject,trans.idbtrans.objectStore(tableName),trans)}if(fake)return new Promise(fn);var trans=PSD.trans,tableName=this.name;return trans&&trans.db===db?trans._promise(mode,supplyIdbStore,writeLocked):tempTransaction(mode,[this.name],supplyIdbStore)},get:function(key,cb){var self=this;return this._idbstore(READONLY,function(resolve,reject,idbstore){fake&&resolve(self.schema.instanceTemplate);var req=idbstore.get(key);req.onerror=eventRejectHandler(reject),req.onsuccess=wrap(function(){resolve(self.hook.reading.fire(req.result))},reject)}).then(cb)},where:function(indexName){return new WhereClause(this,indexName)},count:function(cb){return this.toCollection().count(cb)},offset:function(_offset){return this.toCollection().offset(_offset)},limit:function(numRows){return this.toCollection().limit(numRows)},reverse:function(){return this.toCollection().reverse()},filter:function(filterFunction){return this.toCollection().and(filterFunction)},each:function(fn){return this.toCollection().each(fn)},toArray:function(cb){return this.toCollection().toArray(cb)},orderBy:function(index){return new this._collClass(new WhereClause(this,index))},toCollection:function(){return new this._collClass(new WhereClause(this))},mapToClass:function(constructor,structure){this.schema.mappedClass=constructor;var instanceTemplate=Object.create(constructor.prototype);structure&&applyStructure(instanceTemplate,structure),this.schema.instanceTemplate=instanceTemplate;var readHook=function(obj){if(!obj)return obj;var res=Object.create(constructor.prototype);for(var m in obj)if(hasOwn(obj,m))try{res[m]=obj[m]}catch(_){}return res};return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=readHook,this.hook("reading",readHook),constructor},defineClass:function(structure){return this.mapToClass(Dexie.defineClass(structure),structure)}}),derive(WriteableTable).from(Table).extend({bulkDelete:function(keys$$1){return this.hook.deleting.fire===nop?this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){resolve(_bulkDelete(idbstore,trans,keys$$1,!1,nop))}):this.where(":id").anyOf(keys$$1).delete().then(function(){})},bulkPut:function(objects,keys$$1){var _this=this;return this._idbstore(READWRITE,function(resolve,reject,idbstore){if(!idbstore.keyPath&&!_this.schema.primKey.auto&&!keys$$1)throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");if(idbstore.keyPath&&keys$$1)throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(keys$$1&&keys$$1.length!==objects.length)throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");if(0===objects.length)return resolve();var req,errorHandler,done=function(result){0===errorList.length?resolve(result):reject(new BulkError(_this.name+".bulkPut(): "+errorList.length+" of "+numObjs+" operations failed",errorList))},errorList=[],numObjs=objects.length,table=_this;if(_this.hook.creating.fire===nop&&_this.hook.updating.fire===nop){errorHandler=BulkErrorHandlerCatchAll(errorList);for(var i=0,l=objects.length;i=0;--i){var key=effectiveKeys[i];(null==key||objectLookup[key])&&(objsToAdd.push(objects[i]),keys$$1&&keysToAdd.push(key),null!=key&&(objectLookup[key]=null))}return objsToAdd.reverse(),keys$$1&&keysToAdd.reverse(),table.bulkAdd(objsToAdd,keysToAdd)}).then(function(lastAddedKey){var lastEffectiveKey=effectiveKeys[effectiveKeys.length-1];return null!=lastEffectiveKey?lastEffectiveKey:lastAddedKey}):table.bulkAdd(objects);promise.then(done).catch(BulkError,function(e){errorList=errorList.concat(e.failures),done()}).catch(reject)}},"locked")},bulkAdd:function(objects,keys$$1){var self=this,creatingHook=this.hook.creating.fire;return this._idbstore(READWRITE,function(resolve,reject,idbstore,trans){function done(result){0===errorList.length?resolve(result):reject(new BulkError(self.name+".bulkAdd(): "+errorList.length+" of "+numObjs+" operations failed",errorList))}if(!idbstore.keyPath&&!self.schema.primKey.auto&&!keys$$1)throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");if(idbstore.keyPath&&keys$$1)throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(keys$$1&&keys$$1.length!==objects.length)throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");if(0===objects.length)return resolve();var req,errorHandler,successHandler,errorList=[],numObjs=objects.length;if(creatingHook!==nop){var hookCtx,keyPath=idbstore.keyPath;errorHandler=BulkErrorHandlerCatchAll(errorList,null,!0),successHandler=hookedEventSuccessHandler(null),tryCatch(function(){for(var i=0,l=objects.length;i0&&!this._locked();){var fnAndPSD=this._blockedFuncs.shift();try{usePSD(fnAndPSD[1],fnAndPSD[0])}catch(e){}}return this},_locked:function(){return this._reculock&&PSD.lockOwnerFor!==this},create:function(idbtrans){var _this3=this;if(assert(!this.idbtrans),!idbtrans&&!idbdb)switch(dbOpenError&&dbOpenError.name){case"DatabaseClosedError":throw new exceptions.DatabaseClosed(dbOpenError);case"MissingAPIError":throw new exceptions.MissingAPI(dbOpenError.message,dbOpenError);default:throw new exceptions.OpenFailed(dbOpenError)}if(!this.active)throw new exceptions.TransactionInactive;return assert(null===this._completion._state),idbtrans=this.idbtrans=idbtrans||idbdb.transaction(safariMultiStoreFix(this.storeNames),this.mode),idbtrans.onerror=wrap(function(ev){preventDefault(ev),_this3._reject(idbtrans.error)}),idbtrans.onabort=wrap(function(ev){preventDefault(ev),_this3.active&&_this3._reject(new exceptions.Abort),_this3.active=!1,_this3.on("abort").fire(ev)}),idbtrans.oncomplete=wrap(function(){_this3.active=!1,_this3._resolve()}),this},_promise:function(mode,fn,bWriteLock){var self=this,p=self._locked()?new Promise(function(resolve,reject){self._blockedFuncs.push([function(){self._promise(mode,fn,bWriteLock).then(resolve,reject)},PSD])}):newScope(function(){var p_=self.active?new Promise(function(resolve,reject){if(mode===READWRITE&&self.mode!==READWRITE)throw new exceptions.ReadOnly("Transaction is readonly");!self.idbtrans&&mode&&self.create(),bWriteLock&&self._lock(),fn(resolve,reject,self)}):rejection(new exceptions.TransactionInactive);return self.active&&bWriteLock&&p_.finally(function(){self._unlock()}),p_});return p._lib=!0,p.uncaught(dbUncaught)},abort:function(){this.active&&this._reject(new exceptions.Abort),this.active=!1},tables:{get:deprecated("Transaction.tables",function(){return arrayToObject(this.storeNames,function(name){return[name,allTables[name]]})},"Use db.tables()")},complete:deprecated("Transaction.complete()",function(cb){return this.on("complete",cb)}),error:deprecated("Transaction.error()",function(cb){return this.on("error",cb)}),table:deprecated("Transaction.table()",function(name){if(this.storeNames.indexOf(name)===-1)throw new exceptions.InvalidTable("Table "+name+" not in transaction");return allTables[name]})}),props(WhereClause.prototype,function(){function fail(collectionOrWhereClause,err,T){var collection=collectionOrWhereClause instanceof WhereClause?new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause):collectionOrWhereClause;return collection._ctx.error=T?new T(err):new TypeError(err),collection}function emptyCollection(whereClause){return new whereClause._ctx.collClass(whereClause,function(){return IDBKeyRange.only("")}).limit(0)}function upperFactory(dir){return"next"===dir?function(s){return s.toUpperCase()}:function(s){return s.toLowerCase()}}function lowerFactory(dir){return"next"===dir?function(s){return s.toLowerCase()}:function(s){return s.toUpperCase()}}function nextCasing(key,lowerKey,upperNeedle,lowerNeedle,cmp,dir){for(var length=Math.min(key.length,lowerNeedle.length),llp=-1,i=0;i=0?key.substr(0,llp)+lowerKey[llp]+upperNeedle.substr(llp+1):null;cmp(key[i],lwrKeyChar)<0&&(llp=i)}return length0)&&(lowestPossibleCasing=casing)}return advance(null!==lowestPossibleCasing?function(){cursor.continue(lowestPossibleCasing+nextKeySuffix)}:resolve),!1}),c}return{between:function(lower,upper,includeLower,includeUpper){includeLower=includeLower!==!1,includeUpper=includeUpper===!0;try{return cmp(lower,upper)>0||0===cmp(lower,upper)&&(includeLower||includeUpper)&&(!includeLower||!includeUpper)?emptyCollection(this):new this._ctx.collClass(this,function(){return IDBKeyRange.bound(lower,upper,!includeLower,!includeUpper)})}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}},equals:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.only(value)})},above:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.lowerBound(value,!0)})},aboveOrEqual:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.lowerBound(value)})},below:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.upperBound(value,!0)})},belowOrEqual:function(value){return new this._ctx.collClass(this,function(){return IDBKeyRange.upperBound(value)})},startsWith:function(str){return"string"!=typeof str?fail(this,STRING_EXPECTED):this.between(str,str+maxString,!0,!0)},startsWithIgnoreCase:function(str){return""===str?this.startsWith(str):addIgnoreCaseAlgorithm(this,function(x,a){return 0===x.indexOf(a[0])},[str],maxString)},equalsIgnoreCase:function(str){return addIgnoreCaseAlgorithm(this,function(x,a){return x===a[0]},[str],"")},anyOfIgnoreCase:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.indexOf(x)!==-1},set,"")},startsWithAnyOfIgnoreCase:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return 0===set.length?emptyCollection(this):addIgnoreCaseAlgorithm(this,function(x,a){return a.some(function(n){return 0===x.indexOf(n)})},set,maxString)},anyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments),compare=ascending;try{set.sort(compare)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}if(0===set.length)return emptyCollection(this);var c=new this._ctx.collClass(this,function(){return IDBKeyRange.bound(set[0],set[set.length-1])});c._ondirectionchange=function(direction){compare="next"===direction?ascending:descending,set.sort(compare)};var i=0;return c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;compare(key,set[i])>0;)if(++i,i===set.length)return advance(resolve),!1;return 0===compare(key,set[i])||(advance(function(){cursor.continue(set[i])}),!1)}),c},notEqual:function(value){return this.inAnyRange([[-(1/0),value],[value,maxKey]],{includeLowers:!1,includeUppers:!1})},noneOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);if(0===set.length)return new this._ctx.collClass(this);try{set.sort(ascending)}catch(e){return fail(this,INVALID_KEY_ARGUMENT)}var ranges=set.reduce(function(res,val){return res?res.concat([[res[res.length-1][1],val]]):[[-(1/0),val]]},null);return ranges.push([set[set.length-1],maxKey]),this.inAnyRange(ranges,{includeLowers:!1,includeUppers:!1})},inAnyRange:function(ranges,options){function addRange(ranges,newRange){for(var i=0,l=ranges.length;i0){range[0]=min(range[0],newRange[0]),range[1]=max(range[1],newRange[1]);break}}return i===l&&ranges.push(newRange),ranges}function rangeSorter(a,b){return sortDirection(a[0],b[0])}function keyWithinCurrentRange(key){return!keyIsBeyondCurrentEntry(key)&&!keyIsBeforeCurrentEntry(key)}var ctx=this._ctx;if(0===ranges.length)return emptyCollection(this);if(!ranges.every(function(range){return void 0!==range[0]&&void 0!==range[1]&&ascending(range[0],range[1])<=0}))return fail(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",exceptions.InvalidArgument);var set,includeLowers=!options||options.includeLowers!==!1,includeUppers=options&&options.includeUppers===!0,sortDirection=ascending;try{set=ranges.reduce(addRange,[]),set.sort(rangeSorter)}catch(ex){return fail(this,INVALID_KEY_ARGUMENT)}var i=0,keyIsBeyondCurrentEntry=includeUppers?function(key){return ascending(key,set[i][1])>0}:function(key){return ascending(key,set[i][1])>=0},keyIsBeforeCurrentEntry=includeLowers?function(key){return descending(key,set[i][0])>0}:function(key){return descending(key,set[i][0])>=0},checkKey=keyIsBeyondCurrentEntry,c=new ctx.collClass(this,function(){return IDBKeyRange.bound(set[0][0],set[set.length-1][1],!includeLowers,!includeUppers)});return c._ondirectionchange=function(direction){"next"===direction?(checkKey=keyIsBeyondCurrentEntry,sortDirection=ascending):(checkKey=keyIsBeforeCurrentEntry,sortDirection=descending),set.sort(rangeSorter)},c._addAlgorithm(function(cursor,advance,resolve){for(var key=cursor.key;checkKey(key);)if(++i,i===set.length)return advance(resolve),!1;return!!keyWithinCurrentRange(key)||0!==cmp(key,set[i][1])&&0!==cmp(key,set[i][0])&&(advance(function(){sortDirection===ascending?cursor.continue(set[i][0]):cursor.continue(set[i][1])}),!1)}),c},startsWithAnyOf:function(){var set=getArrayOf.apply(NO_CHAR_ARRAY,arguments);return set.every(function(s){return"string"==typeof s})?0===set.length?emptyCollection(this):this.inAnyRange(set.map(function(str){return[str,str+maxString]})):fail(this,"startsWithAnyOf() only works with strings")}}}),props(Collection.prototype,function(){function addFilter(ctx,fn){ctx.filter=combine(ctx.filter,fn)}function addReplayFilter(ctx,factory,isLimitFilter){var curr=ctx.replayFilter;ctx.replayFilter=curr?function(){return combine(curr(),factory())}:factory,ctx.justLimit=isLimitFilter&&!curr}function addMatchFilter(ctx,fn){ctx.isMatch=combine(ctx.isMatch,fn)}function getIndexOrStore(ctx,store){if(ctx.isPrimKey)return store;var indexSpec=ctx.table.schema.idxByName[ctx.index];if(!indexSpec)throw new exceptions.Schema("KeyPath "+ctx.index+" on object store "+store.name+" is not indexed");return store.index(indexSpec.name)}function openCursor(ctx,store){var idxOrStore=getIndexOrStore(ctx,store);return ctx.keysOnly&&"openKeyCursor"in idxOrStore?idxOrStore.openKeyCursor(ctx.range||null,ctx.dir+ctx.unique):idxOrStore.openCursor(ctx.range||null,ctx.dir+ctx.unique)}function iter(ctx,fn,resolve,reject,idbstore){var filter=ctx.replayFilter?combine(ctx.filter,ctx.replayFilter()):ctx.filter;ctx.or?function(){function resolveboth(){2===++resolved&&resolve()}function union(item,cursor,advance){if(!filter||filter(cursor,advance,resolveboth,reject)){var key=cursor.primaryKey.toString();hasOwn(set,key)||(set[key]=!0,fn(item,cursor,advance))}}var set={},resolved=0;ctx.or._iterate(union,resolveboth,reject,idbstore),iterate(openCursor(ctx,idbstore),ctx.algorithm,union,resolveboth,reject,!ctx.keysOnly&&ctx.valueMapper)}():iterate(openCursor(ctx,idbstore),combine(ctx.algorithm,filter),fn,resolve,reject,!ctx.keysOnly&&ctx.valueMapper)}function getInstanceTemplate(ctx){return ctx.table.schema.instanceTemplate}return{_read:function(fn,cb){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READONLY,fn).then(cb)},_write:function(fn){var ctx=this._ctx;return ctx.error?ctx.table._trans(null,function(resolve,reject){reject(ctx.error)}):ctx.table._idbstore(READWRITE,fn,"locked")},_addAlgorithm:function(fn){var ctx=this._ctx;ctx.algorithm=combine(ctx.algorithm,fn)},_iterate:function(fn,resolve,reject,idbstore){return iter(this._ctx,fn,resolve,reject,idbstore)},clone:function(props$$1){var rv=Object.create(this.constructor.prototype),ctx=Object.create(this._ctx);return props$$1&&extend(ctx,props$$1),rv._ctx=ctx,rv},raw:function(){return this._ctx.valueMapper=null,this},each:function(fn){var ctx=this._ctx;if(fake){var item=getInstanceTemplate(ctx),primKeyPath=ctx.table.schema.primKey.keyPath,key=getByKeyPath(item,ctx.index?ctx.table.schema.idxByName[ctx.index].keyPath:primKeyPath),primaryKey=getByKeyPath(item,primKeyPath);fn(item,{key:key,primaryKey:primaryKey})}return this._read(function(resolve,reject,idbstore){iter(ctx,fn,resolve,reject,idbstore)})},count:function count(cb){if(fake)return Promise.resolve(0).then(cb);var ctx=this._ctx;if(isPlainKeyRange(ctx,!0))return this._read(function(resolve,reject,idbstore){var idx=getIndexOrStore(ctx,idbstore),req=ctx.range?idx.count(ctx.range):idx.count();req.onerror=eventRejectHandler(reject),req.onsuccess=function(e){resolve(Math.min(e.target.result,ctx.limit))}},cb);var count=0;return this._read(function(resolve,reject,idbstore){iter(ctx,function(){return++count,!1},function(){resolve(count)},reject,idbstore)},cb)},sortBy:function(keyPath,cb){function getval(obj,i){return i?getval(obj[parts[i]],i-1):obj[lastPart]}function sorter(a,b){var aVal=getval(a,lastIndex),bVal=getval(b,lastIndex);return aValbVal?order:0}var parts=keyPath.split(".").reverse(),lastPart=parts[0],lastIndex=parts.length-1,order="next"===this._ctx.dir?1:-1;return this.toArray(function(a){return a.sort(sorter)}).then(cb)},toArray:function(cb){var ctx=this._ctx;return this._read(function(resolve,reject,idbstore){if(fake&&resolve([getInstanceTemplate(ctx)]),hasGetAll&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0){var readingHook=ctx.table.hook.reading.fire,idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?idxOrStore.getAll(ctx.range,ctx.limit):idxOrStore.getAll(ctx.range);req.onerror=eventRejectHandler(reject),req.onsuccess=readingHook===mirror?eventSuccessHandler(resolve):wrap(eventSuccessHandler(function(res){try{resolve(res.map(readingHook))}catch(e){reject(e)}}))}else{var a=[];iter(ctx,function(item){a.push(item)},function(){resolve(a)},reject,idbstore)}},cb)},offset:function(_offset2){var ctx=this._ctx;return _offset2<=0?this:(ctx.offset+=_offset2,isPlainKeyRange(ctx)?addReplayFilter(ctx,function(){var offsetLeft=_offset2;return function(cursor,advance){return 0===offsetLeft||(1===offsetLeft?(--offsetLeft,!1):(advance(function(){cursor.advance(offsetLeft),offsetLeft=0}),!1))}}):addReplayFilter(ctx,function(){var offsetLeft=_offset2;return function(){return--offsetLeft<0}}),this)},limit:function(numRows){return this._ctx.limit=Math.min(this._ctx.limit,numRows),addReplayFilter(this._ctx,function(){var rowsLeft=numRows;return function(cursor,advance,resolve){return--rowsLeft<=0&&advance(resolve),rowsLeft>=0}},!0),this},until:function(filterFunction,bIncludeStopEntry){var ctx=this._ctx;return fake&&filterFunction(getInstanceTemplate(ctx)),addFilter(this._ctx,function(cursor,advance,resolve){return!filterFunction(cursor.value)||(advance(resolve),bIncludeStopEntry)}),this},first:function(cb){return this.limit(1).toArray(function(a){return a[0]}).then(cb)},last:function(cb){return this.reverse().first(cb)},filter:function(filterFunction){return fake&&filterFunction(getInstanceTemplate(this._ctx)),addFilter(this._ctx,function(cursor){return filterFunction(cursor.value)}),addMatchFilter(this._ctx,filterFunction),this},and:function(filterFunction){return this.filter(filterFunction)},or:function(indexName){return new WhereClause(this._ctx.table,indexName,this)},reverse:function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},desc:function(){return this.reverse()},eachKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,this.each(function(val,cursor){cb(cursor.key,cursor)})},eachUniqueKey:function(cb){return this._ctx.unique="unique",this.eachKey(cb)},eachPrimaryKey:function(cb){var ctx=this._ctx;return ctx.keysOnly=!ctx.isMatch,this.each(function(val,cursor){cb(cursor.primaryKey,cursor)})},keys:function(cb){var ctx=this._ctx;ctx.keysOnly=!ctx.isMatch;var a=[];return this.each(function(item,cursor){a.push(cursor.key)}).then(function(){return a}).then(cb)},primaryKeys:function(cb){var ctx=this._ctx;if(hasGetAll&&"next"===ctx.dir&&isPlainKeyRange(ctx,!0)&&ctx.limit>0)return this._read(function(resolve,reject,idbstore){var idxOrStore=getIndexOrStore(ctx,idbstore),req=ctx.limit<1/0?idxOrStore.getAllKeys(ctx.range,ctx.limit):idxOrStore.getAllKeys(ctx.range);req.onerror=eventRejectHandler(reject),req.onsuccess=eventSuccessHandler(resolve)}).then(cb);ctx.keysOnly=!ctx.isMatch;var a=[];return this.each(function(item,cursor){a.push(cursor.primaryKey)}).then(function(){return a}).then(cb)},uniqueKeys:function(cb){return this._ctx.unique="unique",this.keys(cb)},firstKey:function(cb){return this.limit(1).keys(function(a){return a[0]}).then(cb)},lastKey:function(cb){return this.reverse().firstKey(cb)},distinct:function(){var ctx=this._ctx,idx=ctx.index&&ctx.table.schema.idxByName[ctx.index];if(!idx||!idx.multi)return this;var set={};return addFilter(this._ctx,function(cursor){var strKey=cursor.primaryKey.toString(),found=hasOwn(set,strKey);return set[strKey]=!0,!found}),this}}}),derive(WriteableCollection).from(Collection).extend({modify:function(changes){var self=this,ctx=this._ctx,hook=ctx.table.hook,updatingHook=hook.updating.fire,deletingHook=hook.deleting.fire;return fake&&"function"==typeof changes&&changes.call({value:ctx.table.schema.instanceTemplate},ctx.table.schema.instanceTemplate),this._write(function(resolve,reject,idbstore,trans){function modifyItem(item,cursor){function onerror(e){return failures.push(e),failKeys.push(thisContext.primKey),checkFinished(),!0}currentKey=cursor.primaryKey;var thisContext={primKey:cursor.primaryKey,value:item,onsuccess:null,onerror:null};if(modifyer.call(thisContext,item,thisContext)!==!1){var bDelete=!hasOwn(thisContext,"value");++count,tryCatch(function(){var req=bDelete?cursor.delete():cursor.update(thisContext.value);req._hookCtx=thisContext,req.onerror=hookedEventRejectHandler(onerror),req.onsuccess=hookedEventSuccessHandler(function(){++successCount,checkFinished()})},onerror)}else thisContext.onsuccess&&thisContext.onsuccess(thisContext.value)}function doReject(e){return e&&(failures.push(e),failKeys.push(currentKey)),reject(new ModifyError("Error modifying one or more objects",failures,successCount,failKeys))}function checkFinished(){iterationComplete&&successCount+failures.length===count&&(failures.length>0?doReject():resolve(successCount))}var modifyer;if("function"==typeof changes)modifyer=updatingHook===nop&&deletingHook===nop?changes:function(item){var origItem=deepClone(item);if(changes.call(this,item,this)===!1)return!1;if(hasOwn(this,"value")){var objectDiff=getObjectDiff(origItem,this.value),additionalChanges=updatingHook.call(this,objectDiff,this.primKey,origItem,trans);additionalChanges&&(item=this.value,keys(additionalChanges).forEach(function(keyPath){setByKeyPath(item,keyPath,additionalChanges[keyPath])}))}else deletingHook.call(this,this.primKey,item,trans)};else if(updatingHook===nop){var keyPaths=keys(changes),numKeys=keyPaths.length;modifyer=function(item){for(var anythingModified=!1,i=0;i99?queue.push(Buffer.concat(data)):queue[lastIndex(queue)]=Buffer.concat(last(queue).concat(data)),queue}if(err)return cb(err);var table=_this.table;d.resolve(pull(toWindow(100,10),_write(writer,reduce,100,cb)))}),d):(cb(new Error("Missing key")),d)}},{key:"read",value:function(key){var _this2=this,p=pushable();return key?(this.exists(key,function(err,exists){return err?p.end(err):exists?void _this2.table.where("key").equals(key).each(function(val){return p.push(toBuffer(val.blob))}).catch(function(err){return p.end(err)}).then(function(){return p.end()}):p.end(new Error("Not found"))}),p):(p.end(new Error("Missing key")),p)}},{key:"exists",value:function(key,cb){return cb=cb||function(){},key?void this.table.where("key").equals(key).count().then(function(val){return cb(null,Boolean(val))}).catch(cb):cb(new Error("Missing key"))}},{key:"remove",value:function(key,cb){if(cb=cb||function(){},!key)return cb(new Error("Missing key"));var coll=this.table.where("key").equals(key);coll.count(function(count){return count>0?coll.delete():null}).then(function(){return cb()}).catch(cb)}},{key:"table",get:function(){return this.db[this.path]}}]),IdbBlobStore}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function isTypedArray(arr){return isStrictTypedArray(arr)||isLooseTypedArray(arr)}function isStrictTypedArray(arr){return arr instanceof Int8Array||arr instanceof Int16Array||arr instanceof Int32Array||arr instanceof Uint8Array||arr instanceof Uint8ClampedArray||arr instanceof Uint16Array||arr instanceof Uint32Array||arr instanceof Float32Array||arr instanceof Float64Array}function isLooseTypedArray(arr){return names[toString.call(arr)]}module.exports=isTypedArray,isTypedArray.strict=isStrictTypedArray,isTypedArray.loose=isLooseTypedArray;var toString=Object.prototype.toString,names={"[object Int8Array]":!0,"[object Int16Array]":!0,"[object Int32Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Uint16Array]":!0,"[object Uint32Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0}},function(module,exports,__webpack_require__){"use strict";(function(setImmediate){var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};module.exports=function(){function _releaser(key,exec){return function(done){return function(){_release(key,exec),done&&done.apply(null,arguments)}}}function _release(key,exec){var i=locked[key].indexOf(exec);~i&&(locked[key].splice(i,1),isLocked(key)?next(function(){locked[key][0](_releaser(key,locked[key][0]))}):delete locked[key])}function _lock(key,exec){return isLocked(key)?(locked[key].push(exec),!1):(locked[key]=[exec],!0)}function lock(key,exec){if(Array.isArray(key)){var keys,locks,l,_ret=function(){var releaser=function(done){return function(){var args=[].slice.call(arguments);for(var key in l)_release(key,l[key]);done.apply(this,args)}};return keys=key.length,locks=[],l={},key.forEach(function(key){function ready(){n++||--keys||exec(releaser)}var n=0;l[key]=ready,_lock(key,ready)&&ready()}),{v:void 0}}();if("object"===("undefined"==typeof _ret?"undefined":_typeof(_ret)))return _ret.v}_lock(key,exec)&&exec(_releaser(key,exec))}function isLocked(key){return!!Array.isArray(locked[key])&&!!locked[key].length}var next="undefined"==typeof setImmediate?setTimeout:setImmediate,locked={};return lock.isLocked=isLocked,lock}}).call(exports,__webpack_require__(10).setImmediate)},function(module,exports,__webpack_require__){"use strict";(function(global,module){function arraySome(array,predicate){for(var index=-1,length=array?array.length:0;++index-1}function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?data.push([key,value]):data[index][1]=value,this}function MapCache(entries){var index=-1,length=entries?entries.length:0;for(this.clear();++indexarrLength))return!1;var stacked=stack.get(array);if(stacked&&stack.get(other))return stacked==other;var index=-1,result=!0,seen=bitmask&UNORDERED_COMPARE_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function isSymbol(value){return"symbol"==("undefined"==typeof value?"undefined":_typeof(value))||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}function toString(value){return null==value?"":baseToString(value)}function get(object,path,defaultValue){var result=null==object?void 0:baseGet(object,path);return void 0===result?defaultValue:result}function hasIn(object,path){return null!=object&&hasPath(object,path,baseHasIn)}function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}function identity(value){return value}function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path)}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},LARGE_ARRAY_SIZE=200,FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",UNORDERED_COMPARE_FLAG=1,PARTIAL_COMPARE_FLAG=2,INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",genTag="[object GeneratorFunction]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",promiseTag="[object Promise]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",reIsDeepProp=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,reIsPlainProp=/^\w*$/,reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reTrim=/^\s+|\s+$/g,reEscapeChar=/\\(\\)?/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsHostCtor=/^\[object .+?Constructor\]$/,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0,typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1; +var freeParseInt=parseInt,freeGlobal="object"==("undefined"==typeof global?"undefined":_typeof(global))&&global&&global.Object===Object&&global,freeSelf="object"==("undefined"==typeof self?"undefined":_typeof(self))&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")(),freeExports="object"==_typeof(exports)&&exports&&!exports.nodeType&&exports,freeModule=freeExports&&"object"==_typeof(module)&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=function(){try{return freeProcess&&freeProcess.binding("util")}catch(e){}}(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),_Symbol=root.Symbol,Uint8Array=root.Uint8Array,propertyIsEnumerable=objectProto.propertyIsEnumerable,splice=arrayProto.splice,nativeKeys=overArg(Object.keys,Object),nativeMax=Math.max,DataView=getNative(root,"DataView"),Map=getNative(root,"Map"),Promise=getNative(root,"Promise"),Set=getNative(root,"Set"),WeakMap=getNative(root,"WeakMap"),nativeCreate=getNative(Object,"create"),dataViewCtorString=toSource(DataView),mapCtorString=toSource(Map),promiseCtorString=toSource(Promise),setCtorString=toSource(Set),weakMapCtorString=toSource(WeakMap),symbolProto=_Symbol?_Symbol.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet,ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet,MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet,SetCache.prototype.add=SetCache.prototype.push=setCacheAdd,SetCache.prototype.has=setCacheHas,Stack.prototype.clear=stackClear,Stack.prototype.delete=stackDelete,Stack.prototype.get=stackGet,Stack.prototype.has=stackHas,Stack.prototype.set=stackSet;var getTag=baseGetTag;(DataView&&getTag(new DataView(new ArrayBuffer(1)))!=dataViewTag||Map&&getTag(new Map)!=mapTag||Promise&&getTag(Promise.resolve())!=promiseTag||Set&&getTag(new Set)!=setTag||WeakMap&&getTag(new WeakMap)!=weakMapTag)&&(getTag=function(value){var result=objectToString.call(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):void 0;if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});var stringToPath=memoize(function(string){string=toString(string);var result=[];return reLeadingDot.test(string)&&result.push(""),string.replace(rePropName,function(match,number,quote,string){result.push(quote?string.replace(reEscapeChar,"$1"):number||match)}),result});memoize.Cache=MapCache;var isArray=Array.isArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=findIndex}).call(exports,__webpack_require__(4),__webpack_require__(50)(module))},function(module,exports){"use strict";function baseSlice(array,start,end){var index=-1,length=array.length;start<0&&(start=-start>length?0:length+start),end=end>length?length:end,end<0&&(end+=length),length=start>end?0:end-start>>>0,start>>>=0;for(var result=Array(length);++index-1&&value%1==0&&value-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isObject(value){var type="undefined"==typeof value?"undefined":_typeof(value);return!!value&&("object"==type||"function"==type)}function isObjectLike(value){return!!value&&"object"==("undefined"==typeof value?"undefined":_typeof(value))}function isSymbol(value){return"symbol"==("undefined"==typeof value?"undefined":_typeof(value))||isObjectLike(value)&&objectToString.call(value)==symbolTag}function toFinite(value){if(!value)return 0===value?value:0;if(value=toNumber(value),value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER}return value===value?value:0}function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0}function toNumber(value){if("number"==typeof value)return value;if(isSymbol(value))return NAN;if(isObject(value)){var other="function"==typeof value.valueOf?value.valueOf():value;value=isObject(other)?other+"":other}if("string"!=typeof value)return 0===value?value:+value;value=value.replace(reTrim,"");var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},INFINITY=1/0,MAX_SAFE_INTEGER=9007199254740991,MAX_INTEGER=1.7976931348623157e308,NAN=NaN,funcTag="[object Function]",genTag="[object GeneratorFunction]",symbolTag="[object Symbol]",reTrim=/^\s+|\s+$/g,reIsBadHex=/^[-+]0x[0-9a-f]+$/i,reIsBinary=/^0b[01]+$/i,reIsOctal=/^0o[0-7]+$/i,reIsUint=/^(?:0|[1-9]\d*)$/,freeParseInt=parseInt,objectProto=Object.prototype,objectToString=objectProto.toString;module.exports=slice},function(module,exports,__webpack_require__){"use strict";(function(process){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=levelIdx}}]),Logger}();module.exports={Colors:Colors,LogLevels:LogLevels,setLogLevel:function(level){GlobalLogLevel=level},setLogfile:function(filename){GlobalLogfile=filename},create:function(category,options){var logger=new Logger(category,options);return logger},forceBrowserMode:function(force){return isNodejs=!force}}}).call(exports,__webpack_require__(1))},function(module,exports){"use strict";module.exports=function(fun){return function next(a,b,c){var loop=!0,sync=!1;do sync=!0,loop=!1,fun.call(function(x,y,z){sync?(a=x,b=y,c=z,loop=!0):next(x,y,z)},a,b,c),sync=!1;while(loop)}}},function(module,exports,__webpack_require__){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};return _classCallCheck(this,CounterStore),options.Index||Object.assign(options,{Index:CounterIndex}),_possibleConstructorReturn(this,(CounterStore.__proto__||Object.getPrototypeOf(CounterStore)).call(this,ipfs,id,dbname,options))}return _inherits(CounterStore,_Store),_createClass(CounterStore,[{key:"inc",value:function(amount){var counter=this._index.get();if(counter)return counter.increment(amount),this._addOperation({op:"COUNTER",key:null,value:counter.payload,meta:{ts:(new Date).getTime()}})}},{key:"value",get:function(){return this._index.get().value}}]),CounterStore}(Store);module.exports=CounterStore},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:[];if(!ipfs)throw new Error("Entry requires ipfs instance");var nexts=null!==next&&next instanceof Array?next.map(function(e){return e.hash?e.hash:e}):[null!==next&&next.hash?next.hash:next],entry={hash:null,payload:data,next:nexts};return Entry.toIpfsHash(ipfs,entry).then(function(hash){return entry.hash=hash,entry})}},{key:"toIpfsHash",value:function(ipfs,entry){if(!ipfs)throw new Error("Entry requires ipfs instance");var data=new Buffer(JSON.stringify(entry));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash){if(!ipfs)throw new Error("Entry requires ipfs instance");if(!hash)throw new Error("Invalid hash: "+hash);return ipfs.object.get(hash,{enc:"base58"}).then(function(obj){var data=JSON.parse(obj.toJSON().data),entry={hash:hash,payload:data.payload,next:data.next};return entry})}},{key:"hasChild",value:function(entry1,entry2){return entry1.next.includes(entry2.hash)}},{key:"compare",value:function(a,b){return a.hash===b.hash}}]),Entry}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=MaxBatchSize&&this._commit(),Entry.create(this._ipfs,data,this._heads).then(function(entry){return _this._heads=[entry.hash],_this._currentBatch.push(entry),entry})}},{key:"join",value:function(other){var _this2=this;if(!other.items)throw new Error("The log to join must be an instance of Log");var newItems=other.items.slice(-Math.max(this.options.maxHistory,1)),diff=differenceWith(newItems,this.items,Entry.compare),final=unionWith(this._currentBatch,diff,Entry.compare);this._items=this._items.concat(final),this._currentBatch=[];var nexts=take(flatten(diff.map(function(f){return f.next})),this.options.maxHistory);return Promise.map(nexts,function(f){var all=_this2.items.map(function(a){return a.hash});return _this2._fetchRecursive(_this2._ipfs,f,all,_this2.options.maxHistory-nexts.length,0).then(function(history){return history.forEach(function(b){return _this2._insert(b)}),history})},{concurrency:1}).then(function(res){return _this2._heads=Log.findHeads(_this2),flatten(res).concat(diff)})}},{key:"_insert",value:function(entry){var _this3=this,indices=entry.next.map(function(next){return _this3._items.map(function(f){return f.hash}).indexOf(next)}),index=indices.length>0?Math.max(Math.max.apply(null,indices)+1,0):0;return this._items.splice(index,0,entry),entry}},{key:"_commit",value:function(){this._items=this._items.concat(this._currentBatch),this._currentBatch=[]}},{key:"_fetchRecursive",value:function(ipfs,hash,all,amount,depth){var _this4=this,isReferenced=function(list,item){return void 0!==list.reverse().find(function(f){return f===item})},result=[];return isReferenced(all,hash)||depth>=amount?Promise.resolve(result):Entry.fromIpfsHash(ipfs,hash).then(function(entry){return result.push(entry),all.push(hash),depth++,Promise.map(entry.next,function(f){return _this4._fetchRecursive(ipfs,f,all,amount,depth)},{concurrency:1}).then(function(res){return flatten(res.concat(result))})})}},{key:"items",get:function(){return this._items.concat(this._currentBatch)}},{key:"snapshot",get:function(){return{id:this.id,items:this._currentBatch.map(function(f){return f.hash})}}}],[{key:"getIpfsHash",value:function(ipfs,log){if(!ipfs)throw new Error("Ipfs instance not defined");var data=new Buffer(JSON.stringify(log.snapshot));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash,options){if(!ipfs)throw new Error("Ipfs instance not defined");if(!hash)throw new Error("Invalid hash: "+hash);options||(options={});var logData=void 0;return ipfs.object.get(hash,{enc:"base58"}).then(function(res){return logData=JSON.parse(res.toJSON().data)}).then(function(res){if(!logData.items)throw new Error("Not a Log instance");return Promise.all(logData.items.map(function(f){return Entry.fromIpfsHash(ipfs,f)}))}).then(function(items){return Object.assign(options,{items:items})}).then(function(items){return new Log(ipfs,logData.id,options)})}},{key:"findHeads",value:function(log){return log.items.reverse().filter(function(f){return!Log.isReferencedInChain(log,f)}).map(function(f){return f.hash})}},{key:"isReferencedInChain",value:function(log,item){return void 0!==log.items.reverse().find(function(e){return Entry.hasChild(e,item)})}},{key:"batchSize",get:function(){return MaxBatchSize}}]),Log}();module.exports=Log}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i3&&void 0!==arguments[3]?arguments[3]:{};_classCallCheck(this,Store),this.id=id,this.dbname=dbname,this.events=new EventEmitter;var opts=Object.assign({},DefaultOptions);Object.assign(opts,options),this.options=opts,this._ipfs=ipfs,this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options),this._lastWrite=[]}return _createClass(Store,[{key:"loadHistory",value:function(hash){var _this=this;return this._lastWrite.includes(hash)?Promise.resolve([]):(hash&&this._lastWrite.push(hash),this.events.emit("load",this.dbname,hash),hash&&this.options.maxHistory>0?Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this._oplog.join(log)}).then(function(merged){_this._index.updateIndex(_this._oplog,merged),_this.events.emit("history",_this.dbname,merged)}).then(function(){return _this.events.emit("ready",_this.dbname)}).then(function(){return _this}):(this.events.emit("ready",this.dbname),Promise.resolve(this)))}},{key:"sync",value:function(hash){var _this2=this;if(!hash||this._lastWrite.includes(hash))return Promise.resolve([]);var newItems=[];hash&&this._lastWrite.push(hash),this.events.emit("sync",this.dbname);(new Date).getTime();return Log.fromIpfsHash(this._ipfs,hash,this.options).then(function(log){return _this2._oplog.join(log)}).then(function(merged){return newItems=merged}).then(function(){return _this2._index.updateIndex(_this2._oplog,newItems)}).then(function(){newItems.reverse().forEach(function(e){return _this2.events.emit("data",_this2.dbname,e)})}).then(function(){return newItems})}},{key:"close",value:function(){this.delete(),this.events.emit("close",this.dbname)}},{key:"delete",value:function(){this._index=new this.options.Index(this.id),this._oplog=new Log(this._ipfs,this.id,this.options)}},{key:"_addOperation",value:function(data){var _this3=this,result=void 0,logHash=void 0;if(this._oplog)return this._oplog.add(data).then(function(res){return result=res}).then(function(){return Log.getIpfsHash(_this3._ipfs,_this3._oplog)}).then(function(hash){return logHash=hash}).then(function(){return _this3._lastWrite.push(logHash)}).then(function(){return _this3._index.updateIndex(_this3._oplog,[result])}).then(function(){return _this3.events.emit("write",_this3.dbname,logHash)}).then(function(){return _this3.events.emit("data",_this3.dbname,result)}).then(function(){return result.hash})}}]),Store}();module.exports=Store},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i2&&void 0!==arguments[2]?arguments[2]:[];if(!ipfs)throw new Error("Entry requires ipfs instance");var nexts=null!==next&&next instanceof Array?next.map(function(e){return e.hash?e.hash:e}):[null!==next&&next.hash?next.hash:next],entry={hash:null,payload:data,next:nexts};return Entry.toIpfsHash(ipfs,entry).then(function(hash){return entry.hash=hash,entry})}},{key:"toIpfsHash",value:function(ipfs,entry){if(!ipfs)throw new Error("Entry requires ipfs instance");var data=new Buffer(JSON.stringify(entry));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash){if(!ipfs)throw new Error("Entry requires ipfs instance");if(!hash)throw new Error("Invalid hash: "+hash);return ipfs.object.get(hash,{enc:"base58"}).then(function(obj){var data=JSON.parse(obj.toJSON().data),entry={hash:hash,payload:data.payload,next:data.next};return entry})}},{key:"hasChild",value:function(entry1,entry2){return entry1.next.includes(entry2.hash)}},{key:"compare",value:function(a,b){return a.hash===b.hash}}]),Entry}()}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i=MaxBatchSize&&this._commit(),Entry.create(this._ipfs,data,this._heads).then(function(entry){return _this._heads=[entry.hash],_this._currentBatch.push(entry),entry})}},{key:"join",value:function(other){var _this2=this;if(!other.items)throw new Error("The log to join must be an instance of Log");var newItems=other.items.slice(-Math.max(this.options.maxHistory,1)),diff=differenceWith(newItems,this.items,Entry.compare),final=unionWith(this._currentBatch,diff,Entry.compare);this._items=this._items.concat(final),this._currentBatch=[];var nexts=take(flatten(diff.map(function(f){return f.next})),this.options.maxHistory);return Promise.map(nexts,function(f){var all=_this2.items.map(function(a){return a.hash});return _this2._fetchRecursive(_this2._ipfs,f,all,_this2.options.maxHistory-nexts.length,0).then(function(history){return history.forEach(function(b){return _this2._insert(b)}),history})},{concurrency:1}).then(function(res){return _this2._heads=Log.findHeads(_this2),flatten(res).concat(diff)})}},{key:"_insert",value:function(entry){var _this3=this,indices=entry.next.map(function(next){return _this3._items.map(function(f){return f.hash}).indexOf(next)}),index=indices.length>0?Math.max(Math.max.apply(null,indices)+1,0):0;return this._items.splice(index,0,entry),entry}},{key:"_commit",value:function(){this._items=this._items.concat(this._currentBatch),this._currentBatch=[]}},{key:"_fetchRecursive",value:function(ipfs,hash,all,amount,depth){var _this4=this,isReferenced=function(list,item){return void 0!==list.reverse().find(function(f){return f===item})},result=[];return isReferenced(all,hash)||depth>=amount?Promise.resolve(result):Entry.fromIpfsHash(ipfs,hash).then(function(entry){return result.push(entry),all.push(hash),depth++,Promise.map(entry.next,function(f){return _this4._fetchRecursive(ipfs,f,all,amount,depth)},{concurrency:1}).then(function(res){return flatten(res.concat(result))})})}},{key:"items",get:function(){return this._items.concat(this._currentBatch)}},{key:"snapshot",get:function(){return{id:this.id,items:this._currentBatch.map(function(f){return f.hash})}}}],[{key:"getIpfsHash",value:function(ipfs,log){if(!ipfs)throw new Error("Ipfs instance not defined");var data=new Buffer(JSON.stringify(log.snapshot));return ipfs.object.put(data).then(function(res){return res.toJSON().multihash})}},{key:"fromIpfsHash",value:function(ipfs,hash,options){if(!ipfs)throw new Error("Ipfs instance not defined");if(!hash)throw new Error("Invalid hash: "+hash);options||(options={});var logData=void 0;return ipfs.object.get(hash,{enc:"base58"}).then(function(res){return logData=JSON.parse(res.toJSON().data)}).then(function(res){if(!logData.items)throw new Error("Not a Log instance");return Promise.all(logData.items.map(function(f){return Entry.fromIpfsHash(ipfs,f)}))}).then(function(items){return Object.assign(options,{items:items})}).then(function(items){return new Log(ipfs,logData.id,options)})}},{key:"findHeads",value:function(log){return log.items.reverse().filter(function(f){return!Log.isReferencedInChain(log,f)}).map(function(f){return f.hash})}},{key:"isReferencedInChain",value:function(log,item){return void 0!==log.items.reverse().find(function(e){return Entry.hasChild(e,item)})}},{key:"batchSize",get:function(){return MaxBatchSize}}]),Log}();module.exports=Log}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;imax?cb(!0):void cb(null,i++)}}},function(module,exports){"use strict";module.exports=function(){return function(abort,cb){cb(!0)}}},function(module,exports){"use strict";module.exports=function(err){return function(abort,cb){cb(err)}}},function(module,exports,__webpack_require__){"use strict";module.exports={keys:__webpack_require__(103),once:__webpack_require__(39),values:__webpack_require__(23),count:__webpack_require__(98),infinite:__webpack_require__(102),empty:__webpack_require__(99),error:__webpack_require__(100)}},function(module,exports){"use strict";module.exports=function(generate){return generate=generate||Math.random,function(end,cb){return end?cb&&cb(end):cb(null,generate())}}},function(module,exports,__webpack_require__){"use strict";var values=__webpack_require__(23);module.exports=function(object){return values(Object.keys(object))}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12);module.exports=function(map){if(!map)return id;map=prop(map);var abortCb,aborted,busy=!1;return function(read){return function next(abort,cb){return aborted?cb(aborted):void(abort?(aborted=abort,busy?read(abort,function(){busy?abortCb=cb:cb(abort)}):read(abort,cb)):read(null,function(end,data){end?cb(end):aborted?cb(aborted):(busy=!0,map(data,function(err,data){busy=!1,aborted?(cb(aborted),abortCb(aborted)):err?next(err,cb):cb(null,data)}))}))}}}},function(module,exports,__webpack_require__){"use strict";var tester=__webpack_require__(42),filter=__webpack_require__(24);module.exports=function(test){return test=tester(test),filter(function(data){return!test(data)})}},function(module,exports,__webpack_require__){"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},values=__webpack_require__(23),once=__webpack_require__(39);module.exports=function(){return function(read){var _read;return function(abort,cb){function nextChunk(){_read(null,function(err,data){err===!0?nextStream():err?read(!0,function(abortErr){cb(err)}):cb(null,data)})}function nextStream(){_read=null,read(null,function(end,stream){return end?cb(end):(Array.isArray(stream)||stream&&"object"===("undefined"==typeof stream?"undefined":_typeof(stream))?stream=values(stream):"function"!=typeof stream&&(stream=once(stream)),_read=stream,void nextChunk())})}abort?_read?_read(abort,function(err){read(err||abort,cb)}):read(abort,cb):_read?nextChunk():nextStream()}}}},function(module,exports,__webpack_require__){"use strict";module.exports={map:__webpack_require__(108),asyncMap:__webpack_require__(104),filter:__webpack_require__(24),filterNot:__webpack_require__(105),through:__webpack_require__(111),take:__webpack_require__(110),unique:__webpack_require__(40),nonUnique:__webpack_require__(109),flatten:__webpack_require__(106)}},function(module,exports,__webpack_require__){"use strict";function id(e){return e}var prop=__webpack_require__(12);module.exports=function(mapper){return mapper?(mapper=prop(mapper),function(read){return function(abort,cb){read(abort,function(end,data){try{data=end?null:mapper(data)}catch(err){return read(err,function(){return cb(err)})}cb(end,data)})}}):id}},function(module,exports,__webpack_require__){"use strict";var unique=__webpack_require__(40);module.exports=function(field){return unique(field,!0)}},function(module,exports){"use strict";module.exports=function(test,opts){opts=opts||{};var last=opts.last||!1,ended=!1;if("number"==typeof test){last=!0;var n=test;test=function(){return--n}}return function(read){function terminate(cb){read(!0,function(err){last=!1,cb(err||!0)})}return function(end,cb){ended?last?terminate(cb):cb(ended):(ended=end)?read(ended,cb):read(null,function(end,data){(ended=ended||end)?cb(ended):test(data)?cb(null,data):(ended=!0,last?cb(null,data):terminate(cb))})}}}},function(module,exports){"use strict";module.exports=function(op,onEnd){function once(abort){!a&&onEnd&&(a=!0,onEnd(abort===!0?null:abort))}var a=!1;return function(read){return function(end,cb){return end&&once(end),read(end,function(end,data){end?once(end):op&&op(data),cb(end,data)})}}}},function(module,exports,__webpack_require__){"use strict";var looper=__webpack_require__(71),window=module.exports=function(init,start){return function(read){start=start||function(start,data){return{start:start,data:data}};var windows=[],output=[],ended=null,j=0;return function(abort,cb){if(output.length)return cb(null,output.shift());if(ended)return cb(ended);j++;read(abort,looper(function(end,data){function _update(end,_data){once||(once=!0,delete windows[windows.indexOf(update)],output.push(start(data,_data)))}var update,next=this,once=!1;return end&&(ended=end),ended||(update=init(data,_update)),update?windows.push(update):once=!0,windows.forEach(function(update,i){update(end,data)}),output.length?cb(null,output.shift()):ended?cb(ended):void read(null,next)}))}}};window.recent=function(size,time){var current=null;return window(function(data,cb){function done(){var _current=current;current=null,clearTimeout(timer),cb(null,_current)}if(!current){current=[];var timer;return time&&(timer=setTimeout(done,time)),function(end,data){return end?done():(current.push(data),void(null!=size&¤t.length>=size&&done()))}}},function(_,data){return data})},window.sliding=function(reduce,width){width=width||10;var k=0;return window(function(data,cb){var acc,i=0;k++;return function(end,data){end||(acc=reduce(acc,data),width<=++i&&cb(null,acc))}})}},function(module,exports){"use strict";function append(array,item){return(array=array||[]).push(item),array}module.exports=function(write,reduce,max,cb){function reader(read){function more(){reading||ended||(reading=!0,read(null,function(err,data){reading=!1,next(err,data)}))}function flush(){if(!writing){var _queue=queue;queue=null,writing=!0,length=0,write(_queue,function(err){writing=!1,ended!==!0||length?ended&&ended!==!0?(cb(ended),_cb&&_cb()):err?read(ended=err,cb):length?flush():more():cb(err)})}}function next(end,data){ended||(ended=end,ended?writing||cb(ended===!0?null:ended):(queue=reduce(queue,data),length=queue&&queue.length||0,null!=queue&&flush(),length1&&void 0!==arguments[1]?arguments[1]:"orbit-db.cache";return cache={},cachePath?(store=new BlobStore(cachePath),filePath=cacheFile,new Promise(function(resolve,reject){store.exists(cacheFile,function(err,exists){return err||!exists?resolve():void lock(cacheFile,function(release){pull(store.read(cacheFile),pull.collect(release(function(err,res){return err?reject(err):(cache=JSON.parse(Buffer.concat(res).toString()||"{}"),void resolve())})))})})})):Promise.resolve()}},{key:"reset",value:function(){cache={},store=null}}]),Cache}();module.exports=Cache}).call(exports,__webpack_require__(0).Buffer)},function(module,exports,__webpack_require__){"use strict";(function(Buffer){function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:{};if(credentials.provider!==OrbitIdentityProvider.id)throw new Error("OrbitIdentityProvider can't handle provider type '"+credentials.provider+"'");if(!credentials.username)throw new Error("'username' not specified");var keys=void 0,profileData=void 0;return Crypto.getKey(credentials.username).then(function(keyPair){return keys=keyPair,Crypto.exportKeyToIpfs(ipfs,keys.publicKey)}).then(function(pubKeyHash){return profileData={name:credentials.username,location:"Earth",image:null,signKey:pubKeyHash,updated:null,identityProvider:{provider:OrbitIdentityProvider.id,id:null}},ipfs.object.put(new Buffer(JSON.stringify(profileData))).then(function(res){return res.toJSON().multihash})}).then(function(hash){return profileData.id=hash,new OrbitUser(keys,profileData)})}},{key:"load",value:function(ipfs){var profile=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(profile.identityProvider.provider!==OrbitIdentityProvider.id)throw new Error("OrbitIdentityProvider can't handle provider type '"+profile.identityProvider.provider+"'");return Promise.resolve(profile)}},{key:"id",get:function(){return"orbit"}}]),OrbitIdentityProvider}();module.exports=OrbitIdentityProvider}).call(exports,__webpack_require__(0).Buffer)},function(module,exports){"use strict";function placeHoldersCount(b64){var len=b64.length;if(len%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===b64[len-2]?2:"="===b64[len-1]?1:0}function byteLength(b64){return 3*b64.length/4-placeHoldersCount(b64)}function toByteArray(b64){var i,j,l,tmp,placeHolders,arr,len=b64.length;placeHolders=placeHoldersCount(b64),arr=new Arr(3*len/4-placeHolders),l=placeHolders>0?len-4:len;var L=0;for(i=0,j=0;i>16&255,arr[L++]=tmp>>8&255,arr[L++]=255&tmp;return 2===placeHolders?(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4, +arr[L++]=255&tmp):1===placeHolders&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[L++]=tmp>>8&255,arr[L++]=255&tmp),arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]}function encodeChunk(uint8,start,end){for(var tmp,output=[],i=start;ilen2?len2:i+maxChunkLength));return 1===extraBytes?(tmp=uint8[len-1],output+=lookup[tmp>>2],output+=lookup[tmp<<4&63],output+="=="):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],output+=lookup[tmp>>10],output+=lookup[tmp>>4&63],output+=lookup[tmp<<2&63],output+="="),parts.push(output),parts.join("")}exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}function BasePoint(curve,type){this.curve=curve,this.type=type,this.precomputed=null}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,getNAF=utils.getNAF,getJSF=utils.getJSF,assert=utils.assert;module.exports=BaseCurve,BaseCurve.prototype.point=function(){throw new Error("Not implemented")},BaseCurve.prototype.validate=function(){throw new Error("Not implemented")},BaseCurve.prototype._fixedNafMul=function(p,k){assert(p.precomputed);var doubles=p._getDoubles(),naf=getNAF(k,1),I=(1<=j;k--)nafW=(nafW<<1)+naf[k];repr.push(nafW)}for(var a=this.jpoint(null,null,null),b=this.jpoint(null,null,null),i=I;i>0;i--){for(var j=0;j=0;i--){for(var k=0;i>=0&&0===naf[i];i--)k++;if(i>=0&&k++,acc=acc.dblp(k),i<0)break;var z=naf[i];assert(0!==z),acc="affine"===p.type?z>0?acc.mixedAdd(wnd[z-1>>1]):acc.mixedAdd(wnd[-z-1>>1].neg()):z>0?acc.add(wnd[z-1>>1]):acc.add(wnd[-z-1>>1].neg())}return"affine"===p.type?acc.toP():acc},BaseCurve.prototype._wnafMulAdd=function(defW,points,coeffs,len,jacobianResult){for(var wndWidth=this._wnafT1,wnd=this._wnafT2,naf=this._wnafT3,max=0,i=0;i=1;i-=2){var a=i-1,b=i;if(1===wndWidth[a]&&1===wndWidth[b]){var comb=[points[a],null,null,points[b]];0===points[a].y.cmp(points[b].y)?(comb[1]=points[a].add(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg())):0===points[a].y.cmp(points[b].y.redNeg())?(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].add(points[b].neg())):(comb[1]=points[a].toJ().mixedAdd(points[b]),comb[2]=points[a].toJ().mixedAdd(points[b].neg()));var index=[-3,-1,-5,-7,0,7,5,1,3],jsf=getJSF(coeffs[a],coeffs[b]);max=Math.max(jsf[0].length,max),naf[a]=new Array(max),naf[b]=new Array(max);for(var j=0;j=0;i--){for(var k=0;i>=0;){for(var zero=!0,j=0;j=0&&k++,acc=acc.dblp(k),i<0)break;for(var j=0;j0?p=wnd[j][z-1>>1]:z<0&&(p=wnd[j][-z-1>>1].neg()),acc="affine"===p.type?acc.mixedAdd(p):acc.add(p))}}for(var i=0;i=Math.ceil((k.bitLength()+1)/doubles.step)},BasePoint.prototype._getDoubles=function(step,power){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var doubles=[this],acc=this,i=0;i":""},Point.prototype.isInfinity=function(){return 0===this.x.cmpn(0)&&0===this.y.cmp(this.z)},Point.prototype._extDbl=function(){var a=this.x.redSqr(),b=this.y.redSqr(),c=this.z.redSqr();c=c.redIAdd(c);var d=this.curve._mulA(a),e=this.x.redAdd(this.y).redSqr().redISub(a).redISub(b),g=d.redAdd(b),f=g.redSub(c),h=d.redSub(b),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projDbl=function(){var nx,ny,nz,b=this.x.redAdd(this.y).redSqr(),c=this.x.redSqr(),d=this.y.redSqr();if(this.curve.twisted){var e=this.curve._mulA(c),f=e.redAdd(d);if(this.zOne)nx=b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)),ny=f.redMul(e.redSub(d)),nz=f.redSqr().redSub(f).redSub(f);else{var h=this.z.redSqr(),j=f.redSub(h).redISub(h);nx=b.redSub(c).redISub(d).redMul(j),ny=f.redMul(e.redSub(d)),nz=f.redMul(j)}}else{var e=c.redAdd(d),h=this.curve._mulC(this.c.redMul(this.z)).redSqr(),j=e.redSub(h).redSub(h);nx=this.curve._mulC(b.redISub(e)).redMul(j),ny=this.curve._mulC(e).redMul(c.redISub(d)),nz=e.redMul(j)}return this.curve.point(nx,ny,nz)},Point.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},Point.prototype._extAdd=function(p){var a=this.y.redSub(this.x).redMul(p.y.redSub(p.x)),b=this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)),c=this.t.redMul(this.curve.dd).redMul(p.t),d=this.z.redMul(p.z.redAdd(p.z)),e=b.redSub(a),f=d.redSub(c),g=d.redAdd(c),h=b.redAdd(a),nx=e.redMul(f),ny=g.redMul(h),nt=e.redMul(h),nz=f.redMul(g);return this.curve.point(nx,ny,nz,nt)},Point.prototype._projAdd=function(p){var ny,nz,a=this.z.redMul(p.z),b=a.redSqr(),c=this.x.redMul(p.x),d=this.y.redMul(p.y),e=this.curve.d.redMul(c).redMul(d),f=b.redSub(e),g=b.redAdd(e),tmp=this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d),nx=a.redMul(f).redMul(tmp);return this.curve.twisted?(ny=a.redMul(g).redMul(d.redSub(this.curve._mulA(c))),nz=f.redMul(g)):(ny=a.redMul(g).redMul(d.redSub(c)),nz=this.curve._mulC(f).redMul(g)),this.curve.point(nx,ny,nz)},Point.prototype.add=function(p){return this.isInfinity()?p:p.isInfinity()?this:this.curve.extended?this._extAdd(p):this._projAdd(p)},Point.prototype.mul=function(k){return this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!1)},Point.prototype.jmulAdd=function(k1,p,k2){return this.curve._wnafMulAdd(1,[this,p],[k1,k2],2,!0)},Point.prototype.normalize=function(){if(this.zOne)return this;var zi=this.z.redInvm();return this.x=this.x.redMul(zi),this.y=this.y.redMul(zi),this.t&&(this.t=this.t.redMul(zi)),this.z=this.curve.one,this.zOne=!0,this},Point.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()},Point.prototype.getY=function(){return this.normalize(),this.y.fromRed()},Point.prototype.eq=function(other){return this===other||0===this.getX().cmp(other.getX())&&0===this.getY().cmp(other.getY())},Point.prototype.eqXToP=function(x){var rx=x.toRed(this.curve.red).redMul(this.z);if(0===this.x.cmp(rx))return!0;for(var xc=x.clone(),t=this.curve.redN.redMul(this.z);;){if(xc.iadd(this.curve.n),xc.cmp(this.curve.p)>=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}return!1},Point.prototype.toP=Point.prototype.normalize,Point.prototype.mixedAdd=Point.prototype.add},function(module,exports,__webpack_require__){"use strict";function MontCurve(conf){Base.call(this,"mont",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.i4=new BN(4).toRed(this.red).redInvm(),this.two=new BN(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}function Point(curve,x,z){Base.BasePoint.call(this,curve,"projective"),null===x&&null===z?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new BN(x,16),this.z=new BN(z,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}var curve=__webpack_require__(16),BN=__webpack_require__(6),inherits=__webpack_require__(3),Base=curve.base,elliptic=__webpack_require__(2),utils=elliptic.utils;inherits(MontCurve,Base),module.exports=MontCurve,MontCurve.prototype.validate=function(point){var x=point.normalize().x,x2=x.redSqr(),rhs=x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x),y=rhs.redSqrt();return 0===y.redSqr().cmp(rhs)},inherits(Point,Base.BasePoint),MontCurve.prototype.decodePoint=function(bytes,enc){return this.point(utils.toArray(bytes,enc),1)},MontCurve.prototype.point=function(x,z){return new Point(this,x,z)},MontCurve.prototype.pointFromJSON=function(obj){return Point.fromJSON(this,obj)},Point.prototype.precompute=function(){},Point.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Point.fromJSON=function(curve,obj){return new Point(curve,obj[0],obj[1]||curve.one)},Point.prototype.inspect=function(){return this.isInfinity()?"":""},Point.prototype.isInfinity=function(){return 0===this.z.cmpn(0)},Point.prototype.dbl=function(){var a=this.x.redAdd(this.z),aa=a.redSqr(),b=this.x.redSub(this.z),bb=b.redSqr(),c=aa.redSub(bb),nx=aa.redMul(bb),nz=c.redMul(bb.redAdd(this.curve.a24.redMul(c)));return this.curve.point(nx,nz)},Point.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.diffAdd=function(p,diff){var a=this.x.redAdd(this.z),b=this.x.redSub(this.z),c=p.x.redAdd(p.z),d=p.x.redSub(p.z),da=d.redMul(a),cb=c.redMul(b),nx=diff.z.redMul(da.redAdd(cb).redSqr()),nz=diff.x.redMul(da.redISub(cb).redSqr());return this.curve.point(nx,nz)},Point.prototype.mul=function(k){for(var t=k.clone(),a=this,b=this.curve.point(null,null),c=this,bits=[];0!==t.cmpn(0);t.iushrn(1))bits.push(t.andln(1));for(var i=bits.length-1;i>=0;i--)0===bits[i]?(a=a.diffAdd(b,c),b=b.dbl()):(b=a.diffAdd(b,c),a=a.dbl());return b},Point.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Point.prototype.eq=function(other){return 0===this.getX().cmp(other.getX())},Point.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Point.prototype.getX=function(){return this.normalize(),this.x.fromRed()}},function(module,exports,__webpack_require__){"use strict";function ShortCurve(conf){Base.call(this,"short",conf),this.a=new BN(conf.a,16).toRed(this.red),this.b=new BN(conf.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=0===this.a.fromRed().cmpn(0),this.threeA=0===this.a.fromRed().sub(this.p).cmpn(-3),this.endo=this._getEndomorphism(conf),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}function Point(curve,x,y,isRed){Base.BasePoint.call(this,curve,"affine"),null===x&&null===y?(this.x=null,this.y=null,this.inf=!0):(this.x=new BN(x,16),this.y=new BN(y,16),isRed&&(this.x.forceRed(this.curve.red),this.y.forceRed(this.curve.red)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.inf=!1)}function JPoint(curve,x,y,z){Base.BasePoint.call(this,curve,"jacobian"),null===x&&null===y&&null===z?(this.x=this.curve.one,this.y=this.curve.one,this.z=new BN(0)):(this.x=new BN(x,16),this.y=new BN(y,16),this.z=new BN(z,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}var curve=__webpack_require__(16),elliptic=__webpack_require__(2),BN=__webpack_require__(6),inherits=__webpack_require__(3),Base=curve.base,assert=elliptic.utils.assert;inherits(ShortCurve,Base),module.exports=ShortCurve,ShortCurve.prototype._getEndomorphism=function(conf){if(this.zeroA&&this.g&&this.n&&1===this.p.modn(3)){var beta,lambda;if(conf.beta)beta=new BN(conf.beta,16).toRed(this.red);else{var betas=this._getEndoRoots(this.p);beta=betas[0].cmp(betas[1])<0?betas[0]:betas[1],beta=beta.toRed(this.red)}if(conf.lambda)lambda=new BN(conf.lambda,16);else{var lambdas=this._getEndoRoots(this.n);0===this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta))?lambda=lambdas[0]:(lambda=lambdas[1],assert(0===this.g.mul(lambda).x.cmp(this.g.x.redMul(beta))))}var basis;return basis=conf.basis?conf.basis.map(function(vec){return{a:new BN(vec.a,16),b:new BN(vec.b,16)}}):this._getEndoBasis(lambda),{beta:beta,lambda:lambda,basis:basis}}},ShortCurve.prototype._getEndoRoots=function(num){var red=num===this.p?this.red:BN.mont(num),tinv=new BN(2).toRed(red).redInvm(),ntinv=tinv.redNeg(),s=new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv),l1=ntinv.redAdd(s).fromRed(),l2=ntinv.redSub(s).fromRed();return[l1,l2]},ShortCurve.prototype._getEndoBasis=function(lambda){for(var a0,b0,a1,b1,a2,b2,prevR,r,x,aprxSqrt=this.n.ushrn(Math.floor(this.n.bitLength()/2)),u=lambda,v=this.n.clone(),x1=new BN(1),y1=new BN(0),x2=new BN(0),y2=new BN(1),i=0;0!==u.cmpn(0);){var q=v.div(u);r=v.sub(q.mul(u)),x=x2.sub(q.mul(x1));var y=y2.sub(q.mul(y1));if(!a1&&r.cmp(aprxSqrt)<0)a0=prevR.neg(),b0=x1,a1=r.neg(),b1=x;else if(a1&&2===++i)break;prevR=r,v=u,u=r,x2=x1,x1=x,y2=y1,y1=y}a2=r.neg(),b2=x;var len1=a1.sqr().add(b1.sqr()),len2=a2.sqr().add(b2.sqr());return len2.cmp(len1)>=0&&(a2=a0,b2=b0),a1.negative&&(a1=a1.neg(),b1=b1.neg()),a2.negative&&(a2=a2.neg(),b2=b2.neg()),[{a:a1,b:b1},{a:a2,b:b2}]},ShortCurve.prototype._endoSplit=function(k){var basis=this.endo.basis,v1=basis[0],v2=basis[1],c1=v2.b.mul(k).divRound(this.n),c2=v1.b.neg().mul(k).divRound(this.n),p1=c1.mul(v1.a),p2=c2.mul(v2.a),q1=c1.mul(v1.b),q2=c2.mul(v2.b),k1=k.sub(p1).sub(p2),k2=q1.add(q2).neg();return{k1:k1,k2:k2}},ShortCurve.prototype.pointFromX=function(x,odd){x=new BN(x,16),x.red||(x=x.toRed(this.red));var y2=x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b),y=y2.redSqrt();if(0!==y.redSqr().redSub(y2).cmp(this.zero))throw new Error("invalid point");var isOdd=y.fromRed().isOdd();return(odd&&!isOdd||!odd&&isOdd)&&(y=y.redNeg()),this.point(x,y)},ShortCurve.prototype.validate=function(point){if(point.inf)return!0;var x=point.x,y=point.y,ax=this.a.redMul(x),rhs=x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);return 0===y.redSqr().redISub(rhs).cmpn(0)},ShortCurve.prototype._endoWnafMulAdd=function(points,coeffs,jacobianResult){for(var npoints=this._endoWnafT1,ncoeffs=this._endoWnafT2,i=0;i":""},Point.prototype.isInfinity=function(){return this.inf},Point.prototype.add=function(p){if(this.inf)return p;if(p.inf)return this;if(this.eq(p))return this.dbl();if(this.neg().eq(p))return this.curve.point(null,null);if(0===this.x.cmp(p.x))return this.curve.point(null,null);var c=this.y.redSub(p.y);0!==c.cmpn(0)&&(c=c.redMul(this.x.redSub(p.x).redInvm()));var nx=c.redSqr().redISub(this.x).redISub(p.x),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.dbl=function(){if(this.inf)return this;var ys1=this.y.redAdd(this.y);if(0===ys1.cmpn(0))return this.curve.point(null,null);var a=this.curve.a,x2=this.x.redSqr(),dyinv=ys1.redInvm(),c=x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv),nx=c.redSqr().redISub(this.x.redAdd(this.x)),ny=c.redMul(this.x.redSub(nx)).redISub(this.y);return this.curve.point(nx,ny)},Point.prototype.getX=function(){return this.x.fromRed()},Point.prototype.getY=function(){return this.y.fromRed()},Point.prototype.mul=function(k){return k=new BN(k,16),this._hasDoubles(k)?this.curve._fixedNafMul(this,k):this.curve.endo?this.curve._endoWnafMulAdd([this],[k]):this.curve._wnafMul(this,k)},Point.prototype.mulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs):this.curve._wnafMulAdd(1,points,coeffs,2)},Point.prototype.jmulAdd=function(k1,p2,k2){var points=[this,p2],coeffs=[k1,k2];return this.curve.endo?this.curve._endoWnafMulAdd(points,coeffs,!0):this.curve._wnafMulAdd(1,points,coeffs,2,!0)},Point.prototype.eq=function(p){return this===p||this.inf===p.inf&&(this.inf||0===this.x.cmp(p.x)&&0===this.y.cmp(p.y))},Point.prototype.neg=function(_precompute){if(this.inf)return this;var res=this.curve.point(this.x,this.y.redNeg());if(_precompute&&this.precomputed){var pre=this.precomputed,negate=function(p){return p.neg()};res.precomputed={naf:pre.naf&&{wnd:pre.naf.wnd,points:pre.naf.points.map(negate)},doubles:pre.doubles&&{step:pre.doubles.step,points:pre.doubles.points.map(negate)}}}return res},Point.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var res=this.curve.jpoint(this.x,this.y,this.curve.one);return res},inherits(JPoint,Base.BasePoint),ShortCurve.prototype.jpoint=function(x,y,z){return new JPoint(this,x,y,z)},JPoint.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var zinv=this.z.redInvm(),zinv2=zinv.redSqr(),ax=this.x.redMul(zinv2),ay=this.y.redMul(zinv2).redMul(zinv);return this.curve.point(ax,ay)},JPoint.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},JPoint.prototype.add=function(p){if(this.isInfinity())return p;if(p.isInfinity())return this;var pz2=p.z.redSqr(),z2=this.z.redSqr(),u1=this.x.redMul(pz2),u2=p.x.redMul(z2),s1=this.y.redMul(pz2.redMul(p.z)),s2=p.y.redMul(z2.redMul(this.z)),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(p.z).redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.mixedAdd=function(p){if(this.isInfinity())return p.toJ();if(p.isInfinity())return this;var z2=this.z.redSqr(),u1=this.x,u2=p.x.redMul(z2),s1=this.y,s2=p.y.redMul(z2).redMul(this.z),h=u1.redSub(u2),r=s1.redSub(s2);if(0===h.cmpn(0))return 0!==r.cmpn(0)?this.curve.jpoint(null,null,null):this.dbl();var h2=h.redSqr(),h3=h2.redMul(h),v=u1.redMul(h2),nx=r.redSqr().redIAdd(h3).redISub(v).redISub(v),ny=r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)),nz=this.z.redMul(h);return this.curve.jpoint(nx,ny,nz)},JPoint.prototype.dblp=function(pow){if(0===pow)return this;if(this.isInfinity())return this;if(!pow)return this.dbl();if(this.curve.zeroA||this.curve.threeA){for(var r=this,i=0;i=0)return!1;if(rx.redIAdd(t),0===this.x.cmp(rx))return!0}return!1},JPoint.prototype.inspect=function(){return this.isInfinity()?"":""},JPoint.prototype.isInfinity=function(){return 0===this.z.cmpn(0)}},function(module,exports,__webpack_require__){"use strict";function PresetCurve(options){"short"===options.type?this.curve=new elliptic.curve.short(options):"edwards"===options.type?this.curve=new elliptic.curve.edwards(options):this.curve=new elliptic.curve.mont(options),this.g=this.curve.g,this.n=this.curve.n,this.hash=options.hash,assert(this.g.validate(),"Invalid curve"),assert(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}function defineCurve(name,options){Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,get:function(){var curve=new PresetCurve(options);return Object.defineProperty(curves,name,{configurable:!0,enumerable:!0,value:curve}),curve}})}var curves=exports,hash=__webpack_require__(8),elliptic=__webpack_require__(2),assert=elliptic.utils.assert;curves.PresetCurve=PresetCurve,defineCurve("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:hash.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),defineCurve("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:hash.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),defineCurve("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:hash.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),defineCurve("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:hash.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),defineCurve("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:hash.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),defineCurve("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"0",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:!1,g:["9"]}),defineCurve("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:hash.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var pre;try{pre=__webpack_require__(131)}catch(e){pre=void 0}defineCurve("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:hash.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",pre]})},function(module,exports,__webpack_require__){"use strict";function EC(options){return this instanceof EC?("string"==typeof options&&(assert(elliptic.curves.hasOwnProperty(options),"Unknown curve "+options),options=elliptic.curves[options]),options instanceof elliptic.curves.PresetCurve&&(options={curve:options}),this.curve=options.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=options.curve.g,this.g.precompute(options.curve.n.bitLength()+1),void(this.hash=options.hash||options.curve.hash)):new EC(options)}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert,KeyPair=__webpack_require__(125),Signature=__webpack_require__(126);module.exports=EC,EC.prototype.keyPair=function(options){return new KeyPair(this,options)},EC.prototype.keyFromPrivate=function(priv,enc){return KeyPair.fromPrivate(this,priv,enc)},EC.prototype.keyFromPublic=function(pub,enc){return KeyPair.fromPublic(this,pub,enc)},EC.prototype.genKeyPair=function(options){options||(options={});for(var drbg=new elliptic.hmacDRBG({hash:this.hash,pers:options.pers,entropy:options.entropy||elliptic.rand(this.hash.hmacStrength),nonce:this.n.toArray()}),bytes=this.n.byteLength(),ns2=this.n.sub(new BN(2));;){var priv=new BN(drbg.generate(bytes));if(!(priv.cmp(ns2)>0))return priv.iaddn(1),this.keyFromPrivate(priv)}},EC.prototype._truncateToN=function(msg,truncOnly){var delta=8*msg.byteLength()-this.n.bitLength();return delta>0&&(msg=msg.ushrn(delta)),!truncOnly&&msg.cmp(this.n)>=0?msg.sub(this.n):msg},EC.prototype.sign=function(msg,key,enc,options){"object"==typeof enc&&(options=enc,enc=null),options||(options={}),key=this.keyFromPrivate(key,enc),msg=this._truncateToN(new BN(msg,16));for(var bytes=this.n.byteLength(),bkey=key.getPrivate().toArray("be",bytes),nonce=msg.toArray("be",bytes),drbg=new elliptic.hmacDRBG({hash:this.hash,entropy:bkey,nonce:nonce,pers:options.pers,persEnc:options.persEnc}),ns1=this.n.sub(new BN(1)),iter=0;!0;iter++){var k=options.k?options.k(iter):new BN(drbg.generate(this.n.byteLength()));if(k=this._truncateToN(k,!0),!(k.cmpn(1)<=0||k.cmp(ns1)>=0)){var kp=this.g.mul(k);if(!kp.isInfinity()){var kpX=kp.getX(),r=kpX.umod(this.n);if(0!==r.cmpn(0)){var s=k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));if(s=s.umod(this.n),0!==s.cmpn(0)){var recoveryParam=(kp.getY().isOdd()?1:0)|(0!==kpX.cmp(r)?2:0);return options.canonical&&s.cmp(this.nh)>0&&(s=this.n.sub(s),recoveryParam^=1),new Signature({r:r,s:s,recoveryParam:recoveryParam})}}}}}},EC.prototype.verify=function(msg,signature,key,enc){msg=this._truncateToN(new BN(msg,16)),key=this.keyFromPublic(key,enc),signature=new Signature(signature,"hex");var r=signature.r,s=signature.s;if(r.cmpn(1)<0||r.cmp(this.n)>=0)return!1;if(s.cmpn(1)<0||s.cmp(this.n)>=0)return!1;var sinv=s.invm(this.n),u1=sinv.mul(msg).umod(this.n),u2=sinv.mul(r).umod(this.n);if(!this.curve._maxwellTrick){var p=this.g.mulAdd(u1,key.getPublic(),u2);return!p.isInfinity()&&0===p.getX().umod(this.n).cmp(r)}var p=this.g.jmulAdd(u1,key.getPublic(),u2);return!p.isInfinity()&&p.eqXToP(r)},EC.prototype.recoverPubKey=function(msg,signature,j,enc){assert((3&j)===j,"The recovery param is more than two bits"),signature=new Signature(signature,enc);var n=this.n,e=new BN(msg),r=signature.r,s=signature.s,isYOdd=1&j,isSecondKey=j>>1;if(r.cmp(this.curve.p.umod(this.curve.n))>=0&&isSecondKey)throw new Error("Unable to find sencond key candinate");r=isSecondKey?this.curve.pointFromX(r.add(this.curve.n),isYOdd):this.curve.pointFromX(r,isYOdd);var rInv=signature.r.invm(n),s1=n.sub(e).mul(rInv).umod(n),s2=s.mul(rInv).umod(n);return this.g.mulAdd(s1,r,s2)},EC.prototype.getKeyRecoveryParam=function(e,signature,Q,enc){if(signature=new Signature(signature,enc),null!==signature.recoveryParam)return signature.recoveryParam;for(var i=0;i<4;i++){var Qprime;try{Qprime=this.recoverPubKey(e,signature,i)}catch(e){continue}if(Qprime.eq(Q))return i}throw new Error("Unable to find valid recovery factor")}},function(module,exports,__webpack_require__){"use strict";function KeyPair(ec,options){this.ec=ec,this.priv=null,this.pub=null,options.priv&&this._importPrivate(options.priv,options.privEnc),options.pub&&this._importPublic(options.pub,options.pubEnc)}var BN=__webpack_require__(6);module.exports=KeyPair,KeyPair.fromPublic=function(ec,pub,enc){return pub instanceof KeyPair?pub:new KeyPair(ec,{pub:pub,pubEnc:enc})},KeyPair.fromPrivate=function(ec,priv,enc){return priv instanceof KeyPair?priv:new KeyPair(ec,{priv:priv,privEnc:enc})},KeyPair.prototype.validate=function(){var pub=this.getPublic();return pub.isInfinity()?{result:!1,reason:"Invalid public key"}:pub.validate()?pub.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},KeyPair.prototype.getPublic=function(compact,enc){return"string"==typeof compact&&(enc=compact,compact=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),enc?this.pub.encode(enc,compact):this.pub},KeyPair.prototype.getPrivate=function(enc){return"hex"===enc?this.priv.toString(16,2):this.priv},KeyPair.prototype._importPrivate=function(key,enc){this.priv=new BN(key,enc||16),this.priv=this.priv.umod(this.ec.curve.n)},KeyPair.prototype._importPublic=function(key,enc){return key.x||key.y?void(this.pub=this.ec.curve.point(key.x,key.y)):void(this.pub=this.ec.curve.decodePoint(key,enc))},KeyPair.prototype.derive=function(pub){return pub.mul(this.priv).getX()},KeyPair.prototype.sign=function(msg,enc,options){return this.ec.sign(msg,this,enc,options)},KeyPair.prototype.verify=function(msg,signature){return this.ec.verify(msg,signature,this)},KeyPair.prototype.inspect=function(){return""}},function(module,exports,__webpack_require__){"use strict";function Signature(options,enc){return options instanceof Signature?options:void(this._importDER(options,enc)||(assert(options.r&&options.s,"Signature without r or s"),this.r=new BN(options.r,16),this.s=new BN(options.s,16),void 0===options.recoveryParam?this.recoveryParam=null:this.recoveryParam=options.recoveryParam))}function Position(){this.place=0}function getLength(buf,p){var initial=buf[p.place++];if(!(128&initial))return initial;for(var octetLen=15&initial,val=0,i=0,off=p.place;i>>3);for(arr.push(128|octets);--octets;)arr.push(len>>>(octets<<3)&255);arr.push(len)}var BN=__webpack_require__(6),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert;module.exports=Signature,Signature.prototype._importDER=function(data,enc){data=utils.toArray(data,enc);var p=new Position;if(48!==data[p.place++])return!1;var len=getLength(data,p);if(len+p.place!==data.length)return!1;if(2!==data[p.place++])return!1;var rlen=getLength(data,p),r=data.slice(p.place,rlen+p.place);if(p.place+=rlen,2!==data[p.place++])return!1;var slen=getLength(data,p);if(data.length!==slen+p.place)return!1;var s=data.slice(p.place,slen+p.place);return 0===r[0]&&128&r[1]&&(r=r.slice(1)),0===s[0]&&128&s[1]&&(s=s.slice(1)),this.r=new BN(r),this.s=new BN(s),this.recoveryParam=null,!0},Signature.prototype.toDER=function(enc){var r=this.r.toArray(),s=this.s.toArray();for(128&r[0]&&(r=[0].concat(r)),128&s[0]&&(s=[0].concat(s)),r=rmPadding(r),s=rmPadding(s);!(s[0]||128&s[1]);)s=s.slice(1);var arr=[2];constructLength(arr,r.length),arr=arr.concat(r),arr.push(2),constructLength(arr,s.length);var backHalf=arr.concat(s),res=[48];return constructLength(res,backHalf.length),res=res.concat(backHalf),utils.encode(res,enc)}},function(module,exports,__webpack_require__){"use strict";function EDDSA(curve){if(assert("ed25519"===curve,"only tested with ed25519 so far"),!(this instanceof EDDSA))return new EDDSA(curve);var curve=elliptic.curves[curve].curve;this.curve=curve,this.g=curve.g,this.g.precompute(curve.n.bitLength()+1),this.pointClass=curve.point().constructor,this.encodingLength=Math.ceil(curve.n.bitLength()/8),this.hash=hash.sha512}var hash=__webpack_require__(8),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert,parseBytes=utils.parseBytes,KeyPair=__webpack_require__(128),Signature=__webpack_require__(129);module.exports=EDDSA,EDDSA.prototype.sign=function(message,secret){message=parseBytes(message);var key=this.keyFromSecret(secret),r=this.hashInt(key.messagePrefix(),message),R=this.g.mul(r),Rencoded=this.encodePoint(R),s_=this.hashInt(Rencoded,key.pubBytes(),message).mul(key.priv()),S=r.add(s_).umod(this.curve.n);return this.makeSignature({R:R,S:S,Rencoded:Rencoded})},EDDSA.prototype.verify=function(message,sig,pub){message=parseBytes(message),sig=this.makeSignature(sig);var key=this.keyFromPublic(pub),h=this.hashInt(sig.Rencoded(),key.pubBytes(),message),SG=this.g.mul(sig.S()),RplusAh=sig.R().add(key.pub().mul(h));return RplusAh.eq(SG)},EDDSA.prototype.hashInt=function(){for(var hash=this.hash(),i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(entropy,nonce,pers)}var hash=__webpack_require__(8),elliptic=__webpack_require__(2),utils=elliptic.utils,assert=utils.assert;module.exports=HmacDRBG,HmacDRBG.prototype._init=function(entropy,nonce,pers){var seed=entropy.concat(nonce).concat(pers);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var i=0;i=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(entropy.concat(add||[])),this.reseed=1},HmacDRBG.prototype.generate=function(len,enc,add,addEnc){if(this.reseed>this.reseedInterval)throw new Error("Reseed is required");"string"!=typeof enc&&(addEnc=add,add=enc,enc=null),add&&(add=utils.toArray(add,addEnc),this._update(add));for(var temp=[];temp.length>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}return res}function zero2(word){return 1===word.length?"0"+word:word}function toHex(msg){for(var res="",i=0;i=0;){var z;if(k.isOdd()){var mod=k.andln(ws-1);z=mod>(ws>>1)-1?(ws>>1)-mod:mod,k.isubn(z)}else z=0;naf.push(z);for(var shift=0!==k.cmpn(0)&&0===k.andln(ws-1)?w+1:1,i=1;i0||k2.cmpn(-d2)>0;){var m14=k1.andln(3)+d1&3,m24=k2.andln(3)+d2&3;3===m14&&(m14=-1),3===m24&&(m24=-1);var u1;if(0===(1&m14))u1=0;else{var m8=k1.andln(7)+d1&7;u1=3!==m8&&5!==m8||2!==m24?m14:-m14}jsf[0].push(u1);var u2;if(0===(1&m24))u2=0;else{var m8=k2.andln(7)+d2&7;u2=3!==m8&&5!==m8||2!==m14?m24:-m24}jsf[1].push(u2),2*d1===u1+1&&(d1=1-d1),2*d2===u2+1&&(d2=1-d2),k1.iushrn(1),k2.iushrn(1)}return jsf}function cachedProperty(obj,name,computer){var key="_"+name;obj.prototype[name]=function(){return void 0!==this[key]?this[key]:this[key]=computer.call(this)}}function parseBytes(bytes){return"string"==typeof bytes?utils.toArray(bytes,"hex"):bytes}function intFromLE(bytes){return new BN(bytes,"hex","le")}var utils=exports,BN=__webpack_require__(6);utils.assert=function(val,msg){if(!val)throw new Error(msg||"Assertion failed")},utils.toArray=toArray,utils.zero2=zero2,utils.toHex=toHex,utils.encode=function(arr,enc){return"hex"===enc?toHex(arr):arr},utils.getNAF=getNAF,utils.getJSF=getJSF,utils.cachedProperty=cachedProperty,utils.parseBytes=parseBytes,utils.intFromLE=intFromLE},function(module,exports,__webpack_require__){(function(process){function noop(){}function patch(fs){function readFile(path,options,cb){function go$readFile(path,options,cb){return fs$readFile(path,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$readFile,[path,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$readFile(path,options,cb)}function writeFile(path,data,options,cb){function go$writeFile(path,data,options,cb){return fs$writeFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$writeFile,[path,data,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$writeFile(path,data,options,cb)}function appendFile(path,data,options,cb){function go$appendFile(path,data,options,cb){return fs$appendFile(path,data,options,function(err){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$appendFile,[path,data,options,cb]])})}return"function"==typeof options&&(cb=options,options=null),go$appendFile(path,data,options,cb)}function readdir(path,options,cb){function go$readdir$cb(err,files){files&&files.sort&&files.sort(),!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$readdir,[args]])}var args=[path];return"function"!=typeof options?args.push(options):cb=options,args.push(go$readdir$cb),go$readdir(args)}function go$readdir(args){return fs$readdir.apply(fs,args)}function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new ReadStream(path,options)}function createWriteStream(path,options){return new WriteStream(path,options)}function open(path,flags,mode,cb){function go$open(path,flags,mode,cb){return fs$open(path,flags,mode,function(err,fd){!err||"EMFILE"!==err.code&&"ENFILE"!==err.code?("function"==typeof cb&&cb.apply(this,arguments),retry()):enqueue([go$open,[path,flags,mode,cb]])})}return"function"==typeof mode&&(cb=mode,mode=null),go$open(path,flags,mode,cb)}polyfills(fs),fs.gracefulify=patch,fs.FileReadStream=ReadStream,fs.FileWriteStream=WriteStream,fs.createReadStream=createReadStream,fs.createWriteStream=createWriteStream;var fs$readFile=fs.readFile;fs.readFile=readFile;var fs$writeFile=fs.writeFile;fs.writeFile=writeFile;var fs$appendFile=fs.appendFile;fs$appendFile&&(fs.appendFile=appendFile);var fs$readdir=fs.readdir;if(fs.readdir=readdir,"v0.8"===process.version.substr(0,4)){var legStreams=legacy(fs);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs.ReadStream;ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs.WriteStream;WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open,fs.ReadStream=ReadStream,fs.WriteStream=WriteStream;var fs$open=fs.open;return fs.open=open,fs}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),queue.push(elem)}function retry(){var elem=queue.shift();elem&&(debug("RETRY",elem[0].name,elem[1]),elem[0].apply(null,elem[1]))}var fs=__webpack_require__(15),polyfills=__webpack_require__(135),legacy=__webpack_require__(134),queue=[],util=__webpack_require__(14),debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join("\nGFS4: "),console.error(m)}),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(queue),__webpack_require__(54).equal(queue.length,0)}),module.exports=patch(__webpack_require__(43)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&(module.exports=patch(fs)),module.exports.close=fs.close=function(fs$close){return function(fd,cb){return fs$close.call(fs,fd,function(err){err||retry(),"function"==typeof cb&&cb.apply(this,arguments)})}}(fs.close),module.exports.closeSync=fs.closeSync=function(fs$closeSync){return function(fd){var rval=fs$closeSync.apply(fs,arguments);return retry(),rval}}(fs.closeSync)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){(function(process){function legacy(fs){function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;indexthis.end)throw new Error("start must be <= end");this.pos=this.start}return null!==this.fd?void process.nextTick(function(){self._read()}):void fs.open(this.path,this.flags,this.mode,function(err,fd){return err?(self.emit("error",err),void(self.readable=!1)):(self.fd=fd,self.emit("open",fd),void self._read())})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index= zero");this.pos=this.start}this.busy=!1,this._queue=[],null===this.fd&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}return{ReadStream:ReadStream,WriteStream:WriteStream}}var Stream=__webpack_require__(17).Stream;module.exports=legacy}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){(function(process){function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.lchmod||(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.lchown||(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),"win32"===platform&&(fs.rename=function(fs$rename){return function(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){return er&&("EACCES"===er.code||"EPERM"===er.code)&&Date.now()-start<6e4?(setTimeout(function(){fs.stat(to,function(stater,st){stater&&"ENOENT"===stater.code?fs$rename(from,to,CB):cb(er)})},backoff),void(backoff<100&&(backoff+=10))):void(cb&&cb(er))})}}(fs.rename)),fs.read=function(fs$read){return function(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&"function"==typeof callback_){var eagCounter=0;callback=function(er,_,__){return er&&"EAGAIN"===er.code&&eagCounter<10?(eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback)):void callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}}(fs.read),fs.readSync=function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if("EAGAIN"===er.code&&eagCounter<10){eagCounter++;continue}throw er}}}(fs.readSync)}function patchLchmod(fs){fs.lchmod=function(path,mode,callback){fs.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){return err?void(callback&&callback(err)):void fs.fchmod(fd,mode,function(err){fs.close(fd,function(err2){callback&&callback(err||err2)})})})},fs.lchmodSync=function(path,mode){var ret,fd=fs.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0;try{ret=fs.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}}function patchLutimes(fs){constants.hasOwnProperty("O_SYMLINK")?(fs.lutimes=function(path,at,mt,cb){fs.open(path,constants.O_SYMLINK,function(er,fd){return er?void(cb&&cb(er)):void fs.futimes(fd,at,mt,function(er){fs.close(fd,function(er2){cb&&cb(er||er2)})})})},fs.lutimesSync=function(path,at,mt){var ret,fd=fs.openSync(path,constants.O_SYMLINK),threw=!0;try{ret=fs.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs.closeSync(fd)}catch(er){}else fs.closeSync(fd)}return ret}):(fs.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs.lutimesSync=function(){})}function chmodFix(orig){return orig?function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chmodFixSync(orig){return orig?function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}:orig}function chownFix(orig){return orig?function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}:orig}function chownFixSync(orig){return orig?function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}:orig}function statFix(orig){return orig?function(target,cb){return orig.call(fs,target,function(er,stats){return stats?(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296),void(cb&&cb.apply(this,arguments))):cb.apply(this,arguments)})}:orig}function statFixSync(orig){return orig?function(target){var stats=orig.call(fs,target);return stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296),stats}:orig}function chownErOk(er){if(!er)return!0;if("ENOSYS"===er.code)return!0;var nonroot=!process.getuid||0!==process.getuid();return!(!nonroot||"EINVAL"!==er.code&&"EPERM"!==er.code)}var fs=__webpack_require__(43),constants=__webpack_require__(143),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch(er){}var chdir=process.chdir;process.chdir=function(d){cwd=null,chdir.call(process,d)},module.exports=patch}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){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}var hash=__webpack_require__(8),utils=hash.utils,assert=utils.assert;exports.BlockHash=BlockHash,BlockHash.prototype.update=function(msg,enc){if(msg=utils.toArray(msg,enc),this.pending?this.pending=this.pending.concat(msg):this.pending=msg,this.pendingTotal+=msg.length,this.pending.length>=this._delta8){msg=this.pending;var r=msg.length%this._delta8;this.pending=msg.slice(msg.length-r,msg.length),0===this.pending.length&&(this.pending=null),msg=utils.join32(msg,0,msg.length-r,this.endian);for(var i=0;i>>24&255,res[i++]=len>>>16&255,res[i++]=len>>>8&255,res[i++]=255&len}else{res[i++]=255&len,res[i++]=len>>>8&255,res[i++]=len>>>16&255,res[i++]=len>>>24&255,res[i++]=0,res[i++]=0,res[i++]=0,res[i++]=0;for(var t=8;tthis.blockSize&&(key=(new this.Hash).update(key).digest()),assert(key.length<=this.blockSize);for(var i=key.length;i>>3}function g1_256(x){return rotr32(x,17)^rotr32(x,19)^x>>>10}function ft_1(s,x,y,z){return 0===s?ch32(x,y,z):1===s||3===s?p32(x,y,z):2===s?maj32(x,y,z):void 0}function ch64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^~xh&zh;return r<0&&(r+=4294967296),r}function ch64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^~xl&zl;return r<0&&(r+=4294967296),r}function maj64_hi(xh,xl,yh,yl,zh,zl){var r=xh&yh^xh&zh^yh&zh;return r<0&&(r+=4294967296),r}function maj64_lo(xh,xl,yh,yl,zh,zl){var r=xl&yl^xl&zl^yl&zl;return r<0&&(r+=4294967296),r}function s0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,28),c1_hi=rotr64_hi(xl,xh,2),c2_hi=rotr64_hi(xl,xh,7),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function s0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,28),c1_lo=rotr64_lo(xl,xh,2),c2_lo=rotr64_lo(xl,xh,7),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function s1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,14),c1_hi=rotr64_hi(xh,xl,18),c2_hi=rotr64_hi(xl,xh,9),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function s1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,14),c1_lo=rotr64_lo(xh,xl,18),c2_lo=rotr64_lo(xl,xh,9),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function g0_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,1),c1_hi=rotr64_hi(xh,xl,8),c2_hi=shr64_hi(xh,xl,7),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function g0_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,1),c1_lo=rotr64_lo(xh,xl,8),c2_lo=shr64_lo(xh,xl,7),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}function g1_512_hi(xh,xl){var c0_hi=rotr64_hi(xh,xl,19),c1_hi=rotr64_hi(xl,xh,29),c2_hi=shr64_hi(xh,xl,6),r=c0_hi^c1_hi^c2_hi;return r<0&&(r+=4294967296),r}function g1_512_lo(xh,xl){var c0_lo=rotr64_lo(xh,xl,19),c1_lo=rotr64_lo(xl,xh,29),c2_lo=shr64_lo(xh,xl,6),r=c0_lo^c1_lo^c2_lo;return r<0&&(r+=4294967296),r}var hash=__webpack_require__(8),utils=hash.utils,assert=utils.assert,rotr32=utils.rotr32,rotl32=utils.rotl32,sum32=utils.sum32,sum32_4=utils.sum32_4,sum32_5=utils.sum32_5,rotr64_hi=utils.rotr64_hi,rotr64_lo=utils.rotr64_lo,shr64_hi=utils.shr64_hi,shr64_lo=utils.shr64_lo,sum64=utils.sum64,sum64_hi=utils.sum64_hi,sum64_lo=utils.sum64_lo,sum64_4_hi=utils.sum64_4_hi,sum64_4_lo=utils.sum64_4_lo,sum64_5_hi=utils.sum64_5_hi,sum64_5_lo=utils.sum64_5_lo,BlockHash=hash.common.BlockHash,sha256_K=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],sha512_K=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],sha1_K=[1518500249,1859775393,2400959708,3395469782];utils.inherits(SHA256,BlockHash),exports.sha256=SHA256,SHA256.blockSize=512,SHA256.outSize=256,SHA256.hmacStrength=192,SHA256.padLength=64,SHA256.prototype._update=function(msg,start){for(var W=this.W,i=0;i<16;i++)W[i]=msg[start+i];for(;i>8,lo=255&c;hi?res.push(hi,lo):res.push(lo)}else for(var i=0;i>>24|w>>>8&65280|w<<8&16711680|(255&w)<<24;return res>>>0}function toHex32(msg,endian){for(var res="",i=0;i>>0}return res}function split32(msg,endian){for(var res=new Array(4*msg.length),i=0,k=0;i>>24,res[k+1]=m>>>16&255,res[k+2]=m>>>8&255,res[k+3]=255&m):(res[k+3]=m>>>24,res[k+2]=m>>>16&255,res[k+1]=m>>>8&255,res[k]=255&m)}return res}function rotr32(w,b){return w>>>b|w<<32-b}function rotl32(w,b){return w<>>32-b}function sum32(a,b){return a+b>>>0}function sum32_3(a,b,c){return a+b+c>>>0}function sum32_4(a,b,c,d){return a+b+c+d>>>0}function sum32_5(a,b,c,d,e){return a+b+c+d+e>>>0}function assert(cond,msg){if(!cond)throw new Error(msg||"Assertion failed")}function sum64(buf,pos,ah,al){var bh=buf[pos],bl=buf[pos+1],lo=al+bl>>>0,hi=(lo>>0,buf[pos+1]=lo}function sum64_hi(ah,al,bh,bl){var lo=al+bl>>>0,hi=(lo>>0}function sum64_lo(ah,al,bh,bl){var lo=al+bl;return lo>>>0}function sum64_4_hi(ah,al,bh,bl,ch,cl,dh,dl){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}function sum64_4_lo(ah,al,bh,bl,ch,cl,dh,dl){var lo=al+bl+cl+dl;return lo>>>0}function sum64_5_hi(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var carry=0,lo=al;lo=lo+bl>>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0,carry+=lo>>0}function sum64_5_lo(ah,al,bh,bl,ch,cl,dh,dl,eh,el){var lo=al+bl+cl+dl+el; +return lo>>>0}function rotr64_hi(ah,al,num){var r=al<<32-num|ah>>>num;return r>>>0}function rotr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}function shr64_hi(ah,al,num){return ah>>>num}function shr64_lo(ah,al,num){var r=ah<<32-num|al>>>num;return r>>>0}var utils=exports,inherits=__webpack_require__(3);utils.toArray=toArray,utils.toHex=toHex,utils.htonl=htonl,utils.toHex32=toHex32,utils.zero2=zero2,utils.zero8=zero8,utils.join32=join32,utils.split32=split32,utils.rotr32=rotr32,utils.rotl32=rotl32,utils.sum32=sum32,utils.sum32_3=sum32_3,utils.sum32_4=sum32_4,utils.sum32_5=sum32_5,utils.assert=assert,utils.inherits=inherits,exports.sum64=sum64,exports.sum64_hi=sum64_hi,exports.sum64_lo=sum64_lo,exports.sum64_4_hi=sum64_4_hi,exports.sum64_4_lo=sum64_4_lo,exports.sum64_5_hi=sum64_5_hi,exports.sum64_5_lo=sum64_5_lo,exports.rotr64_hi=rotr64_hi,exports.rotr64_lo=rotr64_lo,exports.shr64_hi=shr64_hi,exports.shr64_lo=shr64_lo},function(module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:(s?-1:1)*(1/0);m+=Math.pow(2,mLen),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,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias),value*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},function(module,exports,__webpack_require__){/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +!function(){function MurmurHash3(key,seed){var m=this instanceof MurmurHash3?this:cache;if(m.reset(seed),"string"==typeof key&&key.length>0&&m.hash(key),m!==this)return m}var cache;MurmurHash3.prototype.hash=function(key){var h1,k1,i,top,len;switch(len=key.length,this.len+=len,k1=this.k1,i=0,this.rem){case 0:k1^=len>i?65535&key.charCodeAt(i++):0;case 1:k1^=len>i?(65535&key.charCodeAt(i++))<<8:0;case 2:k1^=len>i?(65535&key.charCodeAt(i++))<<16:0;case 3:k1^=len>i?(255&key.charCodeAt(i))<<24:0,k1^=len>i?(65280&key.charCodeAt(i++))>>8:0}if(this.rem=len+this.rem&3,len-=this.rem,len>0){for(h1=this.h1;;){if(k1=11601*k1+3432906752*(65535&k1)&4294967295,k1=k1<<15|k1>>>17,k1=13715*k1+461832192*(65535&k1)&4294967295,h1^=k1,h1=h1<<13|h1>>>19,h1=5*h1+3864292196&4294967295,i>=len)break;k1=65535&key.charCodeAt(i++)^(65535&key.charCodeAt(i++))<<8^(65535&key.charCodeAt(i++))<<16,top=key.charCodeAt(i++),k1^=(255&top)<<24^(65280&top)>>8}switch(k1=0,this.rem){case 3:k1^=(65535&key.charCodeAt(i+2))<<16;case 2:k1^=(65535&key.charCodeAt(i+1))<<8;case 1:k1^=65535&key.charCodeAt(i)}this.h1=h1}return this.k1=k1,this},MurmurHash3.prototype.result=function(){var k1,h1;return k1=this.k1,h1=this.h1,k1>0&&(k1=11601*k1+3432906752*(65535&k1)&4294967295,k1=k1<<15|k1>>>17,k1=13715*k1+461832192*(65535&k1)&4294967295,h1^=k1),h1^=this.len,h1^=h1>>>16,h1=51819*h1+2246770688*(65535&h1)&4294967295,h1^=h1>>>13,h1=44597*h1+3266445312*(65535&h1)&4294967295,h1^=h1>>>16,h1>>>0},MurmurHash3.prototype.reset=function(seed){return this.h1="number"==typeof seed?seed:0,this.rem=this.k1=this.len=0,this},cache=new MurmurHash3,module.exports=MurmurHash3}()},function(module,exports){module.exports={O_RDONLY:0,O_WRONLY:1,O_RDWR:2,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:512,O_EXCL:2048,O_NOCTTY:131072,O_TRUNC:1024,O_APPEND:8,O_DIRECTORY:1048576,O_NOFOLLOW:256,O_SYNC:128,O_SYMLINK:2097152,O_NONBLOCK:4,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,E2BIG:7,EACCES:13,EADDRINUSE:48,EADDRNOTAVAIL:49,EAFNOSUPPORT:47,EAGAIN:35,EALREADY:37,EBADF:9,EBADMSG:94,EBUSY:16,ECANCELED:89,ECHILD:10,ECONNABORTED:53,ECONNREFUSED:61,ECONNRESET:54,EDEADLK:11,EDESTADDRREQ:39,EDOM:33,EDQUOT:69,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:65,EIDRM:90,EILSEQ:92,EINPROGRESS:36,EINTR:4,EINVAL:22,EIO:5,EISCONN:56,EISDIR:21,ELOOP:62,EMFILE:24,EMLINK:31,EMSGSIZE:40,EMULTIHOP:95,ENAMETOOLONG:63,ENETDOWN:50,ENETRESET:52,ENETUNREACH:51,ENFILE:23,ENOBUFS:55,ENODATA:96,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:77,ENOLINK:97,ENOMEM:12,ENOMSG:91,ENOPROTOOPT:42,ENOSPC:28,ENOSR:98,ENOSTR:99,ENOSYS:78,ENOTCONN:57,ENOTDIR:20,ENOTEMPTY:66,ENOTSOCK:38,ENOTSUP:45,ENOTTY:25,ENXIO:6,EOPNOTSUPP:102,EOVERFLOW:84,EPERM:1,EPIPE:32,EPROTO:100,EPROTONOSUPPORT:43,EPROTOTYPE:41,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:70,ETIME:101,ETIMEDOUT:60,ETXTBSY:26,EWOULDBLOCK:35,EXDEV:18,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:10,SIGFPE:8,SIGKILL:9,SIGUSR1:30,SIGSEGV:11,SIGUSR2:31,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:20,SIGCONT:19,SIGSTOP:17,SIGTSTP:18,SIGTTIN:21,SIGTTOU:22,SIGURG:16,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:23,SIGSYS:12,SSL_OP_ALL:2147486719,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_EPHEMERAL_RSA:0,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER:32,SSL_OP_MICROSOFT_SESS_ID_BUG:1,SSL_OP_MSIE_SSLV2_RSA_PADDING:0,SSL_OP_NETSCAPE_CA_DN_BUG:536870912,SSL_OP_NETSCAPE_CHALLENGE_BUG:2,SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG:1073741824,SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG:8,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:16777216,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_PKCS1_CHECK_1:0,SSL_OP_PKCS1_CHECK_2:0,SSL_OP_SINGLE_DH_USE:1048576,SSL_OP_SINGLE_ECDH_USE:524288,SSL_OP_SSLEAY_080_CLIENT_DH_BUG:128,SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG:0,SSL_OP_TLS_BLOCK_PADDING_BUG:512,SSL_OP_TLS_D5_BUG:256,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_ECDH:16,ENGINE_METHOD_ECDSA:32,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_STORE:256,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_UDP_REUSEADDR:4}},function(module,exports){module.exports={_args:[[{raw:"elliptic@^6.3.1",scope:null,escapedName:"elliptic",name:"elliptic",rawSpec:"^6.3.1",spec:">=6.3.1 <7.0.0",type:"range"},"/Users/samuli/code/orbit-core/node_modules/orbit-crypto"]],_from:"elliptic@>=6.3.1 <7.0.0",_id:"elliptic@6.3.2",_inCache:!0,_location:"/elliptic",_nodeVersion:"6.3.0",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/elliptic-6.3.2.tgz_1473938837205_0.3108903462998569"},_npmUser:{name:"indutny",email:"fedor@indutny.com"},_npmVersion:"3.10.3",_phantomChildren:{},_requested:{raw:"elliptic@^6.3.1",scope:null,escapedName:"elliptic",name:"elliptic",rawSpec:"^6.3.1",spec:">=6.3.1 <7.0.0",type:"range"},_requiredBy:["/browserify-sign","/create-ecdh","/orbit-crypto"],_resolved:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz",_shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",_shrinkwrap:null,_spec:"elliptic@^6.3.1",_where:"/Users/samuli/code/orbit-core/node_modules/orbit-crypto",author:{name:"Fedor Indutny",email:"fedor@indutny.com"},bugs:{url:"https://github.com/indutny/elliptic/issues"},dependencies:{"bn.js":"^4.4.0",brorand:"^1.0.1","hash.js":"^1.0.0",inherits:"^2.0.1"},description:"EC cryptography",devDependencies:{brfs:"^1.4.3",coveralls:"^2.11.3",grunt:"^0.4.5","grunt-browserify":"^5.0.0","grunt-contrib-connect":"^1.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^1.0.1","grunt-mocha-istanbul":"^3.0.1","grunt-saucelabs":"^8.6.2",istanbul:"^0.4.2",jscs:"^2.9.0",jshint:"^2.6.0",mocha:"^2.1.0"},directories:{},dist:{shasum:"e4c81e0829cf0a65ab70e998b8232723b5c1bc48",tarball:"https://registry.npmjs.org/elliptic/-/elliptic-6.3.2.tgz"},files:["lib"],gitHead:"cbace4683a4a548dc0306ef36756151a20299cd5",homepage:"https://github.com/indutny/elliptic",keywords:["EC","Elliptic","curve","Cryptography"],license:"MIT",main:"lib/elliptic.js",maintainers:[{name:"indutny",email:"fedor@indutny.com"}],name:"elliptic",optionalDependencies:{},readme:"ERROR: No README data found!",repository:{type:"git",url:"git+ssh://git@github.com/indutny/elliptic.git"},scripts:{jscs:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",jshint:"jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",lint:"npm run jscs && npm run jshint",test:"npm run lint && npm run unit",unit:"istanbul test _mocha --reporter=spec test/index.js",version:"grunt dist && git add dist/"},version:"6.3.2"}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(9)},function(module,exports,__webpack_require__){"use strict";function BufferList(){this.head=null,this.tail=null,this.length=0}var bufferShim=(__webpack_require__(0).Buffer,__webpack_require__(25));module.exports=BufferList,BufferList.prototype.push=function(v){var entry={data:v,next:null};this.length>0?this.tail.next=entry:this.head=entry,this.tail=entry,++this.length},BufferList.prototype.unshift=function(v){var entry={data:v,next:this.head};0===this.length&&(this.tail=entry),this.head=entry,++this.length},BufferList.prototype.shift=function(){if(0!==this.length){var ret=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,ret}},BufferList.prototype.clear=function(){this.head=this.tail=null,this.length=0},BufferList.prototype.join=function(s){if(0===this.length)return"";for(var p=this.head,ret=""+p.data;p=p.next;)ret+=s+p.data;return ret},BufferList.prototype.concat=function(n){if(0===this.length)return bufferShim.alloc(0);if(1===this.length)return this.head.data;for(var ret=bufferShim.allocUnsafe(n>>>0),p=this.head,i=0;p;)p.data.copy(ret,i),i+=p.data.length,p=p.next;return ret}},function(module,exports,__webpack_require__){module.exports=__webpack_require__(46)},function(module,exports,__webpack_require__){(function(process){var Stream=function(){try{return __webpack_require__(17)}catch(_){}}();exports=module.exports=__webpack_require__(47),exports.Stream=Stream||exports,exports.Readable=exports,exports.Writable=__webpack_require__(28),exports.Duplex=__webpack_require__(9),exports.Transform=__webpack_require__(27),exports.PassThrough=__webpack_require__(46),!process.browser&&"disable"===process.env.READABLE_STREAM&&Stream&&(module.exports=Stream)}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){module.exports=__webpack_require__(27)},function(module,exports,__webpack_require__){module.exports=__webpack_require__(28)},function(module,exports,__webpack_require__){(function(process){function asyncMap(){function cb(er){er&&!errState&&(errState=er);for(var argLen=arguments.length,i=1;il){var newList=list.slice(l);a+=(list.length-l)*n,l=list.length,process.nextTick(function(){newList.forEach(function(ar){steps.forEach(function(fn){fn(ar,cb)})})})}0===--a&&cb_.apply(null,[errState].concat(data))}var steps=Array.prototype.slice.call(arguments),list=steps.shift()||[],cb_=steps.pop();if("function"!=typeof cb_)throw new Error("No callback provided to asyncMap");if(!list)return cb_(null,[]);Array.isArray(list)||(list=[list]);var n=steps.length,data=[],errState=null,l=list.length,a=l*n;return a?void list.forEach(function(ar){steps.forEach(function(fn){fn(ar,cb)})}):cb_(null,[])}module.exports=asyncMap}).call(exports,__webpack_require__(1))},function(module,exports,__webpack_require__){function chain(things,cb){var res=[];!function LOOP(i,len){return i>=len?cb(null,res):(Array.isArray(things[i])&&(things[i]=bindActor.apply(null,things[i].map(function(i){return i===chain.first?res[0]:i===chain.last?res[res.length-1]:i}))),things[i]?void things[i](function(er,data){return er?cb(er,res):(void 0!==data&&(res=res.concat(data)),void LOOP(i+1,len))}):LOOP(i+1,len))}(0,things.length)}module.exports=chain;var bindActor=__webpack_require__(48);chain.first={},chain.last={}},function(module,exports,__webpack_require__){exports.asyncMap=__webpack_require__(151),exports.bindActor=__webpack_require__(48),exports.chain=__webpack_require__(152)},function(module,exports,__webpack_require__){(function(global){function deprecate(fn,msg){function deprecated(){if(!warned){if(config("throwDeprecation"))throw new Error(msg);config("traceDeprecation")?console.trace(msg):console.warn(msg),warned=!0}return fn.apply(this,arguments)}if(config("noDeprecation"))return fn;var warned=!1;return deprecated}function config(name){try{if(!global.localStorage)return!1}catch(_){return!1}var val=global.localStorage[name];return null!=val&&"true"===String(val).toLowerCase()}module.exports=deprecate}).call(exports,__webpack_require__(4))},function(module,exports){"function"==typeof Object.create?module.exports=function(ctor,superCtor){ctor.super_=superCtor,ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}},function(module,exports){module.exports=function(arg){return arg&&"object"==typeof arg&&"function"==typeof arg.copy&&"function"==typeof arg.fill&&"function"==typeof arg.readUInt8}},function(module,exports,__webpack_require__){"use strict";(function(__filename,process){function murmurhex(){for(var hash=new MurmurHash3,ii=0;ii1&&void 0!==arguments[1]?arguments[1]:{};_classCallCheck(this,Orbit),this.events=new EventEmitter,this._ipfs=ipfs,this._orbitdb=null,this._user=null,this._channels={},this._peers=[],this._pollPeersTimer=null,this._options=Object.assign({},defaultOptions),this._cache=new LRU(1e3),Object.assign(this._options,options),Crypto.useKeyStore(this._options.keystorePath)}return _createClass(Orbit,[{key:"connect",value:function(){var _this=this,credentials=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return logger.debug("Load cache from:",this._options.cachePath),logger.info("Connecting to Orbit as '"+JSON.stringify(credentials)),"string"==typeof credentials&&(credentials={provider:"orbit",username:credentials}),this._ipfs.object.put(new Buffer(JSON.stringify({app:"orbit.chat"}))).then(function(res){return _this._ipfs.object.get(res.toJSON().multihash,{enc:"base58"})}).catch(function(err){return logger.error(err)}),IdentityProviders.authorizeUser(this._ipfs,credentials).then(function(user){return _this._user=user}).then(function(){return new OrbitDB(_this._ipfs,_this._user.id)}).then(function(orbitdb){_this._orbitdb=orbitdb,_this._orbitdb.events.on("data",_this._handleMessage.bind(_this)),_this._startPollingForPeers()}).then(function(){return logger.info("Connected to '"+_this._orbitdb.network.name+"' as '"+_this.user.name),_this.events.emit("connected",_this.network,_this.user),_this}).catch(function(e){return console.error(e)})}},{key:"disconnect",value:function(){this._orbitdb&&(logger.warn("Disconnected from '"+this.network.name+"'"),this._orbitdb.disconnect(),this._orbitdb=null,this._user=null,this._channels={},this._pollPeersTimer&&clearInterval(this._pollPeersTimer),this.events.emit("disconnected"))}},{key:"join",value:function(channel){if(logger.debug("Join #"+channel),!channel||""===channel)return Promise.reject("Channel not specified");if(this._channels[channel])return Promise.resolve(!1);var dbOptions={cachePath:this._options.cachePath,maxHistory:this._options.maxHistory};return this._channels[channel]={name:channel,password:null,feed:this._orbitdb.eventlog(channel,dbOptions)},this.events.emit("joined",channel),Promise.resolve(!0)}},{key:"leave",value:function(channel){this._channels[channel]&&(this._channels[channel].feed.close(),delete this._channels[channel],logger.debug("Left channel #"+channel)),this.events.emit("left",channel)}},{key:"send",value:function(channel,message,replyToHash){var _this2=this;if(!message||""===message)return Promise.reject("Can't send an empty message");logger.debug("Send message to #"+channel+": "+message);var data={content:message,replyto:replyToHash||null,from:this.user.id};return this._getChannelFeed(channel).then(function(feed){return _this2._postMessage(feed,Post.Types.Message,data,_this2._user._keys)})}},{key:"get",value:function(channel){var lessThanHash=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,greaterThanHash=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,amount=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;logger.debug("Get messages from #"+channel+": "+lessThanHash+", "+greaterThanHash+", "+amount);var options={limit:amount,lt:lessThanHash,gte:greaterThanHash};return this._getChannelFeed(channel).then(function(feed){return feed.iterator(options).collect()})}},{key:"getPost",value:function(hash,withUserProfile){var _this3=this,post=this._cache.get(hash);if(post)return Promise.resolve(post);var _ret=function(){var post=void 0;return{v:_this3._ipfs.object.get(hash,{enc:"base58"}).then(function(res){return post=JSON.parse(res.toJSON().data)}).then(function(){return Crypto.importKeyFromIpfs(_this3._ipfs,post.signKey)}).then(function(signKey){return Crypto.verify(post.sig,signKey,new Buffer(JSON.stringify({content:post.content,meta:post.meta,replyto:post.replyto})))}).then(function(){return _this3._cache.set(hash,post),withUserProfile?_this3.getUser(post.meta.from).then(function(user){return post.meta.from=user,post}):post})}}();return"object"===("undefined"==typeof _ret?"undefined":_typeof(_ret))?_ret.v:void 0}},{key:"addFile",value:function(channel,source){var _this4=this;if(!source||!source.filename&&!source.directory)return Promise.reject("Filename or directory not specified");var addToIpfsJs=function(ipfs,data){return ipfs.files.add(new Buffer(data)).then(function(result){return{Hash:result[0].toJSON().multihash,isDirectory:!1}})},addToIpfsGo=function(ipfs,filename,filePath){return ipfs.util.addFromFs(filePath,{recursive:!0}).then(function(result){var isDirectory=result[0].path.split("/").pop()!==filename;return{Hash:isDirectory?result[result.length-1].hash:result[0].hash,isDirectory:isDirectory}})};logger.info("Adding file from path '"+source.filename+"'");var isBuffer=!(!source.buffer||!source.filename),name=source.directory?source.directory.split("/").pop():source.filename.split("/").pop(),size=source.meta&&source.meta.size?source.meta.size:0,feed=void 0,addToIpfs=void 0;return addToIpfs=isBuffer?function(){return addToIpfsJs(_this4._ipfs,source.buffer)}:source.directory?function(){return addToIpfsGo(_this4._ipfs,name,source.directory)}:function(){return addToIpfsGo(_this4._ipfs,name,source.filename)},this._getChannelFeed(channel).then(function(res){return feed=res}).then(function(){return addToIpfs()}).then(function(result){logger.info("Added file '"+source.filename+"' as ",result);var type=result.isDirectory?Post.Types.Directory:Post.Types.File,data={name:name,hash:result.Hash,size:size,from:_this4.user.id,meta:source.meta||{}};return _this4._postMessage(feed,type,data,_this4._user._keys)})}},{key:"getFile",value:function(hash){return this._ipfs.cat(hash)}},{key:"getDirectory",value:function(hash){return this._ipfs.ls(hash).then(function(res){return res.Objects[0].Links})}},{key:"getUser",value:function(hash){var _this5=this,user=this._cache.get(hash);return user?Promise.resolve(user):this._ipfs.object.get(hash,{enc:"base58"}).then(function(res){var profileData=Object.assign(JSON.parse(res.toJSON().data));return Object.assign(profileData,{id:hash}),IdentityProviders.loadProfile(_this5._ipfs,profileData).then(function(profile){return Object.assign(profile||profileData,{id:hash}),_this5._cache.set(hash,profile),profile}).catch(function(e){return logger.error(e),profileData})})}},{key:"_postMessage",value:function(feed,postType,data,signKey){var post=void 0;return Post.create(this._ipfs,postType,data,signKey).then(function(res){return post=res}).then(function(){return feed.add(post.Hash)}).then(function(){return post})}},{key:"_getChannelFeed",value:function(channel){var _this6=this;return channel&&""!==channel?new Promise(function(resolve,reject){var feed=_this6._channels[channel]&&_this6._channels[channel].feed?_this6._channels[channel].feed:null;feed||reject("Haven't joined #"+channel),resolve(feed)}):Promise.reject("Channel not specified")}},{key:"_handleMessage",value:function(channel,message){logger.debug("New message in #",channel,"\n"+JSON.stringify(message,null,2)),this._channels[channel]&&this.events.emit("message",channel,message)}},{key:"_startPollingForPeers",value:function(){var _this7=this;this._pollPeersTimer||(this._pollPeersTimer=setInterval(function(){_this7._updateSwarmPeers().then(function(peers){_this7._peers=peers||[],_this7.events.emit("peers",_this7._peers)})},3e3))}},{key:"_updateSwarmPeers",value:function(){var _this8=this;return this._ipfs.libp2p&&this._ipfs.libp2p.swarm.peers?new Promise(function(resolve,reject){_this8._ipfs.libp2p.swarm.peers(function(err,peers){err&&reject(err),resolve(peers)})}).then(function(peers){return Object.keys(peers).map(function(e){return peers[e].multiaddrs[0].toString()})}).catch(function(e){return logger.error(e)}):Promise.resolve([])}},{key:"user",get:function(){return this._user?this._user.profile:null}},{key:"network",get:function(){return this._orbitdb?this._orbitdb.network:null}},{key:"channels",get:function(){return this._channels}},{key:"peers",get:function(){return this._peers}}]),Orbit}();module.exports=Orbit}).call(exports,__webpack_require__(1),__webpack_require__(0).Buffer)}]); \ No newline at end of file diff --git a/lib/config.js b/lib/config.js index f7aafb6d..bc06abfb 100644 --- a/lib/config.js +++ b/lib/config.js @@ -84,6 +84,9 @@ Config.prototype.loadFiles = function(files) { if (file === 'embark.js') { readFiles.push({filename: 'web3.js', content: fs.readFileSync(path.join(__dirname, "/../js/web3.js")).toString()}); readFiles.push({filename: 'ipfs.js', content: fs.readFileSync(path.join(__dirname, "/../js/ipfs.js")).toString()}); + // TODO: remove duplicated files if funcitonality is the same for storage and orbit + readFiles.push({filename: 'ipfs-api.js', content: fs.readFileSync(path.join(__dirname, "/../js/ipfs-api.min.js")).toString()}); + readFiles.push({filename: 'orbit.js', content: fs.readFileSync(path.join(__dirname, "/../js/orbit.min.js")).toString()}); readFiles.push({filename: 'embark.js', content: fs.readFileSync(path.join(__dirname, "/../js/build/embark.bundle.js")).toString()}); } else { readFiles.push({filename: file, content: fs.readFileSync(file).toString()}); From 5a71342dcd488c929cbb45c3282b9b623dcea5fa Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 00:10:12 -0500 Subject: [PATCH 046/257] update README --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0fd69483..9301bdfd 100644 --- a/README.md +++ b/README.md @@ -351,7 +351,17 @@ EmbarkJS - Communication **initialization** -The current available communications are Whisper and Orbit. Whisper is supported in go-ethereum. To run Orbit ```ipfs daemon --enable-pubsub-experiment```. +For Whisper: + +```EmbarkJS.Messages.setProvider('whisper')``` + +For Orbit: + +You'll need to use IPFS from master and run it as: ```ipfs daemon --enable-pubsub-experiment```. + +then set the provider: + +```EmbarkJS.Messages.setProvider('orbit', {server: 'localhost', port: 5001})``` **listening to messages** From 61ae4267818bcd1a5a713af6f7cfb52f5486f590 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 00:10:29 -0500 Subject: [PATCH 047/257] post orbit message on listen to callback --- js/embark.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/embark.js b/js/embark.js index aabfbba5..0918d157 100644 --- a/js/embark.js +++ b/js/embark.js @@ -373,7 +373,7 @@ EmbarkJS.Messages.Orbit.listenTo = function(options) { this.orbit.events.on('message', (topics, message) => { // Get the actual content of the message self.orbit.getPost(message.payload.value, true).then((post) => { - promise.cb(post); + promise.cb(post.content); }); }); From 8f434df92634f51db49bd5c94160100ee2478c84 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 08:38:34 -0500 Subject: [PATCH 048/257] return general and original message object in listenTo callback --- js/build/embark.bundle.js | 23 ++++++++++++++++++----- js/embark.js | 23 ++++++++++++++++++----- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index f1d5f92b..89b0d84e 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -250,6 +250,7 @@ var EmbarkJS = var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + this.currentMessages.identity = web3.shh.newIdentity(); } else if (provider === 'orbit') { this.currentMessages = EmbarkJS.Messages.Orbit; if (options === undefined) { @@ -278,7 +279,7 @@ var EmbarkJS = EmbarkJS.Messages.Whisper.sendMessage = function(options) { var topics = options.topic || options.topics; var data = options.data || options.payload; - var identity = options.identity || web3.shh.newIdentity(); + var identity = options.identity || this.identity || web3.shh.newIdentity(); var ttl = options.ttl || 100; var priority = options.priority || 1000; @@ -319,7 +320,7 @@ var EmbarkJS = var topics = options.topic || options.topics; if (typeof topics === 'string') { - topics = [topics]; + topics = [web3.fromAscii(topics)]; } else { // TODO: replace with es6 + babel; var _topics = []; @@ -349,10 +350,17 @@ var EmbarkJS = var filter = web3.shh.filter(filterOptions, function(err, result) { var payload = JSON.parse(web3.toAscii(result.payload)); + var data; if (err) { promise.error(err); } else { - promise.cb(payload); + data = { + topic: topics.map((t) => web3.toAscii(t)), + data: payload, + from: result.from, + time: (new Date(result.sent * 1000)) + }; + promise.cb(payload, data, result); } }); @@ -418,9 +426,14 @@ var EmbarkJS = var promise = new messageEvents(); this.orbit.events.on('message', (topics, message) => { - // Get the actual content of the message self.orbit.getPost(message.payload.value, true).then((post) => { - promise.cb(post); + var data = { + topic: topics, + data: post.content, + from: post.meta.from.name, + time: (new Date(post.meta.ts)) + }; + promise.cb(post.content, data, post); }); }); diff --git a/js/embark.js b/js/embark.js index 0918d157..1dc08eb3 100644 --- a/js/embark.js +++ b/js/embark.js @@ -203,6 +203,7 @@ EmbarkJS.Messages.setProvider = function(provider, options) { var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + this.currentMessages.identity = web3.shh.newIdentity(); } else if (provider === 'orbit') { this.currentMessages = EmbarkJS.Messages.Orbit; if (options === undefined) { @@ -231,7 +232,7 @@ EmbarkJS.Messages.Whisper = { EmbarkJS.Messages.Whisper.sendMessage = function(options) { var topics = options.topic || options.topics; var data = options.data || options.payload; - var identity = options.identity || web3.shh.newIdentity(); + var identity = options.identity || this.identity || web3.shh.newIdentity(); var ttl = options.ttl || 100; var priority = options.priority || 1000; @@ -272,7 +273,7 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { var topics = options.topic || options.topics; if (typeof topics === 'string') { - topics = [topics]; + topics = [web3.fromAscii(topics)]; } else { // TODO: replace with es6 + babel; var _topics = []; @@ -302,10 +303,17 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { var filter = web3.shh.filter(filterOptions, function(err, result) { var payload = JSON.parse(web3.toAscii(result.payload)); + var data; if (err) { promise.error(err); } else { - promise.cb(payload); + data = { + topic: topics.map((t) => web3.toAscii(t)), + data: payload, + from: result.from, + time: (new Date(result.sent * 1000)) + }; + promise.cb(payload, data, result); } }); @@ -371,9 +379,14 @@ EmbarkJS.Messages.Orbit.listenTo = function(options) { var promise = new messageEvents(); this.orbit.events.on('message', (topics, message) => { - // Get the actual content of the message self.orbit.getPost(message.payload.value, true).then((post) => { - promise.cb(post.content); + var data = { + topic: topics, + data: post.content, + from: post.meta.from.name, + time: (new Date(post.meta.ts)) + }; + promise.cb(post.content, data, post); }); }); From 638988485124a83852060594e80de7a2f41491d3 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 09:32:10 -0500 Subject: [PATCH 049/257] fix unneeded ascii conversion for topics --- js/build/embark.bundle.js | 14 +++++++------- js/embark.js | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index 89b0d84e..8e4941d6 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -293,21 +293,21 @@ var EmbarkJS = // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { - topics = topics; + _topics = [web3.fromAscii(topics)]; } else { // TODO: replace with es6 + babel; var _topics = []; for (var i = 0; i < topics.length; i++) { _topics.push(web3.fromAscii(topics[i])); } - topics = _topics; } + topics = _topics; var payload = JSON.stringify(data); var message = { from: identity, - topics: [web3.fromAscii(topics)], + topics: topics, payload: web3.fromAscii(payload), ttl: ttl, priority: priority @@ -320,15 +320,15 @@ var EmbarkJS = var topics = options.topic || options.topics; if (typeof topics === 'string') { - topics = [web3.fromAscii(topics)]; + _topics = [topics]; } else { // TODO: replace with es6 + babel; var _topics = []; for (var i = 0; i < topics.length; i++) { - _topics.push(web3.fromAscii(topics[i])); + _topics.push(topics[i]); } - topics = _topics; } + topics = _topics; var filterOptions = { topics: topics @@ -355,7 +355,7 @@ var EmbarkJS = promise.error(err); } else { data = { - topic: topics.map((t) => web3.toAscii(t)), + topic: topics, data: payload, from: result.from, time: (new Date(result.sent * 1000)) diff --git a/js/embark.js b/js/embark.js index 1dc08eb3..5b67f17a 100644 --- a/js/embark.js +++ b/js/embark.js @@ -246,21 +246,21 @@ EmbarkJS.Messages.Whisper.sendMessage = function(options) { // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { - topics = topics; + _topics = [web3.fromAscii(topics)]; } else { // TODO: replace with es6 + babel; var _topics = []; for (var i = 0; i < topics.length; i++) { _topics.push(web3.fromAscii(topics[i])); } - topics = _topics; } + topics = _topics; var payload = JSON.stringify(data); var message = { from: identity, - topics: [web3.fromAscii(topics)], + topics: topics, payload: web3.fromAscii(payload), ttl: ttl, priority: priority @@ -273,15 +273,15 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { var topics = options.topic || options.topics; if (typeof topics === 'string') { - topics = [web3.fromAscii(topics)]; + _topics = [topics]; } else { // TODO: replace with es6 + babel; var _topics = []; for (var i = 0; i < topics.length; i++) { - _topics.push(web3.fromAscii(topics[i])); + _topics.push(topics[i]); } - topics = _topics; } + topics = _topics; var filterOptions = { topics: topics @@ -308,7 +308,7 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { promise.error(err); } else { data = { - topic: topics.map((t) => web3.toAscii(t)), + topic: topics, data: payload, from: result.from, time: (new Date(result.sent * 1000)) From 0b73194e12d94cb64f3fecaca5abbb36cef72ba1 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 10:13:23 -0500 Subject: [PATCH 050/257] workaround for topics issue --- js/build/embark.bundle.js | 13 ++++++------- js/embark.js | 13 ++++++------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index 8e4941d6..2fdebf59 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -382,7 +382,6 @@ var EmbarkJS = throw new Error("missing option: data"); } - // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { topics = topics; } else { @@ -390,8 +389,6 @@ var EmbarkJS = topics = topics.join(','); } - // TODO: if it's array then join and send ot several - // keep list of channels joined this.orbit.join(topics); var payload = JSON.stringify(data); @@ -403,14 +400,14 @@ var EmbarkJS = var self = this; var topics = options.topic || options.topics; - // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { topics = topics; } else { - // TODO: better to just send to different channels instead topics = topics.join(','); } + this.orbit.join(topics); + var messageEvents = function() { this.cb = function() {}; }; @@ -425,10 +422,12 @@ var EmbarkJS = var promise = new messageEvents(); - this.orbit.events.on('message', (topics, message) => { + this.orbit.events.on('message', (channel, message) => { + // TODO: looks like sometimes it's receving messages from all topics + if (topics !== channel) return; self.orbit.getPost(message.payload.value, true).then((post) => { var data = { - topic: topics, + topic: channel, data: post.content, from: post.meta.from.name, time: (new Date(post.meta.ts)) diff --git a/js/embark.js b/js/embark.js index 5b67f17a..5226b042 100644 --- a/js/embark.js +++ b/js/embark.js @@ -335,7 +335,6 @@ EmbarkJS.Messages.Orbit.sendMessage = function(options) { throw new Error("missing option: data"); } - // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { topics = topics; } else { @@ -343,8 +342,6 @@ EmbarkJS.Messages.Orbit.sendMessage = function(options) { topics = topics.join(','); } - // TODO: if it's array then join and send ot several - // keep list of channels joined this.orbit.join(topics); var payload = JSON.stringify(data); @@ -356,14 +353,14 @@ EmbarkJS.Messages.Orbit.listenTo = function(options) { var self = this; var topics = options.topic || options.topics; - // do fromAscii to each topics unless it's already a string if (typeof topics === 'string') { topics = topics; } else { - // TODO: better to just send to different channels instead topics = topics.join(','); } + this.orbit.join(topics); + var messageEvents = function() { this.cb = function() {}; }; @@ -378,10 +375,12 @@ EmbarkJS.Messages.Orbit.listenTo = function(options) { var promise = new messageEvents(); - this.orbit.events.on('message', (topics, message) => { + this.orbit.events.on('message', (channel, message) => { + // TODO: looks like sometimes it's receving messages from all topics + if (topics !== channel) return; self.orbit.getPost(message.payload.value, true).then((post) => { var data = { - topic: topics, + topic: channel, data: post.content, from: post.meta.from.name, time: (new Date(post.meta.ts)) From a8beb1bf8c3e895937d575bd8eb401d66a34cd20 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 10:42:11 -0500 Subject: [PATCH 051/257] update readme --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9301bdfd..337bf41f 100644 --- a/README.md +++ b/README.md @@ -366,7 +366,7 @@ then set the provider: **listening to messages** ```Javascript - EmbarkJS.Messages.listenTo({topic: ["achannel", "anotherchannel"]}).then(function(message) { console.log("received: " + message); }) + EmbarkJS.Messages.listenTo({topic: ["topic1", "topic2"]}).then(function(message) { console.log("received: " + message); }) ``` **sending messages** @@ -374,15 +374,17 @@ then set the provider: you can send plain text ```Javascript - EmbarkJS.Messages.sendMessage({topic: "achannel", data: 'hello world'}) + EmbarkJS.Messages.sendMessage({topic: "sometopic", data: 'hello world'}) ``` or an object ```Javascript - EmbarkJS.Messages.sendMessage({topic: "achannel", data: {msg: 'hello world'}}) + EmbarkJS.Messages.sendMessage({topic: "sometopic", data: {msg: 'hello world'}}) ``` +note: array of topics are considered an AND. In Whisper you can use another array for OR combinations of several topics e.g ```["topic1", ["topic2", "topic3"]]``` => ```topic1 AND (topic2 OR topic 3)``` + Tests ====== From f2628eabe188b728edc17b9ecea972a81b24d842 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 12:12:39 -0500 Subject: [PATCH 052/257] update required geth version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3079799c..52eca5cf 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Table of Contents Installation ====== -Requirements: geth (1.4.4 or higher), node (5.0.0) and npm +Requirements: geth (1.5.5 or higher), node (5.0.0) and npm Optional: serpent (develop) if using contracts with Serpent, testrpc or ethersim if using the simulator or the test functionality. Further: depending on the dapp stack you choose: [IPFS](https://ipfs.io/) From 6f8916f40ff415d5238520d98e1671fa6f2b6193 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 12:16:02 -0500 Subject: [PATCH 053/257] update web3 version --- js/web3.js | 689 ++++++++++++++++++++++++++++++++++------------------- 1 file changed, 450 insertions(+), 239 deletions(-) diff --git a/js/web3.js b/js/web3.js index c3417254..f652a595 100644 --- a/js/web3.js +++ b/js/web3.js @@ -420,6 +420,7 @@ module.exports=[ ], "name": "deposit", "outputs": [], + "payable": true, "type": "function" }, { @@ -538,13 +539,8 @@ SolidityTypeAddress.prototype.isType = function (name) { return !!name.match(/address(\[([0-9]*)\])?/); }; -SolidityTypeAddress.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeAddress; - },{"./formatters":9,"./type":14}],5:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); @@ -571,10 +567,6 @@ SolidityTypeBool.prototype.isType = function (name) { return !!name.match(/^bool(\[([0-9]*)\])*$/); }; -SolidityTypeBool.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeBool; },{"./formatters":9,"./type":14}],6:[function(require,module,exports){ @@ -582,7 +574,7 @@ var f = require('./formatters'); var SolidityType = require('./type'); /** - * SolidityTypeBytes is a prootype that represents bytes type + * SolidityTypeBytes is a prototype that represents the bytes type. * It matches: * bytes * bytes[] @@ -591,11 +583,8 @@ var SolidityType = require('./type'); * bytes[3][] * bytes[][6][], ... * bytes32 - * bytes64[] * bytes8[4] - * bytes256[][] * bytes[3][] - * bytes64[][6][], ... */ var SolidityTypeBytes = function () { this._inputFormatter = f.formatInputBytes; @@ -609,12 +598,6 @@ SolidityTypeBytes.prototype.isType = function (name) { return !!name.match(/^bytes([0-9]{1,})(\[([0-9]*)\])*$/); }; -SolidityTypeBytes.prototype.staticPartLength = function (name) { - var matches = name.match(/^bytes([0-9]*)/); - var size = parseInt(matches[1]); - return size * this.staticArrayLength(name); -}; - module.exports = SolidityTypeBytes; },{"./formatters":9,"./type":14}],7:[function(require,module,exports){ @@ -634,7 +617,7 @@ module.exports = SolidityTypeBytes; You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -/** +/** * @file coder.js * @author Marek Kotewicz * @date 2015 @@ -652,6 +635,11 @@ var SolidityTypeReal = require('./real'); var SolidityTypeUReal = require('./ureal'); var SolidityTypeBytes = require('./bytes'); +var isDynamic = function (solidityType, type) { + return solidityType.isDynamicType(type) || + solidityType.isDynamicArray(type); +}; + /** * SolidityCoder prototype should be used to encode/decode solidity params of any type */ @@ -664,7 +652,7 @@ var SolidityCoder = function (types) { * * @method _requireType * @param {String} type - * @returns {SolidityType} + * @returns {SolidityType} * @throws {Error} throws if no matching type is found */ SolidityCoder.prototype._requireType = function (type) { @@ -709,10 +697,13 @@ SolidityCoder.prototype.encodeParams = function (types, params) { var dynamicOffset = solidityTypes.reduce(function (acc, solidityType, index) { var staticPartLength = solidityType.staticPartLength(types[index]); var roundedStaticPartLength = Math.floor((staticPartLength + 31) / 32) * 32; - return acc + roundedStaticPartLength; + + return acc + (isDynamic(solidityTypes[index], types[index]) ? + 32 : + roundedStaticPartLength); }, 0); - var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset); + var result = this.encodeMultiWithOffset(types, solidityTypes, encodeds, dynamicOffset); return result; }; @@ -721,12 +712,8 @@ SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, var result = ""; var self = this; - var isDynamic = function (i) { - return solidityTypes[i].isDynamicArray(types[i]) || solidityTypes[i].isDynamicType(types[i]); - }; - types.forEach(function (type, i) { - if (isDynamic(i)) { + if (isDynamic(solidityTypes[i], types[i])) { result += f.formatInputInt(dynamicOffset).encode(); var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); dynamicOffset += e.length / 2; @@ -737,9 +724,9 @@ SolidityCoder.prototype.encodeMultiWithOffset = function (types, solidityTypes, // TODO: figure out nested arrays }); - + types.forEach(function (type, i) { - if (isDynamic(i)) { + if (isDynamic(solidityTypes[i], types[i])) { var e = self.encodeWithOffset(types[i], solidityTypes[i], encodeds[i], dynamicOffset); dynamicOffset += e.length / 2; result += e; @@ -757,7 +744,7 @@ SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded var nestedName = solidityType.nestedName(type); var nestedStaticPartLength = solidityType.staticPartLength(nestedName); var result = encoded[0]; - + (function () { var previousLength = 2; // in int if (solidityType.isDynamicArray(nestedName)) { @@ -767,7 +754,7 @@ SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded } } })(); - + // first element is length, skip it (function () { for (var i = 0; i < encoded.length - 1; i++) { @@ -778,7 +765,7 @@ SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded return result; })(); - + } else if (solidityType.isStaticArray(type)) { return (function () { var nestedName = solidityType.nestedName(type); @@ -791,7 +778,7 @@ SolidityCoder.prototype.encodeWithOffset = function (type, solidityType, encoded var previousLength = 0; // in int for (var i = 0; i < encoded.length; i++) { // calculate length of previous item - previousLength += +(encoded[i - 1] || [])[0] || 0; + previousLength += +(encoded[i - 1] || [])[0] || 0; result += f.formatInputInt(offset + i * nestedStaticPartLength + previousLength * 32).encode(); } })(); @@ -834,7 +821,7 @@ SolidityCoder.prototype.decodeParam = function (type, bytes) { SolidityCoder.prototype.decodeParams = function (types, bytes) { var solidityTypes = this.getSolidityTypes(types); var offsets = this.getOffsets(types, solidityTypes); - + return solidityTypes.map(function (solidityType, index) { return solidityType.decode(bytes, offsets[index], types[index], index); }); @@ -844,16 +831,16 @@ SolidityCoder.prototype.getOffsets = function (types, solidityTypes) { var lengths = solidityTypes.map(function (solidityType, index) { return solidityType.staticPartLength(types[index]); }); - + for (var i = 1; i < lengths.length; i++) { // sum with length of previous element - lengths[i] += lengths[i - 1]; + lengths[i] += lengths[i - 1]; } return lengths.map(function (length, index) { // remove the current length, so the length is sum of previous elements var staticPartLength = solidityTypes[index].staticPartLength(types[index]); - return length - staticPartLength; + return length - staticPartLength; }); }; @@ -878,7 +865,6 @@ var coder = new SolidityCoder([ module.exports = coder; - },{"./address":4,"./bool":5,"./bytes":6,"./dynamicbytes":8,"./formatters":9,"./int":10,"./real":12,"./string":13,"./uint":15,"./ureal":16}],8:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); @@ -895,17 +881,12 @@ SolidityTypeDynamicBytes.prototype.isType = function (name) { return !!name.match(/^bytes(\[([0-9]*)\])*$/); }; -SolidityTypeDynamicBytes.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - SolidityTypeDynamicBytes.prototype.isDynamicType = function () { return true; }; module.exports = SolidityTypeDynamicBytes; - },{"./formatters":9,"./type":14}],9:[function(require,module,exports){ /* This file is part of web3.js. @@ -923,7 +904,7 @@ module.exports = SolidityTypeDynamicBytes; You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -/** +/** * @file formatters.js * @author Marek Kotewicz * @date 2015 @@ -946,7 +927,7 @@ var SolidityParam = require('./param'); */ var formatInputInt = function (value) { BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE); - var result = utils.padLeft(utils.toTwosComplement(value).round().toString(16), 64); + var result = utils.padLeft(utils.toTwosComplement(value).toString(16), 64); return new SolidityParam(result); }; @@ -1067,7 +1048,7 @@ var formatOutputUInt = function (param) { * @returns {BigNumber} input bytes formatted to real */ var formatOutputReal = function (param) { - return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); + return formatOutputInt(param).dividedBy(new BigNumber(2).pow(128)); }; /** @@ -1078,7 +1059,7 @@ var formatOutputReal = function (param) { * @returns {BigNumber} input bytes formatted to ureal */ var formatOutputUReal = function (param) { - return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); + return formatOutputUInt(param).dividedBy(new BigNumber(2).pow(128)); }; /** @@ -1097,10 +1078,13 @@ var formatOutputBool = function (param) { * * @method formatOutputBytes * @param {SolidityParam} left-aligned hex representation of string + * @param {String} name type name * @returns {String} hex string */ -var formatOutputBytes = function (param) { - return '0x' + param.staticPart(); +var formatOutputBytes = function (param, name) { + var matches = name.match(/^bytes([0-9]*)/); + var size = parseInt(matches[1]); + return '0x' + param.staticPart().slice(0, 2 * size); }; /** @@ -1157,7 +1141,6 @@ module.exports = { formatOutputAddress: formatOutputAddress }; - },{"../utils/config":18,"../utils/utils":20,"./param":11,"bignumber.js":"bignumber.js"}],10:[function(require,module,exports){ var f = require('./formatters'); var SolidityType = require('./type'); @@ -1190,10 +1173,6 @@ SolidityTypeInt.prototype.isType = function (name) { return !!name.match(/^int([0-9]*)?(\[([0-9]*)\])*$/); }; -SolidityTypeInt.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeInt; },{"./formatters":9,"./type":14}],11:[function(require,module,exports){ @@ -1382,10 +1361,6 @@ SolidityTypeReal.prototype.isType = function (name) { return !!name.match(/real([0-9]*)?(\[([0-9]*)\])?/); }; -SolidityTypeReal.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeReal; },{"./formatters":9,"./type":14}],13:[function(require,module,exports){ @@ -1404,17 +1379,12 @@ SolidityTypeString.prototype.isType = function (name) { return !!name.match(/^string(\[([0-9]*)\])*$/); }; -SolidityTypeString.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - SolidityTypeString.prototype.isDynamicType = function () { return true; }; module.exports = SolidityTypeString; - },{"./formatters":9,"./type":14}],14:[function(require,module,exports){ var f = require('./formatters'); var SolidityParam = require('./param'); @@ -1446,18 +1416,27 @@ SolidityType.prototype.isType = function (name) { * @return {Number} length of static part in bytes */ SolidityType.prototype.staticPartLength = function (name) { - throw "this method should be overrwritten for type: " + name; + // If name isn't an array then treat it like a single element array. + return (this.nestedTypes(name) || ['[1]']) + .map(function (type) { + // the length of the nested array + return parseInt(type.slice(1, -1), 10) || 1; + }) + .reduce(function (previous, current) { + return previous * current; + // all basic types are 32 bytes long + }, 32); }; /** * Should be used to determine if type is dynamic array - * eg: + * eg: * "type[]" => true * "type[4]" => false * * @method isDynamicArray * @param {String} name - * @return {Bool} true if the type is dynamic array + * @return {Bool} true if the type is dynamic array */ SolidityType.prototype.isDynamicArray = function (name) { var nestedTypes = this.nestedTypes(name); @@ -1466,13 +1445,13 @@ SolidityType.prototype.isDynamicArray = function (name) { /** * Should be used to determine if type is static array - * eg: + * eg: * "type[]" => false * "type[4]" => true * * @method isStaticArray * @param {String} name - * @return {Bool} true if the type is static array + * @return {Bool} true if the type is static array */ SolidityType.prototype.isStaticArray = function (name) { var nestedTypes = this.nestedTypes(name); @@ -1481,7 +1460,7 @@ SolidityType.prototype.isStaticArray = function (name) { /** * Should return length of static array - * eg. + * eg. * "int[32]" => 32 * "int256[14]" => 14 * "int[2][3]" => 3 @@ -1556,7 +1535,7 @@ SolidityType.prototype.nestedTypes = function (name) { * Should be used to encode the value * * @method encode - * @param {Object} value + * @param {Object} value * @param {String} name * @return {String} encoded value */ @@ -1570,7 +1549,7 @@ SolidityType.prototype.encode = function (value, name) { var result = []; result.push(f.formatInputInt(length).encode()); - + value.forEach(function (v) { result.push(self.encode(v, nestedName)); }); @@ -1646,18 +1625,19 @@ SolidityType.prototype.decode = function (bytes, offset, name) { return result; })(); } else if (this.isDynamicType(name)) { - + return (function () { var dynamicOffset = parseInt('0x' + bytes.substr(offset * 2, 64)); // in bytes var length = parseInt('0x' + bytes.substr(dynamicOffset * 2, 64)); // in bytes var roundedLength = Math.floor((length + 31) / 32); // in int - - return self._outputFormatter(new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0)); + var param = new SolidityParam(bytes.substr(dynamicOffset * 2, ( 1 + roundedLength) * 64), 0); + return self._outputFormatter(param, name); })(); } var length = this.staticPartLength(name); - return this._outputFormatter(new SolidityParam(bytes.substr(offset * 2, length * 2))); + var param = new SolidityParam(bytes.substr(offset * 2, length * 2)); + return this._outputFormatter(param, name); }; module.exports = SolidityType; @@ -1694,10 +1674,6 @@ SolidityTypeUInt.prototype.isType = function (name) { return !!name.match(/^uint([0-9]*)?(\[([0-9]*)\])*$/); }; -SolidityTypeUInt.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeUInt; },{"./formatters":9,"./type":14}],16:[function(require,module,exports){ @@ -1732,10 +1708,6 @@ SolidityTypeUReal.prototype.isType = function (name) { return !!name.match(/^ureal([0-9]*)?(\[([0-9]*)\])*$/); }; -SolidityTypeUReal.prototype.staticPartLength = function (name) { - return 32 * this.staticArrayLength(name); -}; - module.exports = SolidityTypeUReal; },{"./formatters":9,"./type":14}],17:[function(require,module,exports){ @@ -1870,7 +1842,7 @@ module.exports = function (value, options) { }; -},{"crypto-js":58,"crypto-js/sha3":79}],20:[function(require,module,exports){ +},{"crypto-js":59,"crypto-js/sha3":80}],20:[function(require,module,exports){ /* This file is part of web3.js. @@ -2248,7 +2220,7 @@ var toBigNumber = function(number) { * @return {BigNumber} */ var toTwosComplement = function (number) { - var bigNumber = toBigNumber(number); + var bigNumber = toBigNumber(number).round(); if (bigNumber.lessThan(0)) { return new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(bigNumber).plus(1); } @@ -2469,9 +2441,9 @@ module.exports = { isJson: isJson }; -},{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":84}],21:[function(require,module,exports){ +},{"./sha3.js":19,"bignumber.js":"bignumber.js","utf8":85}],21:[function(require,module,exports){ module.exports={ - "version": "0.15.3" + "version": "0.18.0" } },{}],22:[function(require,module,exports){ @@ -2509,6 +2481,7 @@ var DB = require('./web3/methods/db'); var Shh = require('./web3/methods/shh'); var Net = require('./web3/methods/net'); var Personal = require('./web3/methods/personal'); +var Swarm = require('./web3/methods/swarm'); var Settings = require('./web3/settings'); var version = require('./version.json'); var utils = require('./utils/utils'); @@ -2518,6 +2491,7 @@ var Batch = require('./web3/batch'); var Property = require('./web3/property'); var HttpProvider = require('./web3/httpprovider'); var IpcProvider = require('./web3/ipcprovider'); +var BigNumber = require('bignumber.js'); @@ -2529,6 +2503,7 @@ function Web3 (provider) { this.shh = new Shh(this); this.net = new Net(this); this.personal = new Personal(this); + this.bzz = new Swarm(this); this.settings = new Settings(); this.version = { api: version.version @@ -2559,6 +2534,7 @@ Web3.prototype.reset = function (keepIsSyncing) { this.settings = new Settings(); }; +Web3.prototype.BigNumber = BigNumber; Web3.prototype.toHex = utils.toHex; Web3.prototype.toAscii = utils.toAscii; Web3.prototype.toUtf8 = utils.toUtf8; @@ -2622,7 +2598,7 @@ Web3.prototype.createBatch = function () { module.exports = Web3; -},{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/property":44,"./web3/requestmanager":45,"./web3/settings":46}],23:[function(require,module,exports){ +},{"./utils/sha3":19,"./utils/utils":20,"./version.json":21,"./web3/batch":24,"./web3/extend":28,"./web3/httpprovider":32,"./web3/iban":33,"./web3/ipcprovider":34,"./web3/methods/db":37,"./web3/methods/eth":38,"./web3/methods/net":39,"./web3/methods/personal":40,"./web3/methods/shh":41,"./web3/methods/swarm":42,"./web3/property":45,"./web3/requestmanager":46,"./web3/settings":47,"bignumber.js":"bignumber.js"}],23:[function(require,module,exports){ /* This file is part of web3.js. @@ -2712,7 +2688,7 @@ AllSolidityEvents.prototype.attachToContract = function (contract) { module.exports = AllSolidityEvents; -},{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":42}],24:[function(require,module,exports){ +},{"../utils/sha3":19,"../utils/utils":20,"./event":27,"./filter":29,"./formatters":30,"./methods/watches":43}],24:[function(require,module,exports){ /* This file is part of web3.js. @@ -2767,7 +2743,7 @@ Batch.prototype.execute = function () { }).forEach(function (result, index) { if (requests[index].callback) { - if (!Jsonrpc.getInstance().isValidResponse(result)) { + if (!Jsonrpc.isValidResponse(result)) { return requests[index].callback(errors.InvalidResponse(result)); } @@ -2888,7 +2864,7 @@ var checkForContractAddress = function(contract, callback){ // stop watching after 50 blocks (timeout) if (count > 50) { - filter.stopWatching(); + filter.stopWatching(function() {}); callbackFired = true; if (callback) @@ -2908,10 +2884,10 @@ var checkForContractAddress = function(contract, callback){ if(callbackFired || !code) return; - filter.stopWatching(); + filter.stopWatching(function() {}); callbackFired = true; - if(code.length > 2) { + if(code.length > 3) { // console.log('Contract code deployed!'); @@ -2976,6 +2952,16 @@ var ContractFactory = function (eth, abi) { options = args.pop(); } + if (options.value > 0) { + var constructorAbi = abi.filter(function (json) { + return json.type === 'constructor' && json.inputs.length === args.length; + })[0] || {}; + + if (!constructorAbi.payable) { + throw new Error('Cannot send value to non-payable constructor'); + } + } + var bytes = encodeConstructorParams(this.abi, args); options.data += bytes; @@ -3116,10 +3102,12 @@ module.exports = { InvalidResponse: function (result){ var message = !!result && !!result.error && !!result.error.message ? result.error.message : 'Invalid JSON RPC response: ' + JSON.stringify(result); return new Error(message); + }, + ConnectionTimeout: function (ms){ + return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); } }; - },{}],27:[function(require,module,exports){ /* This file is part of web3.js. @@ -3330,7 +3318,7 @@ SolidityEvent.prototype.attachToContract = function (contract) { module.exports = SolidityEvent; -},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":42}],28:[function(require,module,exports){ +},{"../solidity/coder":7,"../utils/sha3":19,"../utils/utils":20,"./filter":29,"./formatters":30,"./methods/watches":43}],28:[function(require,module,exports){ var formatters = require('./formatters'); var utils = require('./../utils/utils'); var Method = require('./method'); @@ -3380,7 +3368,7 @@ var extend = function (web3) { module.exports = extend; -},{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":44}],29:[function(require,module,exports){ +},{"./../utils/utils":20,"./formatters":30,"./method":36,"./property":45}],29:[function(require,module,exports){ /* This file is part of web3.js. @@ -3513,7 +3501,7 @@ var pollFilter = function(self) { }; -var Filter = function (requestManager, options, methods, formatter, callback) { +var Filter = function (requestManager, options, methods, formatter, callback, filterCreationErrorCallback) { var self = this; var implementation = {}; methods.forEach(function (method) { @@ -3533,6 +3521,7 @@ var Filter = function (requestManager, options, methods, formatter, callback) { self.callbacks.forEach(function(cb){ cb(error); }); + filterCreationErrorCallback(error); } else { self.filterId = id; @@ -3571,11 +3560,15 @@ Filter.prototype.watch = function (callback) { return this; }; -Filter.prototype.stopWatching = function () { +Filter.prototype.stopWatching = function (callback) { this.requestManager.stopPolling(this.filterId); - // remove filter async - this.implementation.uninstallFilter(this.filterId, function(){}); this.callbacks = []; + // remove filter async + if (callback) { + this.implementation.uninstallFilter(this.filterId, callback); + } else { + return this.implementation.uninstallFilter(this.filterId); + } }; Filter.prototype.get = function (callback) { @@ -3629,7 +3622,7 @@ module.exports = Filter; You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ -/** +/** * @file formatters.js * @author Marek Kotewicz * @author Fabian Vogelsteller @@ -3696,7 +3689,7 @@ var inputCallFormatter = function (options){ options[key] = utils.fromDecimal(options[key]); }); - return options; + return options; }; /** @@ -3721,12 +3714,12 @@ var inputTransactionFormatter = function (options){ options[key] = utils.fromDecimal(options[key]); }); - return options; + return options; }; /** * Formats the output of a transaction to its proper values - * + * * @method outputTransactionFormatter * @param {Object} tx * @returns {Object} @@ -3745,7 +3738,7 @@ var outputTransactionFormatter = function (tx){ /** * Formats the output of a transaction receipt to its proper values - * + * * @method outputTransactionReceiptFormatter * @param {Object} receipt * @returns {Object} @@ -3771,7 +3764,7 @@ var outputTransactionReceiptFormatter = function (receipt){ * Formats the output of a block to its proper values * * @method outputBlockFormatter - * @param {Object} block + * @param {Object} block * @returns {Object} */ var outputBlockFormatter = function(block) { @@ -3799,7 +3792,7 @@ var outputBlockFormatter = function(block) { /** * Formats the output of a log - * + * * @method outputLogFormatter * @param {Object} log object * @returns {Object} log @@ -3840,7 +3833,7 @@ var inputPostFormatter = function(post) { return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); }); - return post; + return post; }; /** @@ -3892,6 +3885,10 @@ var outputSyncingFormatter = function(result) { result.startingBlock = utils.toDecimal(result.startingBlock); result.currentBlock = utils.toDecimal(result.currentBlock); result.highestBlock = utils.toDecimal(result.highestBlock); + if (result.knownStates) { + result.knownStates = utils.toDecimal(result.knownStates); + result.pulledStates = utils.toDecimal(result.pulledStates); + } return result; }; @@ -3953,6 +3950,7 @@ var SolidityFunction = function (eth, json, address) { return i.type; }); this._constant = json.constant; + this._payable = json.payable; this._name = utils.transformToFullName(json); this._address = address; }; @@ -4027,11 +4025,21 @@ SolidityFunction.prototype.call = function () { if (!callback) { var output = this._eth.call(payload, defaultBlock); return this.unpackOutput(output); - } - + } + var self = this; this._eth.call(payload, defaultBlock, function (error, output) { - callback(error, self.unpackOutput(output)); + if (error) return callback(error, null); + + var unpacked = null; + try { + unpacked = self.unpackOutput(output); + } + catch (e) { + error = e; + } + + callback(error, unpacked); }); }; @@ -4045,6 +4053,10 @@ SolidityFunction.prototype.sendTransaction = function () { var callback = this.extractCallback(args); var payload = this.toPayload(args); + if (payload.value > 0 && !this._payable) { + throw new Error('Cannot send value to non-payable function'); + } + if (!callback) { return this._eth.sendTransaction(payload); } @@ -4113,11 +4125,11 @@ SolidityFunction.prototype.request = function () { var callback = this.extractCallback(args); var payload = this.toPayload(args); var format = this.unpackOutput.bind(this); - + return { method: this._constant ? 'eth_call' : 'eth_sendTransaction', callback: callback, - params: [payload], + params: [payload], format: format }; }; @@ -4193,15 +4205,11 @@ var errors = require('./errors'); // workaround to use httpprovider in different envs var XMLHttpRequest; // jshint ignore: line - -// meteor server environment -if (typeof Meteor !== 'undefined' && Meteor.isServer) { // jshint ignore: line - XMLHttpRequest = Npm.require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line +var XHR2 = require('xhr2');; // jshint ignore: line // browser -} else if (typeof window !== 'undefined' && window.XMLHttpRequest) { +if (typeof window !== 'undefined' && window.XMLHttpRequest) { XMLHttpRequest = window.XMLHttpRequest; // jshint ignore: line - // node } else { XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore: line @@ -4210,8 +4218,9 @@ if (typeof Meteor !== 'undefined' && Meteor.isServer) { // jshint ignore: line /** * HttpProvider should be used to send rpc calls over http */ -var HttpProvider = function (host) { +var HttpProvider = function (host, timeout) { this.host = host || 'http://localhost:8545'; + this.timeout = timeout || 0; }; /** @@ -4222,7 +4231,15 @@ var HttpProvider = function (host) { * @return {XMLHttpRequest} object */ HttpProvider.prototype.prepareRequest = function (async) { - var request = new XMLHttpRequest(); + var request; + + if (async) { + request = new XHR2(); + request.timeout = this.timeout; + }else { + request = new XMLHttpRequest(); + } + request.open('POST', this.host, async); request.setRequestHeader('Content-Type','application/json'); return request; @@ -4249,7 +4266,7 @@ HttpProvider.prototype.send = function (payload) { try { result = JSON.parse(result); } catch(e) { - throw errors.InvalidResponse(request.responseText); + throw errors.InvalidResponse(request.responseText); } return result; @@ -4263,23 +4280,27 @@ HttpProvider.prototype.send = function (payload) { * @param {Function} callback triggered on end with (err, result) */ HttpProvider.prototype.sendAsync = function (payload, callback) { - var request = this.prepareRequest(true); + var request = this.prepareRequest(true); request.onreadystatechange = function() { - if (request.readyState === 4) { + if (request.readyState === 4 && request.timeout !== 1) { var result = request.responseText; var error = null; try { result = JSON.parse(result); } catch(e) { - error = errors.InvalidResponse(request.responseText); + error = errors.InvalidResponse(request.responseText); } callback(error, result); } }; - + + request.ontimeout = function() { + callback(errors.ConnectionTimeout(this.timeout)); + }; + try { request.send(JSON.stringify(payload)); } catch(error) { @@ -4309,8 +4330,7 @@ HttpProvider.prototype.isConnected = function() { module.exports = HttpProvider; - -},{"./errors":26,"xmlhttprequest":17}],33:[function(require,module,exports){ +},{"./errors":26,"xhr2":86,"xmlhttprequest":17}],33:[function(require,module,exports){ /* This file is part of web3.js. @@ -4338,7 +4358,7 @@ var BigNumber = require('bignumber.js'); var padLeft = function (string, bytes) { var result = string; while (result.length < bytes * 2) { - result = '00' + result; + result = '0' + result; } return result; }; @@ -4768,25 +4788,13 @@ module.exports = IpcProvider; /** @file jsonrpc.js * @authors: * Marek Kotewicz + * Aaron Kumavis * @date 2015 */ -var Jsonrpc = function () { - // singleton pattern - if (arguments.callee._singletonInstance) { - return arguments.callee._singletonInstance; - } - arguments.callee._singletonInstance = this; - - this.messageId = 1; -}; - -/** - * @return {Jsonrpc} singleton - */ -Jsonrpc.getInstance = function () { - var instance = new Jsonrpc(); - return instance; +// Initialize Jsonrpc as a simple object with utility functions. +var Jsonrpc = { + messageId: 0 }; /** @@ -4797,15 +4805,18 @@ Jsonrpc.getInstance = function () { * @param {Array} params, an array of method params, optional * @returns {Object} valid jsonrpc payload object */ -Jsonrpc.prototype.toPayload = function (method, params) { +Jsonrpc.toPayload = function (method, params) { if (!method) console.error('jsonrpc method should be specified!'); + // advance message ID + Jsonrpc.messageId++; + return { jsonrpc: '2.0', + id: Jsonrpc.messageId, method: method, - params: params || [], - id: this.messageId++ + params: params || [] }; }; @@ -4816,12 +4827,16 @@ Jsonrpc.prototype.toPayload = function (method, params) { * @param {Object} * @returns {Boolean} true if response is valid, otherwise false */ -Jsonrpc.prototype.isValidResponse = function (response) { - return !!response && - !response.error && - response.jsonrpc === '2.0' && - typeof response.id === 'number' && - response.result !== undefined; // only undefined is not valid json object +Jsonrpc.isValidResponse = function (response) { + return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); + + function validateSingleMessage(message){ + return !!message && + !message.error && + message.jsonrpc === '2.0' && + typeof message.id === 'number' && + message.result !== undefined; // only undefined is not valid json object + } }; /** @@ -4831,10 +4846,9 @@ Jsonrpc.prototype.isValidResponse = function (response) { * @param {Array} messages, an array of objects with method (required) and params (optional) fields * @returns {Array} batch payload */ -Jsonrpc.prototype.toBatchPayload = function (messages) { - var self = this; +Jsonrpc.toBatchPayload = function (messages) { return messages.map(function (message) { - return self.toPayload(message.method, message.params); + return Jsonrpc.toPayload(message.method, message.params); }); }; @@ -5393,6 +5407,10 @@ var properties = function () { name: 'blockNumber', getter: 'eth_blockNumber', outputFormatter: utils.toDecimal + }), + new Property({ + name: 'protocolVersion', + getter: 'eth_protocolVersion' }) ]; }; @@ -5421,7 +5439,7 @@ Eth.prototype.isSyncing = function (callback) { module.exports = Eth; -},{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":43,"../property":44,"../syncing":47,"../transfer":48,"./watches":42}],39:[function(require,module,exports){ +},{"../../utils/config":18,"../../utils/utils":20,"../contract":25,"../filter":29,"../formatters":30,"../iban":33,"../method":36,"../namereg":44,"../property":45,"../syncing":48,"../transfer":49,"./watches":43}],39:[function(require,module,exports){ /* This file is part of web3.js. @@ -5475,7 +5493,7 @@ var properties = function () { module.exports = Net; -},{"../../utils/utils":20,"../property":44}],40:[function(require,module,exports){ +},{"../../utils/utils":20,"../property":45}],40:[function(require,module,exports){ /* This file is part of web3.js. @@ -5536,6 +5554,13 @@ var methods = function () { inputFormatter: [formatters.inputAddressFormatter, null, null] }); + var sendTransaction = new Method({ + name: 'sendTransaction', + call: 'personal_sendTransaction', + params: 2, + inputFormatter: [formatters.inputTransactionFormatter, null] + }); + var lockAccount = new Method({ name: 'lockAccount', call: 'personal_lockAccount', @@ -5546,6 +5571,7 @@ var methods = function () { return [ newAccount, unlockAccount, + sendTransaction, lockAccount ]; }; @@ -5562,7 +5588,7 @@ var properties = function () { module.exports = Personal; -},{"../formatters":30,"../method":36,"../property":44}],41:[function(require,module,exports){ +},{"../formatters":30,"../method":36,"../property":45}],41:[function(require,module,exports){ /* This file is part of web3.js. @@ -5650,7 +5676,154 @@ var methods = function () { module.exports = Shh; -},{"../filter":29,"../formatters":30,"../method":36,"./watches":42}],42:[function(require,module,exports){ +},{"../filter":29,"../formatters":30,"../method":36,"./watches":43}],42:[function(require,module,exports){ +/* + This file is part of web3.js. + + web3.js is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + web3.js is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with web3.js. If not, see . +*/ +/** + * @file bzz.js + * @author Alex Beregszaszi + * @date 2016 + * + * Reference: https://github.com/ethereum/go-ethereum/blob/swarm/internal/web3ext/web3ext.go#L33 + */ + +"use strict"; + +var Method = require('../method'); +var Property = require('../property'); + +function Swarm(web3) { + this._requestManager = web3._requestManager; + + var self = this; + + methods().forEach(function(method) { + method.attachToObject(self); + method.setRequestManager(self._requestManager); + }); + + properties().forEach(function(p) { + p.attachToObject(self); + p.setRequestManager(self._requestManager); + }); +} + +var methods = function () { + var blockNetworkRead = new Method({ + name: 'blockNetworkRead', + call: 'bzz_blockNetworkRead', + params: 1, + inputFormatter: [null] + }); + + var syncEnabled = new Method({ + name: 'syncEnabled', + call: 'bzz_syncEnabled', + params: 1, + inputFormatter: [null] + }); + + var swapEnabled = new Method({ + name: 'swapEnabled', + call: 'bzz_swapEnabled', + params: 1, + inputFormatter: [null] + }); + + var download = new Method({ + name: 'download', + call: 'bzz_download', + params: 2, + inputFormatter: [null, null] + }); + + var upload = new Method({ + name: 'upload', + call: 'bzz_upload', + params: 2, + inputFormatter: [null, null] + }); + + var retrieve = new Method({ + name: 'retrieve', + call: 'bzz_retrieve', + params: 1, + inputFormatter: [null] + }); + + var store = new Method({ + name: 'store', + call: 'bzz_store', + params: 2, + inputFormatter: [null, null] + }); + + var get = new Method({ + name: 'get', + call: 'bzz_get', + params: 1, + inputFormatter: [null] + }); + + var put = new Method({ + name: 'put', + call: 'bzz_put', + params: 2, + inputFormatter: [null, null] + }); + + var modify = new Method({ + name: 'modify', + call: 'bzz_modify', + params: 4, + inputFormatter: [null, null, null, null] + }); + + return [ + blockNetworkRead, + syncEnabled, + swapEnabled, + download, + upload, + retrieve, + store, + get, + put, + modify + ]; +}; + +var properties = function () { + return [ + new Property({ + name: 'hive', + getter: 'bzz_hive' + }), + new Property({ + name: 'info', + getter: 'bzz_info' + }) + ]; +}; + + +module.exports = Swarm; + +},{"../method":36,"../property":45}],43:[function(require,module,exports){ /* This file is part of web3.js. @@ -5766,7 +5939,7 @@ module.exports = { }; -},{"../method":36}],43:[function(require,module,exports){ +},{"../method":36}],44:[function(require,module,exports){ /* This file is part of web3.js. @@ -5807,7 +5980,7 @@ module.exports = { }; -},{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],44:[function(require,module,exports){ +},{"../contracts/GlobalRegistrar.json":1,"../contracts/ICAPRegistrar.json":2}],45:[function(require,module,exports){ /* This file is part of web3.js. @@ -5848,7 +6021,7 @@ Property.prototype.setRequestManager = function (rm) { /** * Should be called to format input args of method - * + * * @method formatInput * @param {Array} * @return {Array} @@ -5865,7 +6038,7 @@ Property.prototype.formatInput = function (arg) { * @return {Object} */ Property.prototype.formatOutput = function (result) { - return this.outputFormatter && result !== null ? this.outputFormatter(result) : result; + return this.outputFormatter && result !== null && result !== undefined ? this.outputFormatter(result) : result; }; /** @@ -5884,7 +6057,7 @@ Property.prototype.extractCallback = function (args) { /** * Should attach function to method - * + * * @method attachToObject * @param {Object} * @param {Function} @@ -5892,7 +6065,7 @@ Property.prototype.extractCallback = function (args) { Property.prototype.attachToObject = function (obj) { var proto = { get: this.buildGet(), - enumerable: true + enumerable: true }; var names = this.name.split('.'); @@ -5916,7 +6089,7 @@ Property.prototype.buildGet = function () { return function get() { return property.formatOutput(property.requestManager.send({ method: property.getter - })); + })); }; }; @@ -5953,7 +6126,7 @@ Property.prototype.request = function () { module.exports = Property; -},{"../utils/utils":20}],45:[function(require,module,exports){ +},{"../utils/utils":20}],46:[function(require,module,exports){ /* This file is part of web3.js. @@ -6010,10 +6183,10 @@ RequestManager.prototype.send = function (data) { return null; } - var payload = Jsonrpc.getInstance().toPayload(data.method, data.params); + var payload = Jsonrpc.toPayload(data.method, data.params); var result = this.provider.send(payload); - if (!Jsonrpc.getInstance().isValidResponse(result)) { + if (!Jsonrpc.isValidResponse(result)) { throw errors.InvalidResponse(result); } @@ -6032,13 +6205,13 @@ RequestManager.prototype.sendAsync = function (data, callback) { return callback(errors.InvalidProvider()); } - var payload = Jsonrpc.getInstance().toPayload(data.method, data.params); + var payload = Jsonrpc.toPayload(data.method, data.params); this.provider.sendAsync(payload, function (err, result) { if (err) { return callback(err); } - if (!Jsonrpc.getInstance().isValidResponse(result)) { + if (!Jsonrpc.isValidResponse(result)) { return callback(errors.InvalidResponse(result)); } @@ -6058,7 +6231,7 @@ RequestManager.prototype.sendBatch = function (data, callback) { return callback(errors.InvalidProvider()); } - var payload = Jsonrpc.getInstance().toBatchPayload(data); + var payload = Jsonrpc.toBatchPayload(data); this.provider.sendAsync(payload, function (err, results) { if (err) { @@ -6173,7 +6346,7 @@ RequestManager.prototype.poll = function () { return; } - var payload = Jsonrpc.getInstance().toBatchPayload(pollsData); + var payload = Jsonrpc.toBatchPayload(pollsData); // map the request id to they poll id var pollsIdMap = {}; @@ -6206,7 +6379,7 @@ RequestManager.prototype.poll = function () { }).filter(function (result) { return !!result; }).filter(function (result) { - var valid = Jsonrpc.getInstance().isValidResponse(result); + var valid = Jsonrpc.isValidResponse(result); if (!valid) { result.callback(errors.InvalidResponse(result)); } @@ -6220,7 +6393,7 @@ RequestManager.prototype.poll = function () { module.exports = RequestManager; -},{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],46:[function(require,module,exports){ +},{"../utils/config":18,"../utils/utils":20,"./errors":26,"./jsonrpc":35}],47:[function(require,module,exports){ var Settings = function () { @@ -6231,7 +6404,7 @@ var Settings = function () { module.exports = Settings; -},{}],47:[function(require,module,exports){ +},{}],48:[function(require,module,exports){ /* This file is part of web3.js. @@ -6326,7 +6499,7 @@ IsSyncing.prototype.stopWatching = function () { module.exports = IsSyncing; -},{"../utils/utils":20,"./formatters":30}],48:[function(require,module,exports){ +},{"../utils/utils":20,"./formatters":30}],49:[function(require,module,exports){ /* This file is part of web3.js. @@ -6420,9 +6593,9 @@ var deposit = function (eth, from, to, value, client, callback) { module.exports = transfer; -},{"../contracts/SmartExchange.json":3,"./iban":33}],49:[function(require,module,exports){ +},{"../contracts/SmartExchange.json":3,"./iban":33}],50:[function(require,module,exports){ -},{}],50:[function(require,module,exports){ +},{}],51:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -6516,13 +6689,18 @@ module.exports = transfer; */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { + // Skip reset of nRounds has been set before and key did not change + if (this._nRounds && this._keyPriorReset === this._key) { + return; + } + // Shortcuts - var key = this._key; + var key = this._keyPriorReset = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds - var nRounds = this._nRounds = keySize + 6 + var nRounds = this._nRounds = keySize + 6; // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; @@ -6650,7 +6828,7 @@ module.exports = transfer; return CryptoJS.AES; })); -},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],51:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],52:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -7526,7 +7704,7 @@ module.exports = transfer; })); -},{"./core":52}],52:[function(require,module,exports){ +},{"./core":53}],53:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -7546,6 +7724,25 @@ module.exports = transfer; * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { + /* + * Local polyfil of Object.create + */ + var create = Object.create || (function () { + function F() {}; + + return function (obj) { + var subtype; + + F.prototype = obj; + + subtype = new F(); + + F.prototype = null; + + return subtype; + }; + }()) + /** * CryptoJS namespace. */ @@ -7560,7 +7757,7 @@ module.exports = transfer; * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { - function F() {} + return { /** @@ -7583,8 +7780,7 @@ module.exports = transfer; */ extend: function (overrides) { // Spawn - F.prototype = this; - var subtype = new F(); + var subtype = create(this); // Augment if (overrides) { @@ -7592,7 +7788,7 @@ module.exports = transfer; } // Create default initializer - if (!subtype.hasOwnProperty('init')) { + if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; @@ -8269,7 +8465,7 @@ module.exports = transfer; return CryptoJS; })); -},{}],53:[function(require,module,exports){ +},{}],54:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -8360,40 +8556,52 @@ module.exports = transfer; // Shortcuts var base64StrLength = base64Str.length; var map = this._map; + var reverseMap = this._reverseMap; + + if (!reverseMap) { + reverseMap = this._reverseMap = []; + for (var j = 0; j < map.length; j++) { + reverseMap[map.charCodeAt(j)] = j; + } + } // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); - if (paddingIndex != -1) { + if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } // Convert - var words = []; - var nBytes = 0; - for (var i = 0; i < base64StrLength; i++) { - if (i % 4) { - var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); - var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); - words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); - nBytes++; - } - } + return parseLoop(base64Str, base64StrLength, reverseMap); - return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; + + function parseLoop(base64Str, base64StrLength, reverseMap) { + var words = []; + var nBytes = 0; + for (var i = 0; i < base64StrLength; i++) { + if (i % 4) { + var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << ((i % 4) * 2); + var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> (6 - (i % 4) * 2); + words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); + nBytes++; + } + } + return WordArray.create(words, nBytes); + } }()); return CryptoJS.enc.Base64; })); -},{"./core":52}],54:[function(require,module,exports){ +},{"./core":53}],55:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -8543,7 +8751,7 @@ module.exports = transfer; return CryptoJS.enc.Utf16; })); -},{"./core":52}],55:[function(require,module,exports){ +},{"./core":53}],56:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -8676,7 +8884,7 @@ module.exports = transfer; return CryptoJS.EvpKDF; })); -},{"./core":52,"./hmac":57,"./sha1":76}],56:[function(require,module,exports){ +},{"./core":53,"./hmac":58,"./sha1":77}],57:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -8743,7 +8951,7 @@ module.exports = transfer; return CryptoJS.format.Hex; })); -},{"./cipher-core":51,"./core":52}],57:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],58:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -8887,7 +9095,7 @@ module.exports = transfer; })); -},{"./core":52}],58:[function(require,module,exports){ +},{"./core":53}],59:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -8906,7 +9114,7 @@ module.exports = transfer; return CryptoJS; })); -},{"./aes":50,"./cipher-core":51,"./core":52,"./enc-base64":53,"./enc-utf16":54,"./evpkdf":55,"./format-hex":56,"./hmac":57,"./lib-typedarrays":59,"./md5":60,"./mode-cfb":61,"./mode-ctr":63,"./mode-ctr-gladman":62,"./mode-ecb":64,"./mode-ofb":65,"./pad-ansix923":66,"./pad-iso10126":67,"./pad-iso97971":68,"./pad-nopadding":69,"./pad-zeropadding":70,"./pbkdf2":71,"./rabbit":73,"./rabbit-legacy":72,"./rc4":74,"./ripemd160":75,"./sha1":76,"./sha224":77,"./sha256":78,"./sha3":79,"./sha384":80,"./sha512":81,"./tripledes":82,"./x64-core":83}],59:[function(require,module,exports){ +},{"./aes":51,"./cipher-core":52,"./core":53,"./enc-base64":54,"./enc-utf16":55,"./evpkdf":56,"./format-hex":57,"./hmac":58,"./lib-typedarrays":60,"./md5":61,"./mode-cfb":62,"./mode-ctr":64,"./mode-ctr-gladman":63,"./mode-ecb":65,"./mode-ofb":66,"./pad-ansix923":67,"./pad-iso10126":68,"./pad-iso97971":69,"./pad-nopadding":70,"./pad-zeropadding":71,"./pbkdf2":72,"./rabbit":74,"./rabbit-legacy":73,"./rc4":75,"./ripemd160":76,"./sha1":77,"./sha224":78,"./sha256":79,"./sha3":80,"./sha384":81,"./sha512":82,"./tripledes":83,"./x64-core":84}],60:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -8983,7 +9191,7 @@ module.exports = transfer; return CryptoJS.lib.WordArray; })); -},{"./core":52}],60:[function(require,module,exports){ +},{"./core":53}],61:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -9252,7 +9460,7 @@ module.exports = transfer; return CryptoJS.MD5; })); -},{"./core":52}],61:[function(require,module,exports){ +},{"./core":53}],62:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9331,7 +9539,7 @@ module.exports = transfer; return CryptoJS.mode.CFB; })); -},{"./cipher-core":51,"./core":52}],62:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],63:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9448,7 +9656,7 @@ module.exports = transfer; return CryptoJS.mode.CTRGladman; })); -},{"./cipher-core":51,"./core":52}],63:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],64:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9507,7 +9715,7 @@ module.exports = transfer; return CryptoJS.mode.CTR; })); -},{"./cipher-core":51,"./core":52}],64:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],65:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9548,7 +9756,7 @@ module.exports = transfer; return CryptoJS.mode.ECB; })); -},{"./cipher-core":51,"./core":52}],65:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],66:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9603,7 +9811,7 @@ module.exports = transfer; return CryptoJS.mode.OFB; })); -},{"./cipher-core":51,"./core":52}],66:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],67:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9653,7 +9861,7 @@ module.exports = transfer; return CryptoJS.pad.Ansix923; })); -},{"./cipher-core":51,"./core":52}],67:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],68:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9698,7 +9906,7 @@ module.exports = transfer; return CryptoJS.pad.Iso10126; })); -},{"./cipher-core":51,"./core":52}],68:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],69:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9739,7 +9947,7 @@ module.exports = transfer; return CryptoJS.pad.Iso97971; })); -},{"./cipher-core":51,"./core":52}],69:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],70:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9770,7 +9978,7 @@ module.exports = transfer; return CryptoJS.pad.NoPadding; })); -},{"./cipher-core":51,"./core":52}],70:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],71:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9816,7 +10024,7 @@ module.exports = transfer; return CryptoJS.pad.ZeroPadding; })); -},{"./cipher-core":51,"./core":52}],71:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53}],72:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -9962,7 +10170,7 @@ module.exports = transfer; return CryptoJS.PBKDF2; })); -},{"./core":52,"./hmac":57,"./sha1":76}],72:[function(require,module,exports){ +},{"./core":53,"./hmac":58,"./sha1":77}],73:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -10153,7 +10361,7 @@ module.exports = transfer; return CryptoJS.RabbitLegacy; })); -},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],73:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],74:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -10346,7 +10554,7 @@ module.exports = transfer; return CryptoJS.Rabbit; })); -},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],74:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],75:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -10486,7 +10694,7 @@ module.exports = transfer; return CryptoJS.RC4; })); -},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],75:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],76:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -10754,7 +10962,7 @@ module.exports = transfer; return CryptoJS.RIPEMD160; })); -},{"./core":52}],76:[function(require,module,exports){ +},{"./core":53}],77:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -10905,7 +11113,7 @@ module.exports = transfer; return CryptoJS.SHA1; })); -},{"./core":52}],77:[function(require,module,exports){ +},{"./core":53}],78:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -10986,7 +11194,7 @@ module.exports = transfer; return CryptoJS.SHA224; })); -},{"./core":52,"./sha256":78}],78:[function(require,module,exports){ +},{"./core":53,"./sha256":79}],79:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -11186,7 +11394,7 @@ module.exports = transfer; return CryptoJS.SHA256; })); -},{"./core":52}],79:[function(require,module,exports){ +},{"./core":53}],80:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -11510,7 +11718,7 @@ module.exports = transfer; return CryptoJS.SHA3; })); -},{"./core":52,"./x64-core":83}],80:[function(require,module,exports){ +},{"./core":53,"./x64-core":84}],81:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -11594,7 +11802,7 @@ module.exports = transfer; return CryptoJS.SHA384; })); -},{"./core":52,"./sha512":81,"./x64-core":83}],81:[function(require,module,exports){ +},{"./core":53,"./sha512":82,"./x64-core":84}],82:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -11918,7 +12126,7 @@ module.exports = transfer; return CryptoJS.SHA512; })); -},{"./core":52,"./x64-core":83}],82:[function(require,module,exports){ +},{"./core":53,"./x64-core":84}],83:[function(require,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS @@ -12689,7 +12897,7 @@ module.exports = transfer; return CryptoJS.TripleDES; })); -},{"./cipher-core":51,"./core":52,"./enc-base64":53,"./evpkdf":55,"./md5":60}],83:[function(require,module,exports){ +},{"./cipher-core":52,"./core":53,"./enc-base64":54,"./evpkdf":56,"./md5":61}],84:[function(require,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS @@ -12994,8 +13202,8 @@ module.exports = transfer; return CryptoJS; })); -},{"./core":52}],84:[function(require,module,exports){ -/*! https://mths.be/utf8js v2.0.0 by @mathias */ +},{"./core":53}],85:[function(require,module,exports){ +/*! https://mths.be/utf8js v2.1.2 by @mathias */ ;(function(root) { // Detect free variables `exports` @@ -13154,7 +13362,7 @@ module.exports = transfer; // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { - var byte2 = readContinuationByte(); + byte2 = readContinuationByte(); codePoint = ((byte1 & 0x1F) << 6) | byte2; if (codePoint >= 0x80) { return codePoint; @@ -13181,7 +13389,7 @@ module.exports = transfer; byte2 = readContinuationByte(); byte3 = readContinuationByte(); byte4 = readContinuationByte(); - codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) | + codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) | (byte3 << 0x06) | byte4; if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) { return codePoint; @@ -13209,7 +13417,7 @@ module.exports = transfer; /*--------------------------------------------------------------------------*/ var utf8 = { - 'version': '2.0.0', + 'version': '2.1.2', 'encode': utf8encode, 'decode': utf8decode }; @@ -13240,6 +13448,9 @@ module.exports = transfer; }(this)); +},{}],86:[function(require,module,exports){ +module.exports = XMLHttpRequest; + },{}],"bignumber.js":[function(require,module,exports){ /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */ @@ -15925,7 +16136,7 @@ module.exports = transfer; } })(this); -},{"crypto":49}],"web3":[function(require,module,exports){ +},{"crypto":50}],"web3":[function(require,module,exports){ var Web3 = require('./lib/web3'); // dont override global variable From e8ef3ed8b7ef07a03d4ea7b8107b31dbbe4bdc66 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 13:32:32 -0500 Subject: [PATCH 054/257] update to web3js 0.18.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 03b868b0..ed6a3489 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,7 @@ "serve-static": "^1.11.1", "shelljs": "^0.5.0", "toposort": "^0.2.10", - "web3": "^0.15.0", + "web3": "^0.18.0", "wrench": "^1.5.8" }, "author": "Iuri Matias ", From 15b8d9b33eb96a2695d2d5b8555565779eed68d1 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 16:52:29 -0500 Subject: [PATCH 055/257] supporting uploading dapp to swarm --- lib/cmd.js | 12 ++++++++++++ lib/index.js | 7 +++++++ lib/ipfs.js | 5 +++-- lib/swarm.js | 29 +++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 lib/swarm.js diff --git a/lib/cmd.js b/lib/cmd.js index b314b714..4e8fc629 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -15,6 +15,7 @@ Cmd.prototype.process = function(args) { this.simulator(); this.test(); this.ipfs(); + this.swarm(); this.otherCommands(); program.parse(args); }; @@ -137,6 +138,7 @@ Cmd.prototype.test = function() { }); }; +// TODO: replace both of this with a deploy/upload command Cmd.prototype.ipfs = function() { var self = this; program @@ -147,6 +149,16 @@ Cmd.prototype.ipfs = function() { }); }; +Cmd.prototype.swarm = function() { + var self = this; + program + .command('swarm') + .description('deploy to SWARM') + .action(function() { + self.Embark.swarm(); + }); +}; + Cmd.prototype.otherCommands = function() { program .action(function(env){ diff --git a/lib/index.js b/lib/index.js index 55d689f3..5a2d6343 100644 --- a/lib/index.js +++ b/lib/index.js @@ -23,6 +23,7 @@ var Monitor = require('./monitor.js'); var ServicesMonitor = require('./services.js'); var Console = require('./console.js'); var IPFS = require('./ipfs.js'); +var Swarm = require('./swarm.js'); var Embark = { @@ -304,6 +305,12 @@ var Embark = { ipfs: function() { var ipfs = new IPFS({buildDir: 'dist/'}); ipfs.deploy(); + }, + + // TODO: should deploy if it hasn't already + swarm: function() { + var swarm = new Swarm({buildDir: 'dist/'}); + swarm.deploy(); } }; diff --git a/lib/ipfs.js b/lib/ipfs.js index 6333c2d6..38b2bfed 100644 --- a/lib/ipfs.js +++ b/lib/ipfs.js @@ -13,8 +13,9 @@ IPFS.prototype.deploy = function() { ipfs_bin = "~/go/bin/ipfs"; } - var cmd = ipfs_bin + " add -r " + build_dir; - console.log(("=== adding " + cmd + " to ipfs").green); + var cmd = ipfs_bin + " add -r " + this.buildDir; + console.log(("=== adding " + this.buildDir + " to ipfs").green); + console.log(cmd.green); var result = exec(cmd); var rows = result.output.split("\n"); diff --git a/lib/swarm.js b/lib/swarm.js new file mode 100644 index 00000000..a7f6cc75 --- /dev/null +++ b/lib/swarm.js @@ -0,0 +1,29 @@ +var colors = require('colors'); + +var Swarm = function(options) { + this.options = options; + this.buildDir = options.buildDir || 'dist/'; +}; + +Swarm.prototype.deploy = function() { + var swarm_bin = exec('which swarm').output.split("\n")[0]; + + if (swarm_bin==='swarm not found' || swarm_bin === ''){ + console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow); + swarm_bin = "~/go/bin/swarm"; + } + + var cmd = swarm_bin + " --defaultpath " + this.buildDir + "index.html --recursive up " + this.buildDir; + console.log(("=== adding " + this.buildDir + " to swarm").green); + console.log(cmd.green); + + var result = exec(cmd); + var rows = result.output.split("\n"); + var dir_hash = rows.reverse()[1]; + + console.log(("=== DApp available at http://localhost:8500/bzz:/" + dir_hash + "/").green); +}; + +module.exports = Swarm; + + From c53d92baa5e9575b9a310084ab172d943010a9c1 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sat, 7 Jan 2017 20:37:48 -0500 Subject: [PATCH 056/257] refactor deployments to upload command --- lib/cmd.js | 28 ++++++++++------------------ lib/index.js | 20 +++++++++++--------- 2 files changed, 21 insertions(+), 27 deletions(-) diff --git a/lib/cmd.js b/lib/cmd.js index 4e8fc629..9df0fdd7 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -14,8 +14,7 @@ Cmd.prototype.process = function(args) { this.blockchain(); this.simulator(); this.test(); - this.ipfs(); - this.swarm(); + this.upload(); this.otherCommands(); program.parse(args); }; @@ -138,24 +137,17 @@ Cmd.prototype.test = function() { }); }; -// TODO: replace both of this with a deploy/upload command -Cmd.prototype.ipfs = function() { +Cmd.prototype.upload = function() { var self = this; program - .command('ipfs') - .description('deploy to IPFS') - .action(function() { - self.Embark.ipfs(); - }); -}; - -Cmd.prototype.swarm = function() { - var self = this; - program - .command('swarm') - .description('deploy to SWARM') - .action(function() { - self.Embark.swarm(); + .command('upload [platform]') + .description('upload your dapp to a decentralized storage. possible options: ipfs, swarm (e.g embark upload swarm)') + .action(function(platform ,options) { + // TODO: get env in cmd line as well + self.Embark.initConfig('development', { + embarkConfig: 'embark.json' + }); + self.Embark.upload(platform); }); }; diff --git a/lib/index.js b/lib/index.js index 5a2d6343..8c5c15c2 100644 --- a/lib/index.js +++ b/lib/index.js @@ -302,17 +302,19 @@ var Embark = { }, // TODO: should deploy if it hasn't already - ipfs: function() { - var ipfs = new IPFS({buildDir: 'dist/'}); - ipfs.deploy(); + upload: function(platform) { + if (platform === 'ipfs') { + var ipfs = new IPFS({buildDir: 'dist/'}); + ipfs.deploy(); + } else if (platform === 'swarm') { + var swarm = new Swarm({buildDir: 'dist/'}); + swarm.deploy(); + } else { + console.log(("unknown platform: " + platform).red); + console.log('try "embark upload ipfs" or "embark upload swarm"'.green); + } }, - // TODO: should deploy if it hasn't already - swarm: function() { - var swarm = new Swarm({buildDir: 'dist/'}); - swarm.deploy(); - } - }; module.exports = Embark; From 26f2ad7407a251e283c92325f15520e80528e4e3 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 8 Jan 2017 13:19:27 -0500 Subject: [PATCH 057/257] refactor ipfs and swarm code --- lib/ipfs.js | 50 ++++++++++++++++++++++++++++++++++++-------------- lib/swarm.js | 51 ++++++++++++++++++++++++++++++++++++++------------- 2 files changed, 74 insertions(+), 27 deletions(-) diff --git a/lib/ipfs.js b/lib/ipfs.js index 38b2bfed..1c79c907 100644 --- a/lib/ipfs.js +++ b/lib/ipfs.js @@ -1,4 +1,5 @@ var colors = require('colors'); +var async = require('async'); var IPFS = function(options) { this.options = options; @@ -6,24 +7,45 @@ var IPFS = function(options) { }; IPFS.prototype.deploy = function() { - var ipfs_bin = exec('which ipfs').output.split("\n")[0]; + var self = this; + async.waterfall([ + function findBinary(callback) { + var ipfs_bin = exec('which ipfs').output.split("\n")[0]; - if (ipfs_bin==='ipfs not found'){ - console.log('=== WARNING: IPFS not in an executable path. Guessing ~/go/bin/ipfs for path'.yellow); - ipfs_bin = "~/go/bin/ipfs"; - } + if (ipfs_bin==='ipfs not found'){ + console.log('=== WARNING: IPFS not in an executable path. Guessing ~/go/bin/ipfs for path'.yellow); + ipfs_bin = "~/go/bin/ipfs"; + } - var cmd = ipfs_bin + " add -r " + this.buildDir; - console.log(("=== adding " + this.buildDir + " to ipfs").green); - console.log(cmd.green); + return callback(null, ipfs_bin); + }, + function runCommand(ipfs_bin, callback) { + var cmd = ipfs_bin + " add -r " + self.buildDir; + console.log(("=== adding " + self.buildDir + " to ipfs").green); + console.log(cmd.green); + var result = exec(cmd); - var result = exec(cmd); - var rows = result.output.split("\n"); - var dir_row = rows[rows.length - 2]; - var dir_hash = dir_row.split(" ")[1]; + return callback(null, result); + }, + function getHashFromOutput(result, callback) { + var rows = result.output.split("\n"); + var dir_row = rows[rows.length - 2]; + var dir_hash = dir_row.split(" ")[1]; - console.log(("=== DApp available at http://localhost:8080/ipfs/" + dir_hash + "/").green); - console.log(("=== DApp available at http://gateway.ipfs.io/ipfs/" + dir_hash + "/").green); + return callback(null, dir_hash); + }, + function printUrls(dir_hash, callback) { + console.log(("=== DApp available at http://localhost:8080/ipfs/" + dir_hash + "/").green); + console.log(("=== DApp available at http://gateway.ipfs.io/ipfs/" + dir_hash + "/").green); + + return callback(); + } + ], function(err, result) { + if (err) { + console.log("error uploading to ipfs".red); + console.log(err); + } + }); }; module.exports = IPFS; diff --git a/lib/swarm.js b/lib/swarm.js index a7f6cc75..1ebb36bb 100644 --- a/lib/swarm.js +++ b/lib/swarm.js @@ -1,4 +1,5 @@ var colors = require('colors'); +var async = require('async'); var Swarm = function(options) { this.options = options; @@ -6,24 +7,48 @@ var Swarm = function(options) { }; Swarm.prototype.deploy = function() { - var swarm_bin = exec('which swarm').output.split("\n")[0]; + var self = this; + async.waterfall([ + function findBinary(callback) { + var swarm_bin = exec('which swarm').output.split("\n")[0]; - if (swarm_bin==='swarm not found' || swarm_bin === ''){ - console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow); - swarm_bin = "~/go/bin/swarm"; - } + if (swarm_bin==='swarm not found' || swarm_bin === ''){ + console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow); + swarm_bin = "~/go/bin/swarm"; + } - var cmd = swarm_bin + " --defaultpath " + this.buildDir + "index.html --recursive up " + this.buildDir; - console.log(("=== adding " + this.buildDir + " to swarm").green); - console.log(cmd.green); + return callback(null, swarm_bin); + }, + function runCommand(swarm_bin, callback) { + var cmd = swarm_bin + " --defaultpath " + self.buildDir + "index.html --recursive up " + self.buildDir; + console.log(("=== adding " + self.buildDir + " to swarm").green); + console.log(cmd.green); + var result = exec(cmd); - var result = exec(cmd); - var rows = result.output.split("\n"); - var dir_hash = rows.reverse()[1]; + return callback(null, result); + }, + function getHashFromOutput(result, callback) { + if (result.code !== 0) { + return callback("couldn't upload, is the swarm daemon running?"); + } - console.log(("=== DApp available at http://localhost:8500/bzz:/" + dir_hash + "/").green); + var rows = result.output.split("\n"); + var dir_hash = rows.reverse()[1]; + + return callback(null, dir_hash); + }, + function printUrls(dir_hash, callback) { + console.log(("=== DApp available at http://localhost:8500/bzz:/" + dir_hash + "/").green); + + return callback(); + } + ], function(err, result) { + if (err) { + console.log("error uploading to swarm".red); + console.log(err); + } + }); }; module.exports = Swarm; - From 59c63b98e1877f4a926d7be0347bd893fdda8541 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 8 Jan 2017 15:47:15 -0500 Subject: [PATCH 058/257] add small test for console --- test/console.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 test/console.js diff --git a/test/console.js b/test/console.js new file mode 100644 index 00000000..05c3045b --- /dev/null +++ b/test/console.js @@ -0,0 +1,22 @@ +/*globals describe, it*/ +var Console = require('../lib/console.js'); +var assert = require('assert'); + +describe('embark.Console', function() { + var console = new Console(); + + describe('#executeCmd', function() { + + describe('command: help', function() { + + it('i should provide a help text', function(done) { + console.executeCmd('help', function(output) { + var lines = output.split('\n'); + assert.equal(lines[0], 'Welcome to Embark 2'); + assert.equal(lines[2], 'possible commands are:'); + done(); + }); + }); + }); + }); +}); From 2afcb340216d9cc87450ac7caddd07a689b181d8 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 8 Jan 2017 15:57:23 -0500 Subject: [PATCH 059/257] Update README.md --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 477f7eeb..e8ec16ce 100644 --- a/README.md +++ b/README.md @@ -353,15 +353,19 @@ EmbarkJS - Communication For Whisper: -```EmbarkJS.Messages.setProvider('whisper')``` +```Javascript + EmbarkJS.Messages.setProvider('whisper') +``` For Orbit: -You'll need to use IPFS from master and run it as: ```ipfs daemon --enable-pubsub-experiment```. +You'll need to use IPFS from master and run it as: ```ipfs daemon --enable-pubsub-experiment``` then set the provider: -```EmbarkJS.Messages.setProvider('orbit', {server: 'localhost', port: 5001})``` +```Javascript + EmbarkJS.Messages.setProvider('orbit', {server: 'localhost', port: 5001}) +``` **listening to messages** From 439fbf6b419b0076a7deeef9bc3f0ba80749ffca Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 8 Jan 2017 16:15:25 -0500 Subject: [PATCH 060/257] make jshint happy --- js/embark.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/js/embark.js b/js/embark.js index 5226b042..1f381b18 100644 --- a/js/embark.js +++ b/js/embark.js @@ -1,4 +1,5 @@ -var Promise = require('bluebird'); +/*jshint esversion: 6 */ +var Promise = require('bluebird'); // jshint ignore: line //var Ipfs = require('./ipfs.js'); var EmbarkJS = { @@ -235,6 +236,7 @@ EmbarkJS.Messages.Whisper.sendMessage = function(options) { var identity = options.identity || this.identity || web3.shh.newIdentity(); var ttl = options.ttl || 100; var priority = options.priority || 1000; + var _topics; if (topics === undefined) { throw new Error("missing option: topic"); @@ -249,7 +251,6 @@ EmbarkJS.Messages.Whisper.sendMessage = function(options) { _topics = [web3.fromAscii(topics)]; } else { // TODO: replace with es6 + babel; - var _topics = []; for (var i = 0; i < topics.length; i++) { _topics.push(web3.fromAscii(topics[i])); } @@ -271,12 +272,12 @@ EmbarkJS.Messages.Whisper.sendMessage = function(options) { EmbarkJS.Messages.Whisper.listenTo = function(options) { var topics = options.topic || options.topics; + var _topics; if (typeof topics === 'string') { _topics = [topics]; } else { // TODO: replace with es6 + babel; - var _topics = []; for (var i = 0; i < topics.length; i++) { _topics.push(topics[i]); } From 84b577bc003981d36c82b4031b6749cb28c59d8f Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Tue, 10 Jan 2017 06:04:48 -0500 Subject: [PATCH 061/257] first stab at docs --- .gitignore | 2 + docs/Makefile | 20 + docs/build/doctrees/environment.pickle | Bin 0 -> 3766 bytes docs/build/doctrees/index.doctree | Bin 0 -> 4738 bytes docs/build/html/.buildinfo | 4 + docs/build/html/_sources/index.rst.txt | 20 + docs/build/html/_static/ajax-loader.gif | Bin 0 -> 673 bytes docs/build/html/_static/alabaster.css | 693 ++ docs/build/html/_static/basic.css | 632 ++ docs/build/html/_static/comment-bright.png | Bin 0 -> 756 bytes docs/build/html/_static/comment-close.png | Bin 0 -> 829 bytes docs/build/html/_static/comment.png | Bin 0 -> 641 bytes docs/build/html/_static/custom.css | 1 + docs/build/html/_static/doctools.js | 287 + docs/build/html/_static/down-pressed.png | Bin 0 -> 222 bytes docs/build/html/_static/down.png | Bin 0 -> 202 bytes docs/build/html/_static/file.png | Bin 0 -> 286 bytes docs/build/html/_static/jquery-3.1.0.js | 10074 ++++++++++++++++++ docs/build/html/_static/jquery.js | 4 + docs/build/html/_static/minus.png | Bin 0 -> 90 bytes docs/build/html/_static/plus.png | Bin 0 -> 90 bytes docs/build/html/_static/pygments.css | 65 + docs/build/html/_static/searchtools.js | 758 ++ docs/build/html/_static/underscore-1.3.1.js | 999 ++ docs/build/html/_static/underscore.js | 31 + docs/build/html/_static/up-pressed.png | Bin 0 -> 214 bytes docs/build/html/_static/up.png | Bin 0 -> 203 bytes docs/build/html/_static/websupport.js | 808 ++ docs/build/html/genindex.html | 94 + docs/build/html/index.html | 113 + docs/build/html/objects.inv | Bin 0 -> 245 bytes docs/build/html/search.html | 104 + docs/build/html/searchindex.js | 1 + docs/make.bat | 36 + docs/source/conf.py | 157 + docs/source/index.rst | 20 + 36 files changed, 14923 insertions(+) create mode 100644 docs/Makefile create mode 100644 docs/build/doctrees/environment.pickle create mode 100644 docs/build/doctrees/index.doctree create mode 100644 docs/build/html/.buildinfo create mode 100644 docs/build/html/_sources/index.rst.txt create mode 100644 docs/build/html/_static/ajax-loader.gif create mode 100644 docs/build/html/_static/alabaster.css create mode 100644 docs/build/html/_static/basic.css create mode 100644 docs/build/html/_static/comment-bright.png create mode 100644 docs/build/html/_static/comment-close.png create mode 100644 docs/build/html/_static/comment.png create mode 100644 docs/build/html/_static/custom.css create mode 100644 docs/build/html/_static/doctools.js create mode 100644 docs/build/html/_static/down-pressed.png create mode 100644 docs/build/html/_static/down.png create mode 100644 docs/build/html/_static/file.png create mode 100644 docs/build/html/_static/jquery-3.1.0.js create mode 100644 docs/build/html/_static/jquery.js create mode 100644 docs/build/html/_static/minus.png create mode 100644 docs/build/html/_static/plus.png create mode 100644 docs/build/html/_static/pygments.css create mode 100644 docs/build/html/_static/searchtools.js create mode 100644 docs/build/html/_static/underscore-1.3.1.js create mode 100644 docs/build/html/_static/underscore.js create mode 100644 docs/build/html/_static/up-pressed.png create mode 100644 docs/build/html/_static/up.png create mode 100644 docs/build/html/_static/websupport.js create mode 100644 docs/build/html/genindex.html create mode 100644 docs/build/html/index.html create mode 100644 docs/build/html/objects.inv create mode 100644 docs/build/html/search.html create mode 100644 docs/build/html/searchindex.js create mode 100644 docs/make.bat create mode 100644 docs/source/conf.py create mode 100644 docs/source/index.rst diff --git a/.gitignore b/.gitignore index 002a236f..4cd6403b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ demo/dist/ demo/.embark/development/ demo/config/production/password boilerplate/dist/ +docs/_build +docs/utils/__pycache_ diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..c293cf23 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = embark +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/build/doctrees/environment.pickle b/docs/build/doctrees/environment.pickle new file mode 100644 index 0000000000000000000000000000000000000000..50c603772711747b26640f939a3940e69d1e7b22 GIT binary patch literal 3766 zcmbVP>y8{p6<&LH=eifKF-Q(sG$aVdf}Kf1q@Vx-2XCy^#A|D9V~J$d)O6QO^=x-n zr>c5)MzSUNk;Rcp1eD?je|Q0&011h=-~o6C{^vW@J(JlL$WAQnxVtXr`kiyW{@vPN z{=T*1|Jmz07jZW2@$58KGD~@8oW1s55hv09($eSd*6-aj*R?lJxze%B;%pp*GK*q^ z7x$^XeqlY$nc`S&D?XxQhEENy+g2j8v58H>HNCFKS;VK#ZbdRIOq}RmCL?Uwb$`Y! zv^GKkgA~u)u@f71?GefQ+}YQj@FbKe?-<$P>5!?DALtGVBR?3K_FeahD=n{)P4G@^ z+oob?S{5qgFDIfHGFvxnoUxQUu_<1$EAWLGqvBy#Zx^@nAU!^D2CeB5Tj8%c6PH$$Natat8!xziDoGCnTp2(Y1(<~jW^%yRf19+!pomT#5eK$^VSUTamCPW-eO+O6s>6bN}~)|!za*(cg4 ztoE=-5^jPd1|;T~6FU^u4cnyEAO<8ZZrSY$v@D9M`rScM<}5Ubkz!-Ta&h4b2}7lD z)FVo8S&z8!Rccz?6jSkv_%`Yjk6OGcPVu@czC)d=1`VhTa;$@-yoSH;;qUu|YnFvV zsL6kt8mKxQ`d&F3YG6igDQ&DMlhklaQfN{E|;M#UCN-&m_yP zQBvKY2`p6&=yw0HMo;a>FgEp7+<#CaMfXco?Tr*#$eC0peIQ-;%bR`QJbm$chnFq1 z^^keU0IKL9s7IsU1!UsPm!F8E2)*=ETU$IeQZ|ivj=CRQwT-MuhsaLk1}nBz_G_6X zGu&vQb{BSS=2FXNETKz0-FAX=KjAD+_Py-Mf* zf!#k|26lwcmx>98v=>HL+f|mM;R!bQvE5WiJc|OBoUxg9pMeedECxmfiVukxP+vjK zcqm15VjHjzfSF*PLJj0%#c;r}8hYku0)^x*%!liuRvuJxWT{ z*ml)ch#A0&_kks<*vDD?@tqib)c1|g+z_Rt!YEeGzVkIp37s9KM-5T@7g!;gJM$8N z-@c@MC~6Dtg08Zy3Fja%%U&NlZCmh%x`4Oo7hl;XA7iR?l7W%lU`bMjh{AgJ_P=-g z_CJ3$+BPt#42T$ovg=8dH!qluq)Jhcs~~kwtlI4{&S5HpiTSSVp4(kiV;YR4G?_FU ziLIJ(pwYI8xoxOX=qW@{C`A8NVN9;y?e~q8plLBTqn=dbK8@o(8meFkrUpOdi5skA z%%goo<Q(sQ>{a?{ct3#_AjJOgqi*-k{(Fz_K0P>m|Nhe_w~r1F4(~qQKRUX9^z`BWulJAk zZ}mTXWAE+bk8Zg^=iD7Rnv-#s7Y1++WrP5uixy_I_me$M9Bm`#CA%s^)0v0n?Ch+U z&y0|n4^6~R`#7l)o^OVUWG4YnS)2rzl8Srs_uPJqpdQ2-1^^9sD5QQAx#xwwR^bl2 zzR=1UP4MzX1-7_UR88V(LBtHB+T1`R=Ky9FQpd%@c96v;kHeDyw7{>)K`*m){NKNoBovunpohmVT!C zkk-Izc|wn1{$mad)0fQTH}Drzeoo^P88RY{JHaExG7Wl$EMvM)XTav5c0Su%youe(F`cCgcH^FmiiCGA3ld9$ zYML_@3OC8Hc;R;Yq2K8|AUgh~74pl=1+gcPfrb0t=gRSOHyPpRWbEbQjTE3im+Hjs fImng0n$H$csKW_ZyA*BgPkdM@>~s8plJ&j-mv_Hf literal 0 HcmV?d00001 diff --git a/docs/build/doctrees/index.doctree b/docs/build/doctrees/index.doctree new file mode 100644 index 0000000000000000000000000000000000000000..ff08a4cc974f415f2dcf634a28674a2f707e0e33 GIT binary patch literal 4738 zcmds5O>ZPe8Mb44zHHBUolS(quGC)TV*?q_hGbbZa6yrfh|!S4287V6x2C&hs_gEr zPF1yM=CD#YAl6cW1Zh4b;KmKEAbtW;q)6Pj@i&knMLbpAJu~ffHY*SpER9uNT_5lJ zywCg9A8h|}cDUjGOg9ukrg@}}6A@CCo0gr3X`=HF^VfcqKgw^LmZXz}#CZECH%&X@ zp&j2ghdc>+K$S<5(9>ib*%PYCJ|_FsrL+~ciy;n-1&jX zyZ~=VNK)--#+5tLgHUNiHH{V)zy%ccB7Vk`>FeG&(;nBJVj_z|k7zHVkfjrdL=&Fi z4C+ZCwD(YpKuby=dLfrI(EOYp=ReL16E^^iwK@9&>#|-pCTx>!u_Lx+nwm_l$#eE1 z>;8W!Z?+vvPIgSAqR=-7?Ow!egpj8e2^F7w=ADUmV`AyO|S5lV-kjCG-{Tlt*wKI z-@%3NTB_p0_VPm0ipe~rsb=}fbM|(#J&nXTzpxSjMEI1&%(UNzbAaw@n45i`1W^`J z#={Un;KDSjkrmxEu}tzJRCFA+N+i(&M?xXfLG-CkWj|y`X21t@aWiWMc!OGch{#$cDnR!4 zl|4SL+oM|iG<&c=ewHadDoybZnBw_oHU<0hWA>LPuxEc=6TOD`KbHU=vA>mw*Kd4A z#Ifmrfp|kvA_KO<`*d@2V`ByRrzPb3g$op`|1-cpDF8oh*$ZAex&Gf{UJ1XB_-W4` zUt}KZasMhnfAZF6!@b=1xzJZp*@nTNSomrVe)%rbD576(HosJ*$?AkHoKVH}D*|a} z71!HUT&K2VPlZH9YD;8<16MA)MAV+37)*pMPLRM}P>XmhBEOpSU5$zyW%jFGKEjBr z{P#(wMYYiFzJ7VPTZ&^3mt}XY)^^2@EetyBob9oDnYpI2u|ir!3nCIfEN|*oReV{N zjZ8~Xtr5)8UR<*cf$LZ%(xq|4)yDToltH5^oSU7Hjc zc=^sR%B~C33$r-&mm1hTFQhod=5jxik&iT#Mkw%YiAK}@%Xi)ib2c2AeIG^lgiqZ{ z2T)IBI?c3?yKNwwqSVXur2n(QP9sz~ro%{ttXVwnm_u6_0#sM3_;cI&AQg0Nvaq=jhf@+;je* zl$y4_d~BXaZy;m{TiE;w!ENy~G6!mbeq!!3K4lSp$SK>Auo~@0B$;Mtr=WcZOrAp( zWwvN?j$J(@AC0~VuVNIn8t2~(7&3MMY8FEKMJD!Rw1im-S@#r%+J8TD9EI%892^Ck zOh{y9>G>g7w%IK4##GZUslr|{`vrn4%x+$?f?r_I(4R)|5LEww9KvBIz(b){;&!rW zx;&}dukGyDR~(wRLy!Ot6Q_`%D1n%E+=+Hs@Wp@qQb2Tt|G?O-~Nu=+*kZahH;O016dAH?5KFY?XZF@pn z1G+CQtUY48qs*21SG88l4i>GK&2^>)Vaiy(X|AnD?joKeNZZP>_>hAP15(vOanX@J mf=?{DhUG2~9H1g|Ul9DFx^$5a@u8MT+~i^H-b$QoeEe_VW*->< literal 0 HcmV?d00001 diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo new file mode 100644 index 00000000..4ee25387 --- /dev/null +++ b/docs/build/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: b94830c2795d3cca64d62e85d39c088d +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_sources/index.rst.txt b/docs/build/html/_sources/index.rst.txt new file mode 100644 index 00000000..74174a83 --- /dev/null +++ b/docs/build/html/_sources/index.rst.txt @@ -0,0 +1,20 @@ +.. embark documentation master file, created by + sphinx-quickstart on Tue Jan 10 05:57:43 2017. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to embark's documentation! +================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/build/html/_static/ajax-loader.gif b/docs/build/html/_static/ajax-loader.gif new file mode 100644 index 0000000000000000000000000000000000000000..61faf8cab23993bd3e1560bff0668bd628642330 GIT binary patch literal 673 zcmZ?wbhEHb6krfw_{6~Q|Nno%(3)e{?)x>&1u}A`t?OF7Z|1gRivOgXi&7IyQd1Pl zGfOfQ60;I3a`F>X^fL3(@);C=vM_KlFfb_o=k{|A33hf2a5d61U}gjg=>Rd%XaNQW zW@Cw{|b%Y*pl8F?4B9 zlo4Fz*0kZGJabY|>}Okf0}CCg{u4`zEPY^pV?j2@h+|igy0+Kz6p;@SpM4s6)XEMg z#3Y4GX>Hjlml5ftdH$4x0JGdn8~MX(U~_^d!Hi)=HU{V%g+mi8#UGbE-*ao8f#h+S z2a0-5+vc7MU$e-NhmBjLIC1v|)9+Im8x1yacJ7{^tLX(ZhYi^rpmXm0`@ku9b53aN zEXH@Y3JaztblgpxbJt{AtE1ad1Ca>{v$rwwvK(>{m~Gf_=-Ro7Fk{#;i~+{{>QtvI yb2P8Zac~?~=sRA>$6{!(^3;ZP0TPFR(G_-UDU(8Jl0?(IXu$~#4A!880|o%~Al1tN literal 0 HcmV?d00001 diff --git a/docs/build/html/_static/alabaster.css b/docs/build/html/_static/alabaster.css new file mode 100644 index 00000000..a88ce299 --- /dev/null +++ b/docs/build/html/_static/alabaster.css @@ -0,0 +1,693 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif; + font-size: 17px; + background-color: #fff; + color: #000; + margin: 0; + padding: 0; +} + + +div.document { + width: 940px; + margin: 30px auto 0 auto; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 220px; +} + +div.sphinxsidebar { + width: 220px; + font-size: 14px; + line-height: 1.5; +} + +hr { + border: 1px solid #B1B4B6; +} + +div.body { + background-color: #fff; + color: #3E4349; + padding: 0 30px 0 30px; +} + +div.body > .section { + text-align: left; +} + +div.footer { + width: 940px; + margin: 20px auto 30px auto; + font-size: 14px; + color: #888; + text-align: right; +} + +div.footer a { + color: #888; +} + +p.caption { + font-family: inherit; + font-size: inherit; +} + + +div.relations { + display: none; +} + + +div.sphinxsidebar a { + color: #444; + text-decoration: none; + border-bottom: 1px dotted #999; +} + +div.sphinxsidebar a:hover { + border-bottom: 1px solid #999; +} + +div.sphinxsidebarwrapper { + padding: 18px 10px; +} + +div.sphinxsidebarwrapper p.logo { + padding: 0; + margin: -10px 0 0 0px; + text-align: center; +} + +div.sphinxsidebarwrapper h1.logo { + margin-top: -10px; + text-align: center; + margin-bottom: 5px; + text-align: left; +} + +div.sphinxsidebarwrapper h1.logo-name { + margin-top: 0px; +} + +div.sphinxsidebarwrapper p.blurb { + margin-top: 0; + font-style: normal; +} + +div.sphinxsidebar h3, +div.sphinxsidebar h4 { + font-family: 'Garamond', 'Georgia', serif; + color: #444; + font-size: 24px; + font-weight: normal; + margin: 0 0 5px 0; + padding: 0; +} + +div.sphinxsidebar h4 { + font-size: 20px; +} + +div.sphinxsidebar h3 a { + color: #444; +} + +div.sphinxsidebar p.logo a, +div.sphinxsidebar h3 a, +div.sphinxsidebar p.logo a:hover, +div.sphinxsidebar h3 a:hover { + border: none; +} + +div.sphinxsidebar p { + color: #555; + margin: 10px 0; +} + +div.sphinxsidebar ul { + margin: 10px 0; + padding: 0; + color: #000; +} + +div.sphinxsidebar ul li.toctree-l1 > a { + font-size: 120%; +} + +div.sphinxsidebar ul li.toctree-l2 > a { + font-size: 110%; +} + +div.sphinxsidebar input { + border: 1px solid #CCC; + font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif; + font-size: 1em; +} + +div.sphinxsidebar hr { + border: none; + height: 1px; + color: #AAA; + background: #AAA; + + text-align: left; + margin-left: 0; + width: 50%; +} + +/* -- body styles ----------------------------------------------------------- */ + +a { + color: #004B6B; + text-decoration: underline; +} + +a:hover { + color: #6D4100; + text-decoration: underline; +} + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Garamond', 'Georgia', serif; + font-weight: normal; + margin: 30px 0px 10px 0px; + padding: 0; +} + +div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } +div.body h2 { font-size: 180%; } +div.body h3 { font-size: 150%; } +div.body h4 { font-size: 130%; } +div.body h5 { font-size: 100%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #DDD; + padding: 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + color: #444; + background: #EAEAEA; +} + +div.body p, div.body dd, div.body li { + line-height: 1.4em; +} + +div.admonition { + margin: 20px 0px; + padding: 10px 30px; + background-color: #EEE; + border: 1px solid #CCC; +} + +div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { + background-color: ; + border-bottom: 1px solid #fafafa; +} + +dd div.admonition { + margin-left: -60px; + padding-left: 60px; +} + +div.admonition p.admonition-title { + font-family: 'Garamond', 'Georgia', serif; + font-weight: normal; + font-size: 24px; + margin: 0 0 10px 0; + padding: 0; + line-height: 1; +} + +div.admonition p.last { + margin-bottom: 0; +} + +div.highlight { + background-color: #fff; +} + +dt:target, .highlight { + background: #FAF3E8; +} + +div.warning { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.danger { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.error { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.caution { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.attention { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.important { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.note { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.tip { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.hint { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.seealso { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.topic { + background-color: #EEE; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre, tt, code { + font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; + font-size: 0.9em; +} + +.hll { + background-color: #FFC; + margin: 0 -12px; + padding: 0 12px; + display: block; +} + +img.screenshot { +} + +tt.descname, tt.descclassname, code.descname, code.descclassname { + font-size: 0.95em; +} + +tt.descname, code.descname { + padding-right: 0.08em; +} + +img.screenshot { + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils { + border: 1px solid #888; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; +} + +table.docutils td, table.docutils th { + border: 1px solid #888; + padding: 0.25em 0.7em; +} + +table.field-list, table.footnote { + border: none; + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} + +table.footnote { + margin: 15px 0; + width: 100%; + border: 1px solid #EEE; + background: #FDFDFD; + font-size: 0.9em; +} + +table.footnote + table.footnote { + margin-top: -15px; + border-top: none; +} + +table.field-list th { + padding: 0 0.8em 0 0; +} + +table.field-list td { + padding: 0; +} + +table.field-list p { + margin-bottom: 0.8em; +} + +table.footnote td.label { + width: .1px; + padding: 0.3em 0 0.3em 0.5em; +} + +table.footnote td { + padding: 0.3em 0.5em; +} + +dl { + margin: 0; + padding: 0; +} + +dl dd { + margin-left: 30px; +} + +blockquote { + margin: 0 0 0 30px; + padding: 0; +} + +ul, ol { + /* Matches the 30px from the narrow-screen "li > ul" selector below */ + margin: 10px 0 10px 30px; + padding: 0; +} + +pre { + background: #EEE; + padding: 7px 30px; + margin: 15px 0px; + line-height: 1.3em; +} + +div.viewcode-block:target { + background: #ffd; +} + +dl pre, blockquote pre, li pre { + margin-left: 0; + padding-left: 30px; +} + +dl dl pre { + margin-left: -90px; + padding-left: 90px; +} + +tt, code { + background-color: #ecf0f3; + color: #222; + /* padding: 1px 2px; */ +} + +tt.xref, code.xref, a tt { + background-color: #FBFBFB; + border-bottom: 1px solid #fff; +} + +a.reference { + text-decoration: none; + border-bottom: 1px dotted #004B6B; +} + +/* Don't put an underline on images */ +a.image-reference, a.image-reference:hover { + border-bottom: none; +} + +a.reference:hover { + border-bottom: 1px solid #6D4100; +} + +a.footnote-reference { + text-decoration: none; + font-size: 0.7em; + vertical-align: top; + border-bottom: 1px dotted #004B6B; +} + +a.footnote-reference:hover { + border-bottom: 1px solid #6D4100; +} + +a:hover tt, a:hover code { + background: #EEE; +} + + +@media screen and (max-width: 870px) { + + div.sphinxsidebar { + display: none; + } + + div.document { + width: 100%; + + } + + div.documentwrapper { + margin-left: 0; + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + } + + div.bodywrapper { + margin-top: 0; + margin-right: 0; + margin-bottom: 0; + margin-left: 0; + } + + ul { + margin-left: 0; + } + + li > ul { + /* Matches the 30px from the "ul, ol" selector above */ + margin-left: 30px; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .bodywrapper { + margin: 0; + } + + .footer { + width: auto; + } + + .github { + display: none; + } + + + +} + + + +@media screen and (max-width: 875px) { + + body { + margin: 0; + padding: 20px 30px; + } + + div.documentwrapper { + float: none; + background: #fff; + } + + div.sphinxsidebar { + display: block; + float: none; + width: 102.5%; + margin: 50px -30px -20px -30px; + padding: 10px 20px; + background: #333; + color: #FFF; + } + + div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, + div.sphinxsidebar h3 a { + color: #fff; + } + + div.sphinxsidebar a { + color: #AAA; + } + + div.sphinxsidebar p.logo { + display: none; + } + + div.document { + width: 100%; + margin: 0; + } + + div.footer { + display: none; + } + + div.bodywrapper { + margin: 0; + } + + div.body { + min-height: 0; + padding: 0; + } + + .rtd_doc_footer { + display: none; + } + + .document { + width: auto; + } + + .footer { + width: auto; + } + + .footer { + width: auto; + } + + .github { + display: none; + } +} + + +/* misc. */ + +.revsys-inline { + display: none!important; +} + +/* Make nested-list/multi-paragraph items look better in Releases changelog + * pages. Without this, docutils' magical list fuckery causes inconsistent + * formatting between different release sub-lists. + */ +div#changelog > div.section > ul > li > p:only-child { + margin-bottom: 0; +} + +/* Hide fugly table cell borders in ..bibliography:: directive output */ +table.docutils.citation, table.docutils.citation td, table.docutils.citation th { + border: none; + /* Below needed in some edge cases; if not applied, bottom shadows appear */ + -moz-box-shadow: none; + -webkit-box-shadow: none; + box-shadow: none; +} \ No newline at end of file diff --git a/docs/build/html/_static/basic.css b/docs/build/html/_static/basic.css new file mode 100644 index 00000000..7ed0e58e --- /dev/null +++ b/docs/build/html/_static/basic.css @@ -0,0 +1,632 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox input[type="text"] { + width: 170px; +} + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, .highlighted { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: relative; + left: 0px; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/docs/build/html/_static/comment-bright.png b/docs/build/html/_static/comment-bright.png new file mode 100644 index 0000000000000000000000000000000000000000..15e27edb12ac25701ac0ac21b97b52bb4e45415e GIT binary patch literal 756 zcmVgfIX78 z$8Pzv({A~p%??+>KickCb#0FM1rYN=mBmQ&Nwp<#JXUhU;{|)}%&s>suq6lXw*~s{ zvHx}3C%<;wE5CH!BR{p5@ml9ws}y)=QN-kL2?#`S5d*6j zk`h<}j1>tD$b?4D^N9w}-k)bxXxFg>+#kme^xx#qg6FI-%iv2U{0h(Y)cs%5a|m%Pn_K3X_bDJ>EH#(Fb73Z zfUt2Q3B>N+ot3qb*DqbTZpFIn4a!#_R-}{?-~Hs=xSS6p&$sZ-k1zDdtqU`Y@`#qL z&zv-~)Q#JCU(dI)Hf;$CEnK=6CK50}q7~wdbI->?E07bJ0R;!GSQTs5Am`#;*WHjvHRvY?&$Lm-vq1a_BzocI^ULXV!lbMd%|^B#fY;XX)n<&R^L z=84u1e_3ziq;Hz-*k5~zwY3*oDKt0;bM@M@@89;@m*4RFgvvM_4;5LB!@OB@^WbVT zjl{t;a8_>od-~P4 m{5|DvB&z#xT;*OnJqG}gk~_7HcNkCr0000W zanA~u9RIXo;n7c96&U)YLgs-FGlx~*_c{Jgvesu1E5(8YEf&5wF=YFPcRe@1=MJmi zag(L*xc2r0(slpcN!vC5CUju;vHJkHc*&70_n2OZsK%O~A=!+YIw z7zLLl7~Z+~RgWOQ=MI6$#0pvpu$Q43 zP@36QAmu6!_9NPM?o<1_!+stoVRRZbW9#SPe!n;#A_6m8f}|xN1;H{`0RoXQ2LM47 zt(g;iZ6|pCb@h2xk&(}S3=EVBUO0e90m2Lp5CB<(SPIaB;n4))3JB87Or#XPOPcum z?<^(g+m9}VNn4Y&B`g8h{t_$+RB1%HKRY6fjtd-<7&EsU;vs0GM(Lmbhi%Gwcfs0FTF}T zL{_M6Go&E0Eg8FuB*(Yn+Z*RVTBE@10eIOb3El^MhO`GabDll(V0&FlJi2k^;q8af zkENdk2}x2)_KVp`5OAwXZM;dG0?M-S)xE1IKDi6BY@5%Or?#aZ9$gcX)dPZ&wA1a< z$rFXHPn|TBf`e?>Are8sKtKrKcjF$i^lp!zkL?C|y^vlHr1HXeVJd;1I~g&Ob-q)& z(fn7s-KI}G{wnKzg_U5G(V%bX6uk zIa+<@>rdmZYd!9Y=C0cuchrbIjuRB_Wq{-RXlic?flu1*_ux}x%(HDH&nT`k^xCeC ziHi1!ChH*sQ6|UqJpTTzX$aw8e(UfcS^f;6yBWd+(1-70zU(rtxtqR%j z-lsH|CKQJXqD{+F7V0OTv8@{~(wp(`oIP^ZykMWgR>&|RsklFMCnOo&Bd{le} zV5F6424Qzl;o2G%oVvmHgRDP9!=rK8fy^!yV8y*4p=??uIRrrr0?>O!(z*g5AvL2!4z0{sq%vhG*Po}`a<6%kTK5TNhtC8}rXNu&h^QH4A&Sk~Autm*s~45(H7+0bi^MraaRVzr05hQ3iK?j` zR#U@^i0WhkIHTg29u~|ypU?sXCQEQgXfObPW;+0YAF;|5XyaMAEM0sQ@4-xCZe=0e z7r$ofiAxn@O5#RodD8rh5D@nKQ;?lcf@tg4o+Wp44aMl~c47azN_(im0N)7OqdPBC zGw;353_o$DqGRDhuhU$Eaj!@m000000NkvXXu0mjfjZ7Z_ literal 0 HcmV?d00001 diff --git a/docs/build/html/_static/custom.css b/docs/build/html/_static/custom.css new file mode 100644 index 00000000..2a924f1d --- /dev/null +++ b/docs/build/html/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/docs/build/html/_static/doctools.js b/docs/build/html/_static/doctools.js new file mode 100644 index 00000000..81634956 --- /dev/null +++ b/docs/build/html/_static/doctools.js @@ -0,0 +1,287 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s == 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node) { + if (node.nodeType == 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { + var span = document.createElement("span"); + span.className = className; + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this); + }); + } + } + return this.each(function() { + highlight(this); + }); +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated == 'undefined') + return string; + return (typeof translated == 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated == 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) == 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this == '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); \ No newline at end of file diff --git a/docs/build/html/_static/down-pressed.png b/docs/build/html/_static/down-pressed.png new file mode 100644 index 0000000000000000000000000000000000000000..5756c8cad8854722893dc70b9eb4bb0400343a39 GIT binary patch literal 222 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`OFdm2Ln;`PZ^+1>KjR?B@S0W7 z%OS_REiHONoJ6{+Ks@6k3590|7k9F+ddB6!zw3#&!aw#S`x}3V3&=A(a#84O-&F7T z^k3tZB;&iR9siw0|F|E|DAL<8r-F4!1H-;1{e*~yAKZN5f0|Ei6yUmR#Is)EM(Po_ zi`qJR6|P<~+)N+kSDgL7AjdIC_!O7Q?eGb+L+qOjm{~LLinM4NHn7U%HcK%uoMYO5 VJ~8zD2B3o(JYD@<);T3K0RV0%P>BEl literal 0 HcmV?d00001 diff --git a/docs/build/html/_static/down.png b/docs/build/html/_static/down.png new file mode 100644 index 0000000000000000000000000000000000000000..1b3bdad2ceffae91cee61b32f3295f9bbe646e48 GIT binary patch literal 202 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!60wlNoGJgf6CVIL!hEy=F?b*7pIY7kW{q%Rg zx!yQ<9v8bmJwa`TQk7YSw}WVQ()mRdQ;TC;* literal 0 HcmV?d00001 diff --git a/docs/build/html/_static/file.png b/docs/build/html/_static/file.png new file mode 100644 index 0000000000000000000000000000000000000000..a858a410e4faa62ce324d814e4b816fff83a6fb3 GIT binary patch literal 286 zcmV+(0pb3MP)s`hMrGg#P~ix$^RISR_I47Y|r1 z_CyJOe}D1){SET-^Amu_i71Lt6eYfZjRyw@I6OQAIXXHDfiX^GbOlHe=Ae4>0m)d(f|Me07*qoM6N<$f}vM^LjV8( literal 0 HcmV?d00001 diff --git a/docs/build/html/_static/jquery-3.1.0.js b/docs/build/html/_static/jquery-3.1.0.js new file mode 100644 index 00000000..f2fc2747 --- /dev/null +++ b/docs/build/html/_static/jquery-3.1.0.js @@ -0,0 +1,10074 @@ +/*eslint-disable no-unused-vars*/ +/*! + * jQuery JavaScript Library v3.1.0 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2016-07-07T21:44Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + + + + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* global Symbol */ +// Defining this global in .eslintrc would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.1.0", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isArray: Array.isArray, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); + }, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.0 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-01-04 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement("fieldset"); + + try { + return !!fn( el ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + // Known :disabled false positives: + // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) + // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Check form elements and option elements for explicit disabling + return "label" in elem && elem.disabled === disabled || + "form" in elem && elem.disabled === disabled || + + // Check non-disabled form elements for fieldset[disabled] ancestors + "form" in elem && elem.disabled === false && ( + // Support: IE6-11+ + // Ancestry is covered for us + elem.isDisabled === disabled || + + // Otherwise, assume any non-