diff --git a/.codeclimate.yml b/.codeclimate.yml index 1f42030a..3e49b5c9 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -8,12 +8,16 @@ engines: enabled: false global-require: enabled: false + guard-for-in: + enabled: false ratings: paths: - "lib/**/*" exclude_paths: -- "tests/" +- "test/" - "old_test/" - "boilerplate/" - "demo/" - "js/" +- "test_app/" +- "docs/" diff --git a/.gitignore b/.gitignore index 002a236f..75be4c5f 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,10 @@ demo/dist/ demo/.embark/development/ demo/config/production/password boilerplate/dist/ +docs/_build +docs/utils/__pycache_ +test_app/dist/ +test_app/.embark/development/ +test_app/config/production/password +test_app/node_modules/ +test_app/chains.json diff --git a/README.md b/README.md index 0bef07fd..ac3cab76 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ - [![Join the chat at https://gitter.im/iurimatias/embark-framework](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iurimatias/embark-framework?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/iurimatias/embark-framework.svg?branch=develop)](https://travis-ci.org/iurimatias/embark-framework) @@ -7,16 +6,33 @@ Status](https://travis-ci.org/iurimatias/embark-framework.svg?branch=develop)](h What is Embark ====== -Embark is a framework that allows you to easily develop and deploy DApps. +Embark is a framework that allows you to easily develop and deploy Decentralized Applications (DApps). + +A Decentralized Application is serverless html5 application that uses one or more decentralized technologies. + +Embark currently integrates with EVM blockchains (Ethereum), Decentralized Storages (IPFS), and Decentralizaed communication platforms (Whisper and Orbit). Swarm is supported for deployment. With Embark you can: + +**Blockchain (Ethereum)** * Automatically deploy contracts and make them available in your JS code. Embark watches for changes, and if you update a contract, Embark will automatically redeploy the contracts (if needed) and the dapp. -* Use any build pipeline or tool you wish, including grunt and meteor. (for 1.x, plugins coming soon for 2.x series) +* Contracts are available in JS with Promises. * Do Test Driven Development with Contracts using Javascript. -* Easily deploy to & use decentralized systems such as IPFS. * Keep track of deployed contracts, deploy only when truly needed. * Manage different chains (e.g testnet, private net, livenet) -* Quickly create advanced DApps using multiple contracts that can interact with decentralized infrastructure for storage and comunication. +* Easily manage complex systems of interdependent contracts. + +**Decentralized Storage (IPFS)** +* Easily Store & Retrieve Data on the DApp through EmbarkJS. Includin uploading and retrieving files. +* Deploy the full application to IPFS or Swarm. + + +**Decentralized Communication (Whisper, Orbit)** +* Easily send/receive messages through channels in P2P through Whisper or Orbit. + +**Web Technologies** +* Integrate with any web technology including React, Foundation, etc.. +* Use any build pipeline or tool you wish, including grunt, gulp and webpack. Table of Contents ====== @@ -28,18 +44,18 @@ 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) * [Deploying to IPFS](#deploying-to-ipfs) -* [LiveReload Plugin](#livereload-plugin) +* [Extending Functionality with Plugins](#plugins) * [Donations](#donations) Installation ====== -Requirements: geth (1.4.4 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. +Requirements: geth (1.5.8 or higher), node (6.9.1 or higher is recommended) and npm +Optional: testrpc (3.0 or higher) if using the simulator or the test functionality. Further: depending on the dapp stack you choose: [IPFS](https://ipfs.io/) ```Bash @@ -58,6 +74,9 @@ Embark's npm package has changed from ```embark-framework``` to ```embark```, th Usage - Demo ====== + +![Embark Demo screenshot](http://i.imgur.com/a9ddSjn.png) + You can easily create a sample working DApp with the following: ```Bash @@ -136,7 +155,7 @@ Solidity/Serpent files in the contracts directory will automatically be deployed Libraries and languages available ====== -Embark can build and deploy contracts coded in Solidity or Serpent. It will make them available on the client side using EmbarkJS and Web3.js. +Embark can build and deploy contracts coded in Solidity. It will make them available on the client side using EmbarkJS and Web3.js. Further documentation for these can be found below: @@ -149,6 +168,7 @@ Embark will automatically take care of deployment for you and set all needed JS ```Javascript # app/contracts/simple_storage.sol +pragma solidity ^0.4.7; contract SimpleStorage { uint public storedData; @@ -169,8 +189,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: @@ -291,6 +311,12 @@ methods in EmbarkJS contracts will be converted to promises. myContract.get().then(function(value) { console.log("value is " + value.toNumber) }); ``` +events: + +```Javascript + myContract.eventName({from: web3.eth.accounts}, 'latest').then(function(event) { console.log(event) }); +``` + **deployment** Client side deployment will be automatically available in Embark for existing contracts: @@ -346,17 +372,33 @@ The current available storage is IPFS. it can be initialized as EmbarkJS.Storage.getUrl(hash); ``` +note: if not using localhost, the cors needs to be set as ```ipfs --json API.HTTPHeaders.Access-Control-Allow-Origin '["your-host-name-port"]``` + EmbarkJS - Communication ====== **initialization** -The current available communication is Whisper. +For 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``` + +then set the provider: + +```Javascript + EmbarkJS.Messages.setProvider('orbit', {server: 'localhost', port: 5001}) +``` **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** @@ -364,15 +406,17 @@ The current available communication is Whisper. 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 ====== @@ -424,9 +468,9 @@ Working with different chains You can specify which environment to deploy to: -```$ embark blockchain production``` +```$ embark blockchain livenet``` -```$ embark run production``` +```$ embark run livenet``` The environment is a specific blockchain configuration that can be managed at config/blockchain.json @@ -439,7 +483,7 @@ The environment is a specific blockchain configuration that can be managed at co "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", "account": { - "password": "config/production/password" + "password": "config/livenet/password" } }, ... @@ -448,7 +492,7 @@ The environment is a specific blockchain configuration that can be managed at co Structuring Application ====== -Embark is quite flexible and you can configure you're own directory structure using ```embark.json``` +Embark is quite flexible and you can configure your own directory structure using ```embark.json``` ```Json # embark.json @@ -456,24 +500,39 @@ Embark is quite flexible and you can configure you're own directory structure us "contracts": ["app/contracts/**"], "app": { "css/app.css": ["app/css/**"], + "images/": ["app/images/**"], "js/app.js": ["embark.js", "app/js/**"], "index.html": "app/index.html" }, "buildDir": "dist/", - "config": "config/" + "config": "config/", + "plugins": {} } ``` -Deploying to IPFS +Deploying to IPFS and Swarm ====== -To deploy a dapp to IPFS, all you need to do is run a local IPFS node and then run ```embark ipfs```. -If you want to deploy to the livenet then after configuring you account on ```config/blockchain.json``` on the ```production``` environment then you can deploy to that chain by specifying the environment ```embark ipfs production```. +To deploy a dapp to IPFS, all you need to do is run a local IPFS node and then run ```embark upload ipfs```. +If you want to deploy to the livenet then after configuring you account on ```config/blockchain.json``` on the ```livenet``` environment then you can deploy to that chain by specifying the environment ```embark ipfs livenet```. -LiveReload Plugin +To deploy a dapp to SWARM, all you need to do is run a local SWARM node and then run ```embark upload swarm```. + +Plugins ====== -Embark works quite well with the LiveReload Plugin +It's possible to extend Embarks functionality with plugins. For example the following is possible: + +* plugin to add support for es6, jsx, coffescript, etc (``embark.registerPipeline``) +* plugin to add standard contracts or a contract framework (``embark.registerContractConfiguration`` and ``embark.addContractFile``) +* plugin to make some contracts available in all environments for use by other contracts or the dapp itself e.g a Token, a DAO, ENS, etc.. (``embark.registerContractConfiguration`` and ``embark.addContractFile``) +* plugin to add a libraries such as react or boostrap (``embark.addFileToPipeline``) +* plugin to specify a particular web3 initialization for special provider uses (``embark.registerClientWeb3Provider``) +* plugin to create a different contract wrapper (``embark.registerContractsGeneration``) +* plugin to add new console commands (``embark.registerConsoleCommand``) +* plugin to add support for another contract language such as viper, LLL, etc (``embark.registerCompiler``) + +For more information on how to develop your own plugin please see the [plugin documentation](http://embark.readthedocs.io/en/latest/plugins.html) Donations ====== diff --git a/boilerplate/.gitignore b/boilerplate/.gitignore index 0b313ff8..77bcafb1 100644 --- a/boilerplate/.gitignore +++ b/boilerplate/.gitignore @@ -2,3 +2,4 @@ node_modules/ dist/ config/production/password +config/livenet/password diff --git a/boilerplate/config/blockchain.json b/boilerplate/config/blockchain.json index 335e6e49..3453a87d 100644 --- a/boilerplate/config/blockchain.json +++ b/boilerplate/config/blockchain.json @@ -1,10 +1,12 @@ { "development": { + "enabled": true, "networkType": "custom", "genesisBlock": "config/development/genesis.json", "datadir": ".embark/development/datadir", "mineWhenNeeded": true, "nodiscover": true, + "maxpeers": 0, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", @@ -13,25 +15,34 @@ } }, "testnet": { + "enabled": true, "networkType": "testnet", - "rpcHost": "localhost", - "rpcPort": 8545 - }, - "livenet": { - "networkType": "livenet", + "light": true, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", "account": { - "password": "config/production/password" + "password": "config/testnet/password" + } + }, + "livenet": { + "enabled": true, + "networkType": "livenet", + "light": true, + "rpcHost": "localhost", + "rpcPort": 8545, + "rpcCorsDomain": "http://localhost:8000", + "account": { + "password": "config/livenet/password" } }, "privatenet": { + "enabled": true, "networkType": "custom", "rpcHost": "localhost", "rpcPort": 8545, "datadir": "yourdatadir", "networkId": "123", - "nodes": [] + "bootnodes": "" } } diff --git a/boilerplate/config/communication.json b/boilerplate/config/communication.json new file mode 100644 index 00000000..07c7851a --- /dev/null +++ b/boilerplate/config/communication.json @@ -0,0 +1,7 @@ +{ + "default": { + "enabled": true, + "provider": "whisper", + "available_providers": ["whisper", "orbit"] + } +} diff --git a/boilerplate/config/production/password b/boilerplate/config/production/password deleted file mode 100644 index 81c2786f..00000000 --- a/boilerplate/config/production/password +++ /dev/null @@ -1 +0,0 @@ -prod_password diff --git a/boilerplate/config/storage.json b/boilerplate/config/storage.json new file mode 100644 index 00000000..f9516470 --- /dev/null +++ b/boilerplate/config/storage.json @@ -0,0 +1,16 @@ +{ + "default": { + "enabled": true, + "ipfs_bin": "ipfs", + "provider": "ipfs", + "available_providers": ["ipfs"], + "host": "localhost", + "port": 5001 + }, + "development": { + "enabled": true, + "provider": "ipfs", + "host": "localhost", + "port": 5001 + } +} diff --git a/boilerplate/config/testnet/password b/boilerplate/config/testnet/password new file mode 100644 index 00000000..414f8490 --- /dev/null +++ b/boilerplate/config/testnet/password @@ -0,0 +1 @@ +test_password diff --git a/boilerplate/config/webserver.json b/boilerplate/config/webserver.json new file mode 100644 index 00000000..c28a3113 --- /dev/null +++ b/boilerplate/config/webserver.json @@ -0,0 +1,5 @@ +{ + "enabled": true, + "host": "localhost", + "port": 8000 +} diff --git a/boilerplate/embark.json b/boilerplate/embark.json index fac6d3ec..5f43498a 100644 --- a/boilerplate/embark.json +++ b/boilerplate/embark.json @@ -6,5 +6,6 @@ "index.html": "app/index.html" }, "buildDir": "dist/", - "config": "config/" + "config": "config/", + "plugins": {} } diff --git a/boilerplate/package.json b/boilerplate/package.json index a315d360..ebd650e9 100644 --- a/boilerplate/package.json +++ b/boilerplate/package.json @@ -1,16 +1,15 @@ { - "name": "app_name", + "name": "%APP_NAME%", "version": "0.0.1", "description": "", - "main": "Gruntfile.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "embark test" }, "author": "", "license": "ISC", "homepage": "", "devDependencies": { - "embark": "^2.1.4", + "embark": "^2.4.0", "mocha": "^2.2.5" } } diff --git a/demo/.gitignore b/demo/.gitignore index 0b313ff8..77bcafb1 100644 --- a/demo/.gitignore +++ b/demo/.gitignore @@ -2,3 +2,4 @@ node_modules/ dist/ config/production/password +config/livenet/password diff --git a/demo/app/contracts/simple_storage.sol b/demo/app/contracts/simple_storage.sol index 53494ce5..13957b2d 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.7; contract SimpleStorage { uint public storedData; diff --git a/demo/app/css/main.css b/demo/app/css/main.css index dc386498..e0043e37 100644 --- a/demo/app/css/main.css +++ b/demo/app/css/main.css @@ -3,3 +3,47 @@ div { margin: 15px; } +.logs { + background-color: black; + font-size: 14px; + color: white; + font-weight: bold; + padding: 10px; + border-radius: 8px; +} + +.tab-content { + border-left: 1px solid #ddd; + border-right: 1px solid #ddd; + border-bottom: 1px solid #ddd; + padding: 10px; + margin: 0px; +} + +.nav-tabs { + margin-bottom: 0; +} + +.status-offline { + vertical-align: middle; + margin-left: 5px; + margin-top: 4px; + width: 12px; + height: 12px; + background: red; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; +} + +.status-online { + vertical-align: middle; + margin-left: 5px; + margin-top: 4px; + width: 12px; + height: 12px; + background: mediumseagreen; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + border-radius: 10px; +} diff --git a/demo/app/images/.gitkeep b/demo/app/images/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/demo/app/index.html b/demo/app/index.html index 809c37e4..9dcde044 100644 --- a/demo/app/index.html +++ b/demo/app/index.html @@ -5,27 +5,101 @@ -

Embark - SimpleStorage Demo

+

Embark - Usage Example

-

1. Set the value in the blockchain

-
- - -

Once you set the value, the transaction will need to be mined and then the value will be updated on the blockchain.

-
+ -

2. Get the current value

-
-
- current value is +
+
+

1. Set the value in the blockchain

+
+ + +

Once you set the value, the transaction will need to be mined and then the value will be updated on the blockchain.

+
+ +

2. Get the current value

+
+
+ current value is +
+ +

Click the button to get the current value. The initial value is 100.

+
+ +

3. Contract Calls

+

Javascript calls being made:

+
+
- -

Click the button to get the current value. The initial value is 100.

-
+
+ +
-

3. Contract Calls

-
-

Javascript call being made:

+

Save text to IPFS

+
+ + +

generated Hash:

+
+ +

Load text from IPFS given an hash

+
+ + +

result:

+
+ +

upload file to ipfs

+
+ + +

generated hash:

+
+ +

Get file or image from ipfs

+
+ + +

file available at:

+

+
+ +

Javascript calls being made:

+
+
EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) +
+
+
+
+ +
+

Listen To channel

+
+ + +
+

messages received:

+

+
+ +

Send Message

+
+ + + +
+ +

Javascript calls being made:

+
+
EmbarkJS.Messages.setProvider('whisper') +
+
+
diff --git a/demo/app/js/_vendor/bootstrap.min.js b/demo/app/js/_vendor/bootstrap.min.js new file mode 100644 index 00000000..e79c0651 --- /dev/null +++ b/demo/app/js/_vendor/bootstrap.min.js @@ -0,0 +1,7 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under the MIT license + */ +if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/demo/app/js/index.js b/demo/app/js/index.js index 53ff009e..cd5863c7 100644 --- a/demo/app/js/index.js +++ b/demo/app/js/index.js @@ -1,22 +1,119 @@ /*globals $, SimpleStorage, document*/ -var addToLog = function(txt) { - $(".logs").append("
" + txt); +var addToLog = function(id, txt) { + $(id + " .logs").append("
" + txt); }; +// =========================== +// Blockchain example +// =========================== $(document).ready(function() { - $("button.set").click(function() { - var value = parseInt($("input.text").val(), 10); + $("#blockchain button.set").click(function() { + var value = parseInt($("#blockchain input.text").val(), 10); SimpleStorage.set(value); - addToLog("SimpleStorage.set(" + value + ")"); + addToLog("#blockchain", "SimpleStorage.set(" + value + ")"); }); - $("button.get").click(function() { + $("#blockchain button.get").click(function() { SimpleStorage.get().then(function(value) { - $(".value").html(value.toNumber()); + $("#blockchain .value").html(value.toNumber()); }); - addToLog("SimpleStorage.get()"); + addToLog("#blockchain", "SimpleStorage.get()"); + }); + +}); + +// =========================== +// Storage (IPFS) example +// =========================== +$(document).ready(function() { + // automatic set if config/storage.json has "enabled": true and "provider": "ipfs" + //EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}); + + $("#storage .error").hide(); + EmbarkJS.Storage.ipfsConnection.ping() + .then(function(){ + $("#status-storage").addClass('status-online'); + $("#storage-controls").show(); + }) + .catch(function(err) { + if(err){ + console.log("IPFS Connection Error => " + err.message); + $("#storage .error").show(); + $("#status-storage").addClass('status-offline'); + $("#storage-controls").hide(); + } + }); + + $("#storage button.setIpfsText").click(function() { + var value = $("#storage input.ipfsText").val(); + EmbarkJS.Storage.saveText(value).then(function(hash) { + $("span.textHash").html(hash); + $("input.textHash").val(hash); + }); + addToLog("#storage", "EmbarkJS.Storage.saveText('" + value + "').then(function(hash) { })"); + }); + + $("#storage button.loadIpfsHash").click(function() { + var value = $("#storage input.textHash").val(); + EmbarkJS.Storage.get(value).then(function(content) { + $("span.ipfsText").html(content); + }); + addToLog("#storage", "EmbarkJS.Storage.get('" + value + "').then(function(content) { })"); + }); + + $("#storage button.uploadFile").click(function() { + var input = $("#storage input[type=file]"); + EmbarkJS.Storage.uploadFile(input).then(function(hash) { + $("span.fileIpfsHash").html(hash); + $("input.fileIpfsHash").val(hash); + }); + addToLog("#storage", "EmbarkJS.Storage.uploadFile($('input[type=file]')).then(function(hash) { })"); + }); + + $("#storage button.loadIpfsFile").click(function() { + var hash = $("#storage input.fileIpfsHash").val(); + var url = EmbarkJS.Storage.getUrl(hash); + var link = '' + url + ''; + $("span.ipfsFileUrl").html(link); + $(".ipfsImage").attr('src', url); + addToLog("#storage", "EmbarkJS.Storage.getUrl('" + hash + "')"); + }); + +}); + +// =========================== +// Communication (Whisper) example +// =========================== +$(document).ready(function() { + + $("#communication .error").hide(); + web3.version.getWhisper(function(err, res) { + if (err) { + $("#communication .error").show(); + $("#communication-controls").hide(); ++ $("#status-communication").addClass('status-offline'); + } else { + EmbarkJS.Messages.setProvider('whisper'); + $("#status-communication").addClass('status-online'); + } + }); + + $("#communication button.listenToChannel").click(function() { + var channel = $("#communication .listen input.channel").val(); + $("#communication #subscribeList").append("
subscribed to " + channel + " now try sending a message"); + EmbarkJS.Messages.listenTo({topic: [channel]}).then(function(message) { + $("#communication #messagesList").append("
channel: " + channel + " message: " + message); + }); + addToLog("#communication", "EmbarkJS.Messages.listenTo({topic: ['" + channel + "']}).then(function(message) {})"); + }); + + $("#communication button.sendMessage").click(function() { + var channel = $("#communication .send input.channel").val(); + var message = $("#communication .send input.message").val(); + EmbarkJS.Messages.sendMessage({topic: channel, data: message}); + addToLog("#communication", "EmbarkJS.Messages.sendMessage({topic: '" + channel + "', data: '" + message + "'})"); }); }); diff --git a/demo/chains.json b/demo/chains.json index 2c63c085..0967ef42 100644 --- a/demo/chains.json +++ b/demo/chains.json @@ -1,2 +1 @@ -{ -} +{} diff --git a/demo/config/blockchain.json b/demo/config/blockchain.json index 335e6e49..0bc6ca2c 100644 --- a/demo/config/blockchain.json +++ b/demo/config/blockchain.json @@ -1,10 +1,12 @@ { "development": { + "enabled": true, "networkType": "custom", "genesisBlock": "config/development/genesis.json", "datadir": ".embark/development/datadir", "mineWhenNeeded": true, "nodiscover": true, + "maxpeers": 0, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", @@ -13,25 +15,35 @@ } }, "testnet": { + "enabled": true, "networkType": "testnet", - "rpcHost": "localhost", - "rpcPort": 8545 - }, - "livenet": { - "networkType": "livenet", + "light": true, "rpcHost": "localhost", "rpcPort": 8545, "rpcCorsDomain": "http://localhost:8000", "account": { - "password": "config/production/password" + "password": "config/testnet/password" + } + }, + "livenet": { + "enabled": true, + "networkType": "livenet", + "light": true, + "rpcHost": "localhost", + "rpcPort": 8545, + "rpcCorsDomain": "http://localhost:8000", + "account": { + "password": "config/livenet/password" } }, "privatenet": { + "enabled": true, "networkType": "custom", "rpcHost": "localhost", "rpcPort": 8545, + "rpcCorsDomain": "http://localhost:8000", "datadir": "yourdatadir", "networkId": "123", - "nodes": [] + "bootnodes": "" } } diff --git a/demo/config/communication.json b/demo/config/communication.json new file mode 100644 index 00000000..07c7851a --- /dev/null +++ b/demo/config/communication.json @@ -0,0 +1,7 @@ +{ + "default": { + "enabled": true, + "provider": "whisper", + "available_providers": ["whisper", "orbit"] + } +} diff --git a/demo/config/storage.json b/demo/config/storage.json new file mode 100644 index 00000000..f9516470 --- /dev/null +++ b/demo/config/storage.json @@ -0,0 +1,16 @@ +{ + "default": { + "enabled": true, + "ipfs_bin": "ipfs", + "provider": "ipfs", + "available_providers": ["ipfs"], + "host": "localhost", + "port": 5001 + }, + "development": { + "enabled": true, + "provider": "ipfs", + "host": "localhost", + "port": 5001 + } +} diff --git a/demo/config/testnet/password b/demo/config/testnet/password new file mode 100644 index 00000000..414f8490 --- /dev/null +++ b/demo/config/testnet/password @@ -0,0 +1 @@ +test_password diff --git a/demo/config/webserver.json b/demo/config/webserver.json new file mode 100644 index 00000000..c28a3113 --- /dev/null +++ b/demo/config/webserver.json @@ -0,0 +1,5 @@ +{ + "enabled": true, + "host": "localhost", + "port": 8000 +} diff --git a/demo/embark.json b/demo/embark.json index fac6d3ec..4fb81d31 100644 --- a/demo/embark.json +++ b/demo/embark.json @@ -2,9 +2,12 @@ "contracts": ["app/contracts/**"], "app": { "css/app.css": ["app/css/**"], - "js/app.js": ["embark.js", "app/js/**"], + "images/": ["app/images/**"], + "js/app.js": ["embark.js", "app/js/_vendor/jquery.min.js", "app/js/_vendor/bootstrap.min.js", "app/js/**"], "index.html": "app/index.html" }, "buildDir": "dist/", - "config": "config/" + "config": "config/", + "plugins": { + } } diff --git a/demo/package.json b/demo/package.json index a315d360..2d381594 100644 --- a/demo/package.json +++ b/demo/package.json @@ -10,7 +10,7 @@ "license": "ISC", "homepage": "", "devDependencies": { - "embark": "^2.1.4", + "embark": "^2.4.0", "mocha": "^2.2.5" } } diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 00000000..3e6108d4 --- /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 = . +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/conf.py b/docs/conf.py new file mode 100644 index 00000000..7af4b190 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,160 @@ +# -*- coding: utf-8 -*- +# +# ENS documentation build configuration file, created by +# sphinx-quickstart on Thu Dec 15 16:45:41 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + +from recommonmark.parser import CommonMarkParser + +source_parsers = { + '.md': CommonMarkParser, +} + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.mathjax'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +source_suffix = ['.rst', '.md'] + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Embark' +copyright = u'2017, Iuri Matias' +author = u'Iuri Matias' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'2.4' +# The full version, including alpha/beta/rc tags. +release = u'2.4.0' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_rtd_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Embarkdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'Embark.tex', u'Embark Documentation', + u'Iuri Matias \\textless{}\\textgreater{}', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'embark', u'Embark Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'Embark', u'Embark Documentation', + author, 'Embark', 'One line description of project.', + 'Miscellaneous'), +] + + + diff --git a/docs/configuring-communication.rst b/docs/configuring-communication.rst new file mode 100644 index 00000000..38bc909e --- /dev/null +++ b/docs/configuring-communication.rst @@ -0,0 +1,22 @@ +Configuring Communication (Whisper, Orbit) +========================== + +Embark will check your prefered communication configuration in the file ``config/communication.json``. This file will contain the prefered configuration for each environment. With ``default`` being the configuration fields that applies to every environment. Each of those can be individually overriden in a per environment basis. + +e.g : + +.. code:: javascript + + { + "default": { + "enabled": true, + "provider": "whisper", + "available_providers": ["whisper", "orbit"] + } + } + +options available: + * ``enabled`` (boolean: true/false) to enable or completly disable communication support + * ``provider`` (string: "wisper" or "orbit") desired provider to automatically connect to on the dapp. e.g in the example above, seting this to ``"whisper"`` will automaticaly add ``EmbarkJS.setProvider('whisper')`` to the generated code + * ``available_providers`` (array: ["whisper", "orbit"]) list of communication platforms to be supported on the dapp. This will affect what's available with the EmbarkJS library on the dapp so if you don't need Orbit for e.g, removing it from this will considerably reduce the file size of the generated JS code. + diff --git a/docs/configuring-storage.rst b/docs/configuring-storage.rst new file mode 100644 index 00000000..592f2295 --- /dev/null +++ b/docs/configuring-storage.rst @@ -0,0 +1,33 @@ +Configuring Storage (IPFS) +========================== + +Embark will check your prefered storage configuration in the file ``config/storage.json``. This file will contain the prefered configuration for each environment. With ``default`` being the configuration fields that applies to every environment. Each of those can be individually overriden in a per environment basis. + +e.g : + +.. code:: javascript + + { + "default": { + "enabled": true, + "ipfs_bin": "ipfs", + "provider": "ipfs", + "available_providers": ["ipfs"], + "host": "localhost", + "port": 5001 + }, + "development": { + "enabled": true, + "provider": "ipfs", + "host": "localhost", + "port": 5001 + } + } + +options available: + * ``enabled`` (boolean: true/false) to enable or completly disable storage support + * ``ipfs_bin`` (string) name or desired path to the ipfs binary + * ``provider`` (string: "ipfs") desired provider to automatically connect to on the dapp. e.g in the example above, seting this to ``"ipfs"`` will automaticaly add ``EmbarkJS.setProvider('ipfs', {server: 'localhost', 5001})`` to the generated code + * ``available_providers`` (array: ["ipfs"]) list of storages to be supported on the dapp. This will affect what's available with the EmbarkJS library on the dapp. + * ``host`` and ``port`` of the ipfs node to connect to. + diff --git a/docs/creating-a-new-dapp.rst b/docs/creating-a-new-dapp.rst new file mode 100644 index 00000000..bd52c029 --- /dev/null +++ b/docs/creating-a-new-dapp.rst @@ -0,0 +1,42 @@ +Creating a new DApp +=================== + +If you want to create a blank new app. + +.. code:: bash + + $ embark new AppName + $ cd AppName + +To run Embark then in one console run: + +.. code:: bash + + $ embark blockchain + +And in another console run: + +.. code:: bash + + $ embark run + +DApp Structure +============== + +.. code:: bash + + app/ + |___ contracts/ #solidity smart contracts + |___ html/ + |___ css/ + |___ js/ + config/ + |___ blockchain.json #rpc and blockchain configuration + |___ contracts.json #ethereum contracts configuration + |___ storage.json #ipfs configuration + |___ communication.json #whisper/orbit configuration + |___ webserver.json #dev webserver configuration + test/ + |___ #contracts tests + +Solidity files in the contracts directory will automatically be deployed with ``embark run``. Changes in any files will automatically be reflected in app, changes to contracts will result in a redeployment and update of their JS Bindings diff --git a/docs/dashboard.rst b/docs/dashboard.rst new file mode 100644 index 00000000..c6b395cd --- /dev/null +++ b/docs/dashboard.rst @@ -0,0 +1,24 @@ +Dashboard +========= + +Embark 2 comes with a terminal dashboard. + +.. figure:: http://i.imgur.com/s4OQZpu.jpg + :alt: Dashboard + + Dashboard + +The dashboard will tell you the state of your contracts, the enviroment +you are using, and what embark is doing at the moment. + +**available services** + +Available Services will display the services available to your dapp in +green, if one of these is down then it will be displayed in red. + +**logs and console** + +There is a console at the bottom which can be used to interact with +contracts or with embark itself. type ``help`` to see a list of +available commands, more commands will be added with each version of +Embark. diff --git a/docs/deploying-to-ipfs.rst b/docs/deploying-to-ipfs.rst new file mode 100644 index 00000000..cb5a20a9 --- /dev/null +++ b/docs/deploying-to-ipfs.rst @@ -0,0 +1,8 @@ +Deploying to IPFS +================= + +To deploy a dapp to IPFS, all you need to do is run a local IPFS node +and then run ``embark upload ipfs``. If you want to deploy to the livenet then +after configuring you account on ``config/blockchain.json`` on the +``livenet`` environment then you can deploy to that chain by +specifying the environment ``embark ipfs livenet``. diff --git a/docs/deploying-to-swarm.rst b/docs/deploying-to-swarm.rst new file mode 100644 index 00000000..aca155d0 --- /dev/null +++ b/docs/deploying-to-swarm.rst @@ -0,0 +1,4 @@ +Deploying to SWARM +================== + +To deploy a dapp to SWARM, all you need to do is run a local SWARM node and then run ``embark upload swarm``. diff --git a/docs/donations.md b/docs/donations.md new file mode 100644 index 00000000..fe9255f3 --- /dev/null +++ b/docs/donations.md @@ -0,0 +1,4 @@ +Donations +====== + +If you like Embark please consider donating to 0x8811FdF0F988f0CD1B7E9DE252ABfA5b18c1cDb1 diff --git a/docs/donations.rst b/docs/donations.rst new file mode 100644 index 00000000..d4daeb63 --- /dev/null +++ b/docs/donations.rst @@ -0,0 +1,5 @@ +Donations +========= + +If you like Embark please consider donating to +0x8811FdF0F988f0CD1B7E9DE252ABfA5b18c1cDb1 diff --git a/docs/embarkjs-communication.rst b/docs/embarkjs-communication.rst new file mode 100644 index 00000000..7e28292b --- /dev/null +++ b/docs/embarkjs-communication.rst @@ -0,0 +1,46 @@ +EmbarkJS - Communication (Whisper, Orbit) +========================================= + +**initialization** + +For Whisper: + +.. code:: javascript + + 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: + +.. code:: javascript + + EmbarkJS.Messages.setProvider('orbit', {server: 'localhost', port: 5001}) + +**listening to messages** + +.. code:: javascript + + EmbarkJS.Messages.listenTo({topic: ["topic1", "topic2"]}).then(function(message) { console.log("received: " + message); }) + +**sending messages** + +you can send plain text + +.. code:: javascript + + EmbarkJS.Messages.sendMessage({topic: "sometopic", data: 'hello world'}) + +or an object + +.. code:: javascript + + 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)`` diff --git a/docs/embarkjs-storage.rst b/docs/embarkjs-storage.rst new file mode 100644 index 00000000..a4641792 --- /dev/null +++ b/docs/embarkjs-storage.rst @@ -0,0 +1,39 @@ +EmbarkJS - Storage (IPFS) +========================= + +**initialization** + +The current available storage is IPFS. it can be initialized as + +.. code:: javascript + + EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) + +**Saving Text** + +.. code:: javascript + + EmbarkJS.Storage.saveText("hello world").then(function(hash) {}); + +**Retrieving Data/Text** + +.. code:: javascript + + EmbarkJS.Storage.get(hash).then(function(content) {}); + +**Uploading a file** + +.. code:: html + + + +.. code:: javascript + + var input = $("input[type=file"]); + EmbarkJS.Storage.uploadFile(input).then(function(hash) {}); + +**Generate URL to file** + +.. code:: javascript + + EmbarkJS.Storage.getUrl(hash); diff --git a/docs/embarkjs.rst b/docs/embarkjs.rst new file mode 100644 index 00000000..50c0e747 --- /dev/null +++ b/docs/embarkjs.rst @@ -0,0 +1,30 @@ +EmbarkJS +======== + +EmbarkJS is a javascript library meant to abstract and facilitate the +development of DApps. + +**promises** + +methods in EmbarkJS contracts will be converted to promises. + +.. code:: javascript + + var myContract = new EmbarkJS.Contract({abi: abiObject, address: "0x123"}); + myContract.get().then(function(value) { console.log("value is " + value.toNumber) }); + +**deployment** + +Client side deployment will be automatically available in Embark for +existing contracts: + +.. code:: javascript + + SimpleStorage.deploy().then(function(anotherSimpleStorage) {}); + +or it can be manually definied as + +.. code:: javascript + + var myContract = new EmbarkJS.Contract({abi: abiObject, code: code}); + myContract.deploy().then(function(anotherMyContractObject) {}); diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..c3550d49 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,40 @@ +.. embark documentation master file, created by + sphinx-quickstart on Tue Jan 10 06:39:27 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! +================================== + +This is a work in progress, feel free to contribute! + +.. toctree:: + :maxdepth: 2 + + installation.rst + usage.rst + dashboard.rst + creating-a-new-dapp.rst + libraries-and-languages-available.rst + using-contracts.rst + configuring-storage.rst + configuring-communication.rst + embarkjs.rst + embarkjs-storage.rst + embarkjs-communication.rst + tests.rst + working-with-different-chains.rst + structuring-application.rst + deploying-to-ipfs.rst + deploying-to-swarm.rst + plugins.rst + using-embark-with-grunt.rst + donations.rst + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/docs/installation.rst b/docs/installation.rst new file mode 100644 index 00000000..ae27adab --- /dev/null +++ b/docs/installation.rst @@ -0,0 +1,24 @@ +Installation +============ + +Requirements: geth (1.5.8 or higher), node (6.9.1 or higher is recommended) and npm +serpent (develop) if using contracts with Serpent, testrpc (3.0 or higher) +if using the simulator or the test functionality. Further: depending on +the dapp stack you choose: `IPFS `__ + +.. code:: bash + + $ npm -g install embark + + # If you plan to use the simulator instead of a real ethereum node. + $ npm -g install ethereumjs-testrpc + +See `Complete Installation +Instructions `__. + +**updating from embark 1** + +Embark's npm package has changed from ``embark-framework`` to +``embark``, this sometimes can create conflicts. To update first +uninstall embark-framework 1 to avoid any conflicts. +``npm uninstall -g embark-framework`` then ``npm install -g embark`` diff --git a/docs/libraries-and-languages-available.rst b/docs/libraries-and-languages-available.rst new file mode 100644 index 00000000..aac3f98b --- /dev/null +++ b/docs/libraries-and-languages-available.rst @@ -0,0 +1,14 @@ +Libraries and languages available +================================= + +Embark can build and deploy contracts coded in Solidity or Serpent. It +will make them available on the client side using EmbarkJS and Web3.js. + +Further documentation for these can be found below: + +- Smart Contracts: + `Solidity `__ and + `Serpent `__ +- Client Side: + `Web3.js `__ + and `EmbarkJS <#embarkjs>`__ diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 00000000..5fb02930 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=embark + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/plugins.rst b/docs/plugins.rst new file mode 100644 index 00000000..99f8d084 --- /dev/null +++ b/docs/plugins.rst @@ -0,0 +1,296 @@ +Extending functionality with plugins +==================================== + +**To add a plugin to embark:** + +1. Add the npm package to package.json + e.g ``npm install embark-babel --save`` +2. Then add the package to ``plugins:`` in embark.json + e.g ``"plugins": { "embark-babel": {} }`` + +**Creating a plugin:** + +1. ``mkdir yourpluginname`` +2. ``cd yourpluginname`` +3. ``npm init`` +4. create and edit ``index.js`` +5. add the following code: + +.. code:: javascript + + module.exports = function(embark) { + } + +The ``embark`` object then provides an api to extend different functionality of embark. + +**Usecases examples** + +* plugin to add support for es6, jsx, coffescript, etc (``embark.registerPipeline``) +* plugin to add standard contracts or a contract framework (``embark.registerContractConfiguration`` and ``embark.addContractFile``) +* plugin to make some contracts available in all environments for use by other contracts or the dapp itself e.g a Token, a DAO, ENS, etc.. (``embark.registerContractConfiguration`` and ``embark.addContractFile``) +* plugin to add a libraries such as react or boostrap (``embark.addFileToPipeline``) +* plugin to specify a particular web3 initialization for special provider uses (``embark.registerClientWeb3Provider``) +* plugin to create a different contract wrapper (``embark.registerContractsGeneration``) +* plugin to add new console commands (``embark.registerConsoleCommand``) +* plugin to add support for another contract language such as viper, LLL, etc (``embark.registerCompiler``) +* plugin that executes certain actions when contracts are deployed (``embark.events.on``) + +**embark.pluginConfig** + +Object containing the config for the plugin specified in embark.json, for e.g with: + +.. code:: json + + "plugins": { + "embark-babel": { "files": ["**/*.js", "!**/jquery.min.js"], "presets": ["es2015", "react"] } + } + +``embark.pluginConfig`` will contain ``{ "files": ["**/*.js", "!**/jquery.min.js"], "presets": ["es2015", "react"] }`` + +**embark.registerPipeline(matchingFiles, callback(options))** + +This call will return the content of the current asset file so the plugin can transform it in some way. Typically this is used to implement pipeline plugins such as Babel, JSX, sass to css, etc.. + +``matchingFiles`` is an array of matching files the plugin should be called for e.g [``**/*.js``, ``!vendor/jquery.js``] matches all javascript files except vendor/jquery.js + +options available: + * targetFile - filename to be generated + * source - content of the file + +expected return: ``string`` + +.. code:: javascript + + var babel = require("babel-core"); + require("babel-preset-react"); + + module.exports = function(embark) { + embark.registerPipeline(["**/*.js", "**/*.jsx"], function(options) { + return babel.transform(options.source, {minified: true, presets: ['react']}).code; + }); + } + +**embark.registerContractConfiguration(contractsConfig)** + +This call is used to specify a configure of one or more contracts in one or +several environments. This is useful for specifying the different configurations +a contract might have depending on the enviroment. For instance in the code +bellow, the ``DGDToken`` contract code will redeployed with the arguments +``100`` in any environment, except for the livenet since it's already deployed +there at a particular address. + +Typically this call is used in combination with ``embark.addContractFile`` + +``contractsConfig`` is an object in the same structure as the one found in the +contracts configuration at ``config/contracts.json``. The users own +configuration will be merged with the one specified in the plugins. + +.. code:: javascript + + module.exports = function(embark) { + embark.registerContractConfiguration({ + "default": { + "contracts": { + "DGDToken": { + "args": [ + 100 + ] + } + } + }, + "livenet": { + "contracts": { + "DGDToken": { + "address": "0xe0b7927c4af23765cb51314a0e0521a9645f0e2a" + } + } + } + }); + } + +**embark.addContractFile(file)** + +Typically this call is used in combination with ``embark.registerContractConfiguration``. If you want to make the contract available but not automatically deployed without the user specifying so you can use ``registerContractConfiguration`` to set the contract config to ``deploy: false``, this is particularly useful for when the user is meant to extend the contract being given (e.g ``contract MyToken is StandardToken``) + +``file`` is the contract file to add to embark, the path should relative to the plugin. + +.. code:: javascript + + module.exports = function(embark) { + embark.addContractFile("./DGDToken.sol"); + } + +**embark.addFileToPipeline(file, options)** + +This call is used to add a file to the pipeline so it's included with the dapp on the client side. + +``file`` is the file to add to the pipeline, the path should relative to the plugin. + +``options`` available: + * skipPipeline - If true it will not apply transformations to the file. For + example if you have a babel plugin to transform es6 code or a minifier plugin, setting this to + true will not apply the plugin on this file. + +.. code:: javascript + + module.exports = function(embark) { + embark.addFileToPipeline("./jquery.js", {skipPipeline: true}); + } + + +**embark.registerClientWeb3Provider(callback(options))** + +This call can be used to override the default web3 object generation in the dapp. it's useful if you want to add a plugin to interact with services like http://infura.io or if you want to use your own web3.js library extension. + +options available: + * rpcHost - configured rpc Host to connect to + * rpcPort - configured rpc Port to connect to + * blockchainConfig - object containing the full blockchain configuration for the current environment + +expected return: ``string`` + +example: + +.. code:: javascript + + module.exports = function(embark) { + embark.registerClientWeb3Provider(function(options) { + return "web3 = new Web3(new Web3.providers.HttpProvider('http://" + options.rpcHost + ":" + options.rpcPort + "');"; + }); + } + + +**embark.registerContractsGeneration(callback(options))** + +By default Embark will use EmbarkJS to declare contracts in the dapp. You can override and use your own client side library. + +options available: + * contracts - Hash of objects containing all the deployed contracts. (key: contractName, value: contract object) + * abiDefinition + * code + * deployedAddress + * gasEstimates + * gas + * gasPrice + * runtimeByteCode + +expected return: ``string`` + +.. code:: javascript + + module.exports = function(embark) { + embark.registerContractsGeneration(function(options) { + for(var className in this.contractsManager.contracts) { + var abi = JSON.stringify(contract.abiDefinition); + + return className + " = " + web3.eth.contract(" + abi + ").at('" + contract.deployedAddress + "');"; + } + }); + } + +**embark.registerConsoleCommand(callback(options))** + +This call is used to extend the console with custom commands. + +expected return: ``string`` (output to print in console) or ``boolean`` (skip command if false) + +.. code:: javascript + + module.exports = function(embark) { + embark.registerConsoleCommand(function(cmd, options) { + if (cmd === "hello") { + return "hello there!"; + } + // continue to embark or next plugin; + return false; + }); + } + +**embark.registerCompiler(extension, callback(contractFiles, doneCallback))** + +expected doneCallback arguments: ``err`` and ``hash`` of compiled contracts + + * Hash of objects containing the compiled contracts. (key: contractName, value: contract object) + + * code - contract bytecode (string) + + * runtimeBytecode - contract runtimeBytecode (string) + + * gasEstimates - gas estimates for constructor and methods (hash) + * e.g ``{"creation":[20131,38200],"external":{"get()":269,"set(uint256)":20163,"storedData()":224},"internal":{}}`` + * functionHashes - object with methods and their corresponding hash identifier (hash) + * e.g ``{"get()":"6d4ce63c","set(uint256)":"60fe47b1","storedData()":"2a1afcd9"}`` + * abiDefinition - contract abi (array of objects) + * e.g ``[{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"}, etc...`` + +below a possible implementation of a solcjs plugin: + +.. code:: javascript + + var solc = require('solc'); + + module.exports = function(embark) { + embark.registerCompiler(".sol", function(contractFiles, cb) { + // prepare input for solc + var input = {}; + for (var i = 0; i < contractFiles.length; i++) { + var filename = contractFiles[i].filename.replace('app/contracts/',''); + input[filename] = contractFiles[i].content.toString(); + } + + // compile files + var output = solc.compile({sources: input}, 1); + + // generate the compileObject expected by embark + var json = output.contracts; + var compiled_object = {}; + for (var className in json) { + var contract = json[className]; + + compiled_object[className] = {}; + compiled_object[className].code = contract.bytecode; + compiled_object[className].runtimeBytecode = contract.runtimeBytecode; + compiled_object[className].gasEstimates = contract.gasEstimates; + compiled_object[className].functionHashes = contract.functionHashes; + compiled_object[className].abiDefinition = JSON.parse(contract.interface); + } + + cb(null, compiled_object); + }); + } + +**embark.logger** + +To print messages to the embark log is it better to use ``embark.logger`` +instead of ``console``. + +e.g ``embark.logger.info("hello")`` + +**embark.events.on(eventName, callback(*args))** + +This call is used to listen and react to events that happen in Embark such as contract deployment + +* eventName - name of event to listen to + * available events: + * "contractsDeployed" - triggered when contracts have been deployed + * "file-add", "file-change", "file-remove", "file-event" - triggered on + a file change, args is (filetype, path) + * "abi", "abi-vanila", "abi-contracts-vanila" - triggered when contracts + have been deployed and returns the generated JS code + * "outputDone" - triggered when dapp is (re)generated + * "firstDeploymentDone" - triggered when the dapp is deployed and generated + for the first time + +.. code:: javascript + + module.exports = function(embark) { + embark.events.on("contractsDeployed", function() { + embark.logger.info("plugin says: your contracts have been deployed"); + }); + embark.events.on("file-changed", function(filetype, path) { + if (type === 'contract') { + embark.logger.info("plugin says: you just changed the contract at " + path); + } + }); + } + diff --git a/docs/structuring-application.rst b/docs/structuring-application.rst new file mode 100644 index 00000000..0d70c5c0 --- /dev/null +++ b/docs/structuring-application.rst @@ -0,0 +1,22 @@ +Structuring Application +======================= + +Embark is quite flexible and you can configure you're own directory +structure using ``embark.json`` + +.. code:: json + + # embark.json + { + "contracts": ["app/contracts/**"], + "app": { + "css/app.css": ["app/css/**"], + "images/": ["app/images/**"], + "js/app.js": ["embark.js", "app/js/**"], + "index.html": "app/index.html" + }, + "buildDir": "dist/", + "config": "config/", + "plugins": {} + } + diff --git a/docs/tests.rst b/docs/tests.rst new file mode 100644 index 00000000..2b6d0801 --- /dev/null +++ b/docs/tests.rst @@ -0,0 +1,48 @@ +Testing Ethereum Contracts +========================== + +You can run specs with ``embark test``, it will run any test files under +``test/``. + +Embark includes a testing lib to fastly run & test your contracts in a +EVM. + +.. code:: javascript + + # test/simple_storage_spec.js + + var assert = require('assert'); + var Embark = require('embark'); + var EmbarkSpec = Embark.initTests(); + var web3 = EmbarkSpec.web3; + + describe("SimpleStorage", function() { + before(function(done) { + var contractsConfig = { + "SimpleStorage": { + args: [100] + } + }; + EmbarkSpec.deployAll(contractsConfig, done); + }); + + it("should set constructor value", function(done) { + SimpleStorage.storedData(function(err, result) { + assert.equal(result.toNumber(), 100); + done(); + }); + }); + + it("set storage value", function(done) { + SimpleStorage.set(150, function() { + SimpleStorage.get(function(err, result) { + assert.equal(result.toNumber(), 150); + done(); + }); + }); + }); + + }); + +Embark uses `Mocha `__ by default, but you can use +any testing framework you want. diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 00000000..63afbdfd --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,44 @@ +Usage +===== + +Usage - Demo +============ + +You can easily create a sample working DApp with the following: + +.. code:: bash + + $ embark demo + $ cd embark_demo + +You can run a REAL ethereum node for development purposes: + +.. code:: bash + + $ embark blockchain + +Alternatively, to use an ethereum rpc simulator simply run: + +.. code:: bash + + $ embark simulator + +By default embark blockchain will mine a minimum amount of ether and +will only mine when new transactions come in. This is quite usefull to +keep a low CPU. The option can be configured at +``config/blockchain.json``. Note that running a real node requires at +least 2GB of free ram, please take this into account if running it in a +VM. + +Then, in another command line: + +.. code:: bash + + $ embark run + +This will automatically deploy the contracts, update their JS bindings +and deploy your DApp to a local server at http://localhost:8000 + +Note that if you update your code it will automatically be re-deployed, +contracts included. There is no need to restart embark, refreshing the +page on the browser will do. diff --git a/docs/using-contracts.rst b/docs/using-contracts.rst new file mode 100644 index 00000000..7c68a287 --- /dev/null +++ b/docs/using-contracts.rst @@ -0,0 +1,138 @@ +Configuring & Using Contracts +=============== + +Embark will automatically take care of deployment for you and set all +needed JS bindings. For example, the contract below: + +.. code:: javascript + + # app/contracts/simple_storage.sol + contract SimpleStorage { + uint public storedData; + + function SimpleStorage(uint initialValue) { + storedData = initialValue; + } + + function set(uint x) { + storedData = x; + } + function get() constant returns (uint retVal) { + return storedData; + } + } + +Will automatically be available in Javascript as: + +.. code:: javascript + + # app/js/index.js + SimpleStorage.set(100); + 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: + +.. code:: json + + # config/contracts.json + { + "development": { + "gas": "auto", + "contracts": { + "SimpleStorage": { + "args": [ + 100 + ] + } + } + } + } + +If you are using multiple contracts, you can pass a reference to another +contract as ``$ContractName``, Embark will automatically replace this +with the correct address for the contract. + +.. code:: json + + # config/contracts.json + { + ... + "development": { + "contracts": { + "SimpleStorage": { + "args": [ + 100, + $MyStorage + ] + }, + "MyStorage": { + "args": [ + "initial string" + ] + }, + "MyMainContract": { + "args": [ + $SimpleStorage + ] + } + } + } + ... + } + +You can now deploy many instances of the same contract. e.g + +.. code:: json + + # config/contracts.json + { + "development": { + "contracts": { + "Currency": { + "deploy": false, + "args": [ + 100 + ] + }, + "Usd": { + "instanceOf": "Currency", + "args": [ + 200 + ] + }, + "MyCoin": { + "instanceOf": "Currency", + "args": [ + 200 + ] + } + } + } + } + ... + +Contracts addresses can be defined, If an address is defined the +contract wouldn't be deployed but its defined address will be used +instead. + +.. code:: json + + # config/contracts.json + { + ... + "development": { + "contracts": { + "UserStorage": { + "address": "0x123456" + }, + "UserManagement": { + "args": [ + "$UserStorage" + ] + } + } + } + ... + } diff --git a/docs/using-embark-with-grunt.rst b/docs/using-embark-with-grunt.rst new file mode 100644 index 00000000..a71fc106 --- /dev/null +++ b/docs/using-embark-with-grunt.rst @@ -0,0 +1,34 @@ +Using Embark with Grunt +==================================== + +**1. Edit embark.json** + +Edit ``embark.json`` to have the line ``"js/app.js": ["embark.js"]``, this will make embark create the file containing the contracts initilization to ``dist/app.js``. + +.. code:: json + + { + "contracts": ["app/contracts/**"], + "app": { + "app.js": ["embark.js"] + }, + "buildDir": "dist/", + "config": "config/", + "plugins": { + } + } + +**2. add the generated file to Grunt config file so it's included with the other assets** + +.. code:: coffee + + module.exports = (grunt) -> + + grunt.initConfig( + files: + js: + src: [ + "dist/app.js" + "app/js/**/*.js" + ] + diff --git a/docs/working-with-different-chains.rst b/docs/working-with-different-chains.rst new file mode 100644 index 00000000..7a90ea13 --- /dev/null +++ b/docs/working-with-different-chains.rst @@ -0,0 +1,26 @@ +Working with different chains +============================= + +You can specify which environment to deploy to: + +``$ embark blockchain livenet`` + +``$ embark run livenet`` + +The environment is a specific blockchain configuration that can be +managed at config/blockchain.json + +.. code:: json + + # config/blockchain.json + ... + "livenet": { + "networkType": "livenet", + "rpcHost": "localhost", + "rpcPort": 8545, + "rpcCorsDomain": "http://localhost:8000", + "account": { + "password": "config/livenet/password" + } + }, + ... diff --git a/js/bluebird.js b/js/bluebird.js deleted file mode 100644 index 0d9834e6..00000000 --- a/js/bluebird.js +++ /dev/null @@ -1,5476 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2015 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -/** - * bluebird build version 3.4.1 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } -}; - -Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); -}; - -Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } -}; - -Async.prototype._reset = function () { - this._isTickUsed = false; -}; - -module.exports = Async; -module.exports.firstLineError = firstLineError; - -},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { -var calledBind = false; -var rejectThis = function(_, e) { - this._reject(e); -}; - -var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); -}; - -var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } -}; - -var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); -}; - -Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; -}; - -Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } -}; - -Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; -}; - -Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); -}; -}; - -},{}],4:[function(_dereq_,module,exports){ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = _dereq_("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; - -},{"./promise":22}],5:[function(_dereq_,module,exports){ -"use strict"; -var cr = Object.create; -if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; -} - -module.exports = function(Promise) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var isIdentifier = util.isIdentifier; - -var getMethodCaller; -var getGetter; -if (!true) { -var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); -}; - -var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); -}; - -var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; -}; - -getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); -}; - -getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); -}; -} - -function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - 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(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); -} -Promise.prototype.call = function (methodName) { - var args = [].slice.call(arguments, 1);; - if (!true) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); -}; - -function namedGetter(obj) { - return obj[this]; -} -function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; -} -Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); -}; -}; - -},{"./util":36}],6:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var async = Promise._async; - -Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise.isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent.isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - child = promise; - promise = parent; - } - } -}; - -Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; -}; - -Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; -}; - -Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; -}; - -Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } -}; - -Promise.prototype._cancel = function() { - if (!this.isCancellable()) return; - - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); -}; - -Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); -}; - -Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; -}; - -Promise.prototype.isCancellable = function() { - return this.isPending() && !this.isCancelled(); -}; - -Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { - if (util.isArray(onCancelCallback)) { - for (var i = 0; i < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } -}; - -Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); -}; - -Promise.prototype._invokeInternalOnCancel = function() { - if (this.isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } -}; - -Promise.prototype._resultCancelled = function() { - this.cancel(); -}; - -}; - -},{"./util":36}],7:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = _dereq_("./util"); -var getKeys = _dereq_("./es5").keys; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; -} - -return catchFilter; -}; - -},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var longStackTraces = false; -var contextStack = []; - -Promise.prototype._promiseCreated = function() {}; -Promise.prototype._pushContext = function() {}; -Promise.prototype._popContext = function() {return null;}; -Promise._peekContext = Promise.prototype._peekContext = function() {}; - -function Context() { - this._trace = new Context.CapturedTrace(peekContext()); -} -Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } -}; - -Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; -}; - -function createContext() { - if (longStackTraces) return new Context(); -} - -function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; -} -Context.CapturedTrace = null; -Context.create = createContext; -Context.deactivateLongStackTraces = function() {}; -Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var 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 = false; - }; - longStackTraces = true; - 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(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; -}; -return Context; -}; - -},{}],9:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = _dereq_("./errors").Warning; -var util = _dereq_("./util"); -var canAttachTrace = util.canAttachTrace; -var unhandledRejectionHandled; -var possiblyUnhandledRejection; -var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; -var stackFramePattern = null; -var formatStack = null; -var indentStackFrames = false; -var printWarning; -var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - -var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - -var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - -var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - -Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); -}; - -Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); -}; - -Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); -}; - -Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; -}; - -Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; -}; - -Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } -}; - -Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; -}; - -Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); -}; - -Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; -}; - -Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; -}; - -Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } -}; - -Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; -}; - -Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); -}; - -Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) - : undefined; -}; - -Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) - : undefined; -}; - -var disableLongStackTraces = function() {}; -Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } -}; - -Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); -}; - -var fireDomEvent = (function() { - try { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, event); - return !util.global.dispatchEvent(domEvent); - }; - } catch (e) {} - return function() { - return false; - }; -})(); - -var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } -})(); - -function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; -} - -var 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 -}; - -var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; -}; - -Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("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 = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } -}; - -function defaultFireEvent() { return false; } - -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) { - ; - ; -}; - -function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - 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(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } -} - -function cancellationOnCancel() { - return this._onCancelField; -} - -function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; -} - -function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; -} - -function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} - -function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } -} -var propagateFromFunction = bindingPropagateFrom; - -function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; -} - -function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); -} - -function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - 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__", true); - } - } -} - -function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var msg = "a promise was created in a " + name + - "handler but was not returned from it"; - promise._warn(msg, true, promiseCreated); - } -} - -function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); -} - -function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - 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"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } -} - -function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); -} - -function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } -} - -function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } -} - -function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; -} - -function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0) { - stack = stack.slice(i); - } - return stack; -} - -function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: cleanStack(stack) - }; -} - -function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } -} - -function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } -} - -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? 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) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); -} - -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; -} - -function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; -} - -var shouldIgnore = function() { return false; }; -var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; -function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } -} - -function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; -} - -function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); -} -util.inherits(CapturedTrace, Error); -Context.CapturedTrace = CapturedTrace; - -CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } -}; - -CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - 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__", true); -}; - -var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - -})([]); - -if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } -} - -var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false -}; - -if (longStackTraces) Promise.longStackTraces(); - -return { - 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){ -"use strict"; -module.exports = function(Promise) { -function returner() { - return this.value; -} -function thrower() { - throw this.reason; -} - -Promise.prototype["return"] = -Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); -}; - -Promise.prototype["throw"] = -Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); -}; - -Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } -}; - -Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } -}; -}; - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseReduce = Promise.reduce; -var PromiseAll = Promise.all; - -function promiseAllThis() { - return PromiseAll(this); -} - -function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); -} - -Promise.prototype.each = function (fn) { - return this.mapSeries(fn) - ._then(promiseAllThis, undefined, undefined, this, undefined); -}; - -Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); -}; - -Promise.each = function (promises, fn) { - return PromiseMapSeries(promises, fn) - ._then(promiseAllThis, undefined, undefined, promises, undefined); -}; - -Promise.mapSeries = PromiseMapSeries; -}; - -},{}],12:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var Objectfreeze = es5.freeze; -var util = _dereq_("./util"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; - -function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; -} - -var _TypeError, _RangeError; -var Warning = subError("Warning", "warning"); -var CancellationError = subError("CancellationError", "cancellation error"); -var TimeoutError = subError("TimeoutError", "timeout error"); -var AggregateError = subError("AggregateError", "aggregate error"); -try { - _TypeError = TypeError; - _RangeError = RangeError; -} catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); -} - -var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - -for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } -} - -es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true -}); -AggregateError.prototype["isOperational"] = true; -var level = 0; -AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; -}; - -function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - -} -inherits(OperationalError, Error); - -var errorTypes = Error["__BluebirdErrorTypes__"]; -if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); -} - -module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning -}; - -},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ -var isES5 = (function(){ - "use strict"; - return this === undefined; -})(); - -if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; -} else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; -} - -},{}],14:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var PromiseMap = Promise.map; - -Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); -}; - -Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); -}; -}; - -},{}],15:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; - -function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; -} - -PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; -}; - -function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; -} - -FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); -}; - -function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; -} - -function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); -} -function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; -} -function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise.isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } -} - -Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); -}; - -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); -}; - -return PassThroughHandlerContext; -}; - -},{"./util":36}],16:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = _dereq_("./errors"); -var TypeError = errors.TypeError; -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -var yieldHandlers = []; - -function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; -} - -function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; -} -util.inherits(PromiseSpawn, Proxyable); - -PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; -}; - -PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } -}; - -PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); -}; - -PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); -}; - -PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } -}; - -PromiseSpawn.prototype.promise = function () { - return this._promise; -}; - -PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); -}; - -PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - this._promiseFulfilled(maybePromise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._promiseRejected(maybePromise._reason()); - } else { - this._promiseCancelled(); - } - } -}; - -Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; -}; - -Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); -}; - -Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; -}; -}; - -},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { -var util = _dereq_("./util"); -var canEvaluate = util.canEvaluate; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var reject; - -if (!true) { -if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.now = 0; \n\ - } \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - promise._pushContext(); \n\ - var callback = this.fn; \n\ - var ret = tryCatch(callback)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", code) - (tryCatch, errorObj, Promise); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; -}} - -Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (!true) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - if (!ret._isFateSealed()) { - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; - -},{"./util":36}],18:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; -var EMPTY_ARRAY = []; - -function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? fn : domain.bind(fn); - this._preservedValues = _filter === INTERNAL - ? new Array(this.length()) - : null; - this._limit = limit; - this._inFlight = 0; - this._queue = limit >= 1 ? [] : EMPTY_ARRAY; - this._init$(undefined, -2); -} -util.inherits(MappingPromiseArray, PromiseArray); - -MappingPromiseArray.prototype._init = function () {}; - -MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; -}; - -MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } -}; - -MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); -}; - -MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; -}; - -function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); -} - -Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); -}; - -Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); -}; - - -}; - -},{"./util":36}],19:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var 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(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; -}; - -Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } -}; -}; - -},{"./util":36}],20:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = _dereq_("./errors"); -var OperationalError = errors.OperationalError; -var es5 = _dereq_("./es5"); - -function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; -} - -var rErrorKey = /^(?:name|message|stack|cause)$/; -function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; -} - -function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; - -},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise) { -var util = _dereq_("./util"); -var async = Promise._async; -var tryCatch = util.tryCatch; -var errorObj = util.errorObj; - -function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} -function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } -} - -Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; -}; -}; - -},{"./util":36}],22:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function() { -var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); -}; -var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); -}; -function Proxyable() {} -var UNDEFINED_BINDING = {}; -var util = _dereq_("./util"); - -var getDomain; -if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; -} else { - getDomain = function() { - return null; - }; -} -util.notEnumerableProp(Promise, "_getDomain", getDomain); - -var es5 = _dereq_("./es5"); -var Async = _dereq_("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = _dereq_("./errors"); -var TypeError = Promise.TypeError = errors.TypeError; -Promise.RangeError = errors.RangeError; -var CancellationError = Promise.CancellationError = errors.CancellationError; -Promise.TimeoutError = errors.TimeoutError; -Promise.OperationalError = errors.OperationalError; -Promise.RejectionError = errors.OperationalError; -Promise.AggregateError = errors.AggregateError; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {}; -var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); -var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = _dereq_("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - if (self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -} - -function Promise(executor) { - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - if (executor !== INTERNAL) { - check(this, executor); - this._resolveFromExecutor(executor); - } - this._promiseCreated(); - this._fireEvent("promiseCreated", this); -} - -Promise.prototype.toString = function () { - return "[object Promise]"; -}; - -Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("expecting an object but got " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); -}; - -Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); -}; - -Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); -}; - -Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); -}; - -Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); -}; - -Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; -}; - -Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return 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 - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.all = function (promises) { - return new PromiseArray(promises).promise(); -}; - -Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; -}; - -Promise.resolve = Promise.fulfilled = Promise.cast; - -Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; -}; - -Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - 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 = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && domain.bind(handler)), - promise: promise, - receiver: receiver, - value: value - }); - } else { - target._addCallbacks(didFulfill, didReject, promise, receiver, domain); - } - - return promise; -}; - -Promise.prototype._length = function () { - return this._bitField & 65535; -}; - -Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; -}; - -Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; -}; - -Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); -}; - -Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); -}; - -Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); -}; - -Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); -}; - -Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; -}; - -Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; -}; - -Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); -}; - -Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); -}; - -Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; -}; - -Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; -}; - -Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; -}; - -Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; -}; - -Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; -}; - -Promise.prototype._boundValue = function() {}; - -Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); -}; - -Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) 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 >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : domain.bind(fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : domain.bind(reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : domain.bind(fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : domain.bind(reject); - } - } - this._setLength(index + 1); - return index; -}; - -Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); -}; - -Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } -}; - -Promise.prototype._rejectCallback = -function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); -}; - -Promise.prototype._resolveFromExecutor = function (executor) { - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } -}; - -Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise -) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } -}; - -Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; -}; - -Promise.prototype._followee = function() { - return this._rejectionHandler0; -}; - -Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; -}; - -Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } -}; - -Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } -}; - -Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); -}; - -Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); -}; - -Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; -}; - -Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } -}; - -Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } -}; - -Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } -}; - -Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } -}; - -Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - 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; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } -}; - -function deferResolve(v) {this.promise._resolveCallback(v);} -function deferReject(v) {this.promise._rejectCallback(v, false);} - -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, debug); -Promise.Promise = Promise; -Promise.version = "3.4.0"; -_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); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return 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){ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = _dereq_("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - } -} - -function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); -} -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; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - 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; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); -}; - -PromiseArray.prototype._isResolved = function () { - return this._values === null; -}; - -PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); -}; - -PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise.isCancellable()) return; - this._values = null; - this._promise._cancel(); -}; - -PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); -}; - -PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; -}; - -PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; -}; - -PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } -}; - -PromiseArray.prototype.shouldCopyValues = function () { - return true; -}; - -PromiseArray.prototype.getActualLength = function (len) { - return len; -}; - -return PromiseArray; -}; - -},{"./util":36}],24:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = _dereq_("./util"); -var nodebackForPromise = _dereq_("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = _dereq_("./errors").TypeError; -var defaultSuffix = "Async"; -var defaultPromisified = {__isPromisified__: true}; -var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" -]; -var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - -var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; -}; - -function propsFilter(key) { - return !noCopyPropsPattern.test(key); -} - -function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } -} - -function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; -} -function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } -} - -function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; -} - -var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); -}; - -var makeNodePromisifiedEval; -if (!true) { -var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; -}; - -var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); -}; - -var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); -}; - -var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; -}; - -makeNodePromisifiedEval = -function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); -}; -} - -function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; -} - -var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - -function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; -} - -function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); -} - -Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; -}; - -Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); -}; -}; - - -},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); -var isObject = util.isObject; -var es5 = _dereq_("./es5"); -var Es6Map; -if (typeof Map === "function") Es6Map = Map; - -var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; -})(); - -var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; -}; - -function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, -3); -} -util.inherits(PropertiesPromiseArray, PromiseArray); - -PropertiesPromiseArray.prototype._init = function () {}; - -PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; -}; - -PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; -}; - -function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; -} - -Promise.prototype.props = function () { - return props(this); -}; - -Promise.props = function (promises) { - return props(promises); -}; -}; - -},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ -"use strict"; -function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } -} - -function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; -} - -Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; -}; - -Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; -}; - -Queue.prototype._unshiftOne = function(value) { - var capacity = this._capacity; - this._checkCapacity(this.length() + 1); - var front = this._front; - var i = (((( front - 1 ) & - ( capacity - 1) ) ^ capacity ) - capacity ); - this[i] = value; - this._front = i; - this._length = this.length() + 1; -}; - -Queue.prototype.unshift = function(fn, receiver, arg) { - this._unshiftOne(arg); - this._unshiftOne(receiver); - this._unshiftOne(fn); -}; - -Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; -}; - -Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; -}; - -Queue.prototype.length = function () { - return this._length; -}; - -Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } -}; - -Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); -}; - -module.exports = Queue; - -},{}],27:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = _dereq_("./util"); - -var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); -}; - -function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; -} - -Promise.race = function (promises) { - return race(promises, undefined); -}; - -Promise.prototype.race = function () { - return race(this, undefined); -}; - -}; - -},{"./util":36}],28:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = _dereq_("./util"); -var tryCatch = util.tryCatch; - -function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : domain.bind(fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - this._eachValues = _each === INTERNAL ? [] : undefined; - this._promise._captureStackTrace(); - this._init$(undefined, -5); -} -util.inherits(ReductionPromiseArray, PromiseArray); - -ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && accum !== INTERNAL) { - this._eachValues.push(accum); - } -}; - -ReductionPromiseArray.prototype._eachComplete = function(value) { - this._eachValues.push(value); - return this._eachValues; -}; - -ReductionPromiseArray.prototype._init = function() {}; - -ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); -}; - -ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; -}; - -ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; -}; - -ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } -}; - -ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); -}; - -Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); -}; - -Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); -}; - -function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } -} - -function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); -} - -function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } -} - -function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; -} -}; - -},{"./util":36}],29:[function(_dereq_,module,exports){ -"use strict"; -var util = _dereq_("./util"); -var schedule; -var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); -}; -var NativePromise = util.getNativePromise(); -if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; -} else if (typeof NativePromise === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; -} else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - window.navigator.standalone)) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); -} else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; -} else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; -} else { - schedule = noAsyncScheduler; -} -module.exports = schedule; - -},{"./util":36}],30:[function(_dereq_,module,exports){ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = _dereq_("./util"); - -function SettledPromiseArray(values) { - this.constructor$(values); -} -util.inherits(SettledPromiseArray, PromiseArray); - -SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; -}; - -SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); -}; -SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); -}; - -Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); -}; - -Promise.prototype.settle = function () { - return Promise.settle(this); -}; -}; - -},{"./util":36}],31:[function(_dereq_,module,exports){ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = _dereq_("./util"); -var RangeError = _dereq_("./errors").RangeError; -var AggregateError = _dereq_("./errors").AggregateError; -var isArray = util.isArray; -var CANCELLATION = {}; - - -function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; -} -util.inherits(SomePromiseArray, PromiseArray); - -SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } -}; - -SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); -}; - -SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; -}; - -SomePromiseArray.prototype.howMany = function () { - return this._howMany; -}; - -SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; -}; - -SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - -}; -SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); -}; - -SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; -}; - -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)); -}; - -function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; -} - -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){ -"use strict"; -module.exports = function(Promise) { -function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } -} - -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\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var reason = PromiseInspection.prototype.error = -PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); -}; - -var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; -}; - -var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; -}; - -var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; -}; - -var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; -}; - -PromiseInspection.prototype.isCancelled = -Promise.prototype._isCancelled = function() { - return (this._bitField & 65536) === 65536; -}; - -Promise.prototype.isCancelled = function() { - return this._target()._isCancelled(); -}; - -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(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); -}; - -Promise.prototype._value = function() { - return this._settledValue(); -}; - -Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); -}; - -Promise.PromiseInspection = PromiseInspection; -}; - -},{}],33:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = _dereq_("./util"); -var errorObj = util.errorObj; -var isObject = util.isObject; - -function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; -} - -function doGetThen(obj) { - return obj.then; -} - -function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} - -var hasProp = {}.hasOwnProperty; -function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } -} - -function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; -} - -return tryConvertToPromise; -}; - -},{"./util":36}],34:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = _dereq_("./util"); -var TimeoutError = Promise.TimeoutError; - -function HandleWrapper(handle) { - this.handle = handle; -} - -HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); -}; - -var afterValue = function(value) { return delay(+this).thenReturn(value); }; -var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - } - ret._setAsyncGuaranteed(); - return ret; -}; - -Promise.prototype.delay = function (ms) { - return delay(ms, this); -}; - -var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } -}; - -function successClear(value) { - clearTimeout(this.handle); - return value; -} - -function failureClear(reason) { - clearTimeout(this.handle); - throw reason; -} - -Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; -}; - -}; - -},{"./util":36}],35:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - 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(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - -}; - -},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ -"use strict"; -var es5 = _dereq_("./es5"); -var canEvaluate = typeof navigator == "undefined"; - -var errorObj = {e: {}}; -var tryCatchTarget; -var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - -function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } -} -function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; -} - -var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; -}; - - -function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - -} - -function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; -} - -function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); -} - -function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; -} - -function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } -} - -function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; -} - -function thrower(r) { - throw r; -} - -var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - -})(); - -var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; -function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } -} - -function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); -} - -var rident = /^[a-z$_][a-z$_0-9]*$/i; -function isIdentifier(str) { - return rident.test(str); -} - -function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; -} - -function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } -} - -function isError(obj) { - return obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"; -} - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} -} - -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); -} - -function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); -} - -var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } -})(); - -function classString(obj) { - return {}.toString.call(obj); -} - -function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } -} - -var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; -}; - -if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; -} - -var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - -function env(key, def) { - return isNode ? process.env[key] : def; -} - -function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } -} - -var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - env: env, - global: globalObject, - getNativePromise: getNativePromise -}; -ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); -})(); - -if (ret.isNode) ret.toFastProperties(process); - -try {throw new Error(); } catch (e) {ret.lastLineError = e;} -module.exports = ret; - -},{"./es5":13}]},{},[4])(4) -}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } \ No newline at end of file diff --git a/js/build/embark.bundle.js b/js/build/embark.bundle.js index 321bfd24..eed9d3d4 100644 --- a/js/build/embark.bundle.js +++ b/js/build/embark.bundle.js @@ -43,9 +43,9 @@ var EmbarkJS = /************************************************************************/ /******/ ([ /* 0 */ -/***/ function(module, exports, __webpack_require__) { +/***/ function(module, exports) { - var Promise = __webpack_require__(1); + /*jshint esversion: 6 */ //var Ipfs = require('./ipfs.js'); var EmbarkJS = { @@ -57,7 +57,7 @@ var EmbarkJS = this.abi = options.abi; this.address = options.address; - this.code = options.code; + this.code = '0x' + options.code; this.web3 = options.web3 || web3; var ContractClass = this.web3.eth.contract(this.abi); @@ -106,40 +106,73 @@ var EmbarkJS = }; return true; } else if (typeof self._originalContractObject[p] === 'function') { - self[p] = Promise.promisify(self._originalContractObject[p]); + self[p] = function(_args) { + var args = Array.prototype.slice.call(arguments); + var fn = self._originalContractObject[p]; + var props = self.abi.find((x) => x.name == p); + + var promise = new Promise(function(resolve, reject) { + args.push(function(err, transaction) { + promise.tx = transaction; + if (err) { + return reject(err); + } + + var getConfirmation = function() { + self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) { + if (err) { + return reject(err); + } + + if (receipt !== null) { + return resolve(receipt); + } + + setTimeout(getConfirmation, 1000); + }); + }; + + if (typeof(transaction) !== "string" || props.constant) { + resolve(transaction); + } else { + getConfirmation(); + } + }); + + fn.apply(fn, args); + }); + + return promise; + }; return true; } return false; }); }; - EmbarkJS.Contract.prototype.deploy = function(args) { + EmbarkJS.Contract.prototype.deploy = function(args, _options) { var self = this; var contractParams; + var options = _options || {}; contractParams = args || []; contractParams.push({ from: this.web3.eth.accounts[0], data: this.code, - gas: 500000, - gasPrice: 10000000000000 + gas: options.gas || 800000 }); var contractObject = this.web3.eth.contract(this.abi); var promise = new Promise(function(resolve, reject) { contractParams.push(function(err, transaction) { - console.log("callback"); if (err) { - console.log("error"); reject(err); } else if (transaction.address !== undefined) { - console.log("address contract: " + transaction.address); resolve(new EmbarkJS.Contract({abi: self.abi, code: self.code, address: transaction.address})); } }); - console.log(contractParams); // returns promise // deploys contract @@ -156,13 +189,14 @@ var EmbarkJS = EmbarkJS.Storage = { }; - // EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) - //{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 +204,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 +228,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 +255,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) { @@ -233,20 +277,45 @@ var EmbarkJS = EmbarkJS.Messages = { }; - EmbarkJS.Messages.setProvider = function(provider) { + EmbarkJS.Messages.setProvider = function(provider, options) { + var self = this; + var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + if (typeof variable === 'undefined') { + if (options === undefined) { + web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); + } else { + web3 = new Web3(new Web3.providers.HttpProvider("http://" + options.server + ':' + options.port)); + } + } + web3.version.getWhisper(function(err, res) { + if (err) { + console.log("whisper not available"); + } else { + self.currentMessages.identity = web3.shh.newIdentity(); + } + }); + } 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 = { @@ -255,9 +324,10 @@ 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; + var _topics; if (topics === undefined) { throw new Error("missing option: topic"); @@ -269,42 +339,41 @@ 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 }; - return web3.shh.post(message); + return web3.shh.post(message, function() {}); }; EmbarkJS.Messages.Whisper.listenTo = function(options) { var topics = options.topic || options.topics; + var _topics = []; if (typeof topics === 'string') { - topics = [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 @@ -322,5805 +391,107 @@ var EmbarkJS = return err; }; + messageEvents.prototype.stop = function() { + this.filter.stopWatching(); + }; + var promise = new messageEvents(); 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, + data: payload, + from: result.from, + time: (new Date(result.sent * 1000)) + }; + promise.cb(payload, data, result); } }); + promise.filter = filter; + + 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"); + } + + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + 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; + + if (typeof topics === 'string') { + topics = topics; + } else { + topics = topics.join(','); + } + + this.orbit.join(topics); + + 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', (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: channel, + data: post.content, + from: post.meta.from.name, + time: (new Date(post.meta.ts)) + }; + promise.cb(post.content, data, post); + }); + }); + return promise; }; module.exports = EmbarkJS; -/***/ }, -/* 1 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2015 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - /** - * bluebird build version 3.4.6 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each - */ - !function(e){if(true)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { - var fn = queue.shift(); - if (typeof fn !== "function") { - fn._settlePromises(); - continue; - } - var receiver = queue.shift(); - var arg = queue.shift(); - fn.call(receiver, arg); - } - }; - - Async.prototype._drainQueues = function () { - this._drainQueue(this._normalQueue); - this._reset(); - this._haveDrainedQueues = true; - this._drainQueue(this._lateQueue); - }; - - Async.prototype._queueTick = function () { - if (!this._isTickUsed) { - this._isTickUsed = true; - this._schedule(this.drainQueues); - } - }; - - Async.prototype._reset = function () { - this._isTickUsed = false; - }; - - module.exports = Async; - module.exports.firstLineError = firstLineError; - - },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { - var calledBind = false; - var rejectThis = function(_, e) { - this._reject(e); - }; - - var targetRejected = function(e, context) { - context.promiseRejectionQueued = true; - context.bindingPromise._then(rejectThis, rejectThis, null, this, e); - }; - - var bindingResolved = function(thisArg, context) { - if (((this._bitField & 50397184) === 0)) { - this._resolveCallback(context.target); - } - }; - - var bindingRejected = function(e, context) { - if (!context.promiseRejectionQueued) this._reject(e); - }; - - Promise.prototype.bind = function (thisArg) { - if (!calledBind) { - calledBind = true; - Promise.prototype._propagateFrom = debug.propagateFromFunction(); - Promise.prototype._boundValue = debug.boundValueFunction(); - } - var maybePromise = tryConvertToPromise(thisArg); - var ret = new Promise(INTERNAL); - ret._propagateFrom(this, 1); - var target = this._target(); - ret._setBoundTo(maybePromise); - if (maybePromise instanceof Promise) { - var context = { - promiseRejectionQueued: false, - promise: ret, - target: target, - bindingPromise: maybePromise - }; - target._then(INTERNAL, targetRejected, undefined, ret, context); - maybePromise._then( - bindingResolved, bindingRejected, undefined, ret, context); - ret._setOnCancel(maybePromise); - } else { - ret._resolveCallback(target); - } - return ret; - }; - - Promise.prototype._setBoundTo = function (obj) { - if (obj !== undefined) { - this._bitField = this._bitField | 2097152; - this._boundTo = obj; - } else { - this._bitField = this._bitField & (~2097152); - } - }; - - Promise.prototype._isBound = function () { - return (this._bitField & 2097152) === 2097152; - }; - - Promise.bind = function (thisArg, value) { - return Promise.resolve(value).bind(thisArg); - }; - }; - - },{}],4:[function(_dereq_,module,exports){ - "use strict"; - var old; - if (typeof Promise !== "undefined") old = Promise; - function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; - } - var bluebird = _dereq_("./promise")(); - bluebird.noConflict = noConflict; - module.exports = bluebird; - - },{"./promise":22}],5:[function(_dereq_,module,exports){ - "use strict"; - var cr = Object.create; - if (cr) { - var callerCache = cr(null); - var getterCache = cr(null); - callerCache[" size"] = getterCache[" size"] = 0; - } - - module.exports = function(Promise) { - var util = _dereq_("./util"); - var canEvaluate = util.canEvaluate; - var isIdentifier = util.isIdentifier; - - var getMethodCaller; - var getGetter; - if (false) { - var makeMethodCaller = function (methodName) { - return new Function("ensureMethod", " \n\ - return function(obj) { \n\ - 'use strict' \n\ - var len = this.length; \n\ - ensureMethod(obj, 'methodName'); \n\ - switch(len) { \n\ - case 1: return obj.methodName(this[0]); \n\ - case 2: return obj.methodName(this[0], this[1]); \n\ - case 3: return obj.methodName(this[0], this[1], this[2]); \n\ - case 0: return obj.methodName(); \n\ - default: \n\ - return obj.methodName.apply(obj, this); \n\ - } \n\ - }; \n\ - ".replace(/methodName/g, methodName))(ensureMethod); - }; - - var makeGetter = function (propertyName) { - return new Function("obj", " \n\ - 'use strict'; \n\ - return obj.propertyName; \n\ - ".replace("propertyName", propertyName)); - }; - - var getCompiled = function(name, compiler, cache) { - var ret = cache[name]; - if (typeof ret !== "function") { - if (!isIdentifier(name)) { - return null; - } - ret = compiler(name); - cache[name] = ret; - cache[" size"]++; - if (cache[" size"] > 512) { - var keys = Object.keys(cache); - for (var i = 0; i < 256; ++i) delete cache[keys[i]]; - cache[" size"] = keys.length - 256; - } - } - return ret; - }; - - getMethodCaller = function(name) { - return getCompiled(name, makeMethodCaller, callerCache); - }; - - getGetter = function(name) { - return getCompiled(name, makeGetter, getterCache); - }; - } - - function ensureMethod(obj, methodName) { - var fn; - if (obj != null) fn = obj[methodName]; - if (typeof fn !== "function") { - 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(); - var fn = ensureMethod(obj, methodName); - return fn.apply(obj, this); - } - Promise.prototype.call = function (methodName) { - var args = [].slice.call(arguments, 1);; - if (false) { - if (canEvaluate) { - var maybeCaller = getMethodCaller(methodName); - if (maybeCaller !== null) { - return this._then( - maybeCaller, undefined, undefined, args, undefined); - } - } - } - args.push(methodName); - return this._then(caller, undefined, undefined, args, undefined); - }; - - function namedGetter(obj) { - return obj[this]; - } - function indexedGetter(obj) { - var index = +this; - if (index < 0) index = Math.max(0, index + obj.length); - return obj[index]; - } - Promise.prototype.get = function (propertyName) { - var isIndex = (typeof propertyName === "number"); - var getter; - if (!isIndex) { - if (canEvaluate) { - var maybeGetter = getGetter(propertyName); - getter = maybeGetter !== null ? maybeGetter : namedGetter; - } else { - getter = namedGetter; - } - } else { - getter = indexedGetter; - } - return this._then(getter, undefined, undefined, propertyName, undefined); - }; - }; - - },{"./util":36}],6:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, PromiseArray, apiRejection, debug) { - var util = _dereq_("./util"); - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var async = Promise._async; - - Promise.prototype["break"] = Promise.prototype.cancel = function() { - if (!debug.cancellation()) return this._warn("cancellation is disabled"); - - var promise = this; - var child = promise; - while (promise._isCancellable()) { - if (!promise._cancelBy(child)) { - if (child._isFollowing()) { - child._followee().cancel(); - } else { - child._cancelBranched(); - } - break; - } - - var parent = promise._cancellationParent; - if (parent == null || !parent._isCancellable()) { - if (promise._isFollowing()) { - promise._followee().cancel(); - } else { - promise._cancelBranched(); - } - break; - } else { - if (promise._isFollowing()) promise._followee().cancel(); - promise._setWillBeCancelled(); - child = promise; - promise = parent; - } - } - }; - - Promise.prototype._branchHasCancelled = function() { - this._branchesRemainingToCancel--; - }; - - Promise.prototype._enoughBranchesHaveCancelled = function() { - return this._branchesRemainingToCancel === undefined || - this._branchesRemainingToCancel <= 0; - }; - - Promise.prototype._cancelBy = function(canceller) { - if (canceller === this) { - this._branchesRemainingToCancel = 0; - this._invokeOnCancel(); - return true; - } else { - this._branchHasCancelled(); - if (this._enoughBranchesHaveCancelled()) { - this._invokeOnCancel(); - return true; - } - } - return false; - }; - - Promise.prototype._cancelBranched = function() { - if (this._enoughBranchesHaveCancelled()) { - this._cancel(); - } - }; - - Promise.prototype._cancel = function() { - if (!this._isCancellable()) return; - this._setCancelled(); - async.invoke(this._cancelPromises, this, undefined); - }; - - Promise.prototype._cancelPromises = function() { - if (this._length() > 0) this._settlePromises(); - }; - - Promise.prototype._unsetOnCancel = function() { - this._onCancelField = undefined; - }; - - 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 < onCancelCallback.length; ++i) { - this._doInvokeOnCancel(onCancelCallback[i], internalOnly); - } - } else if (onCancelCallback !== undefined) { - if (typeof onCancelCallback === "function") { - if (!internalOnly) { - var e = tryCatch(onCancelCallback).call(this._boundValue()); - if (e === errorObj) { - this._attachExtraTrace(e.e); - async.throwLater(e.e); - } - } - } else { - onCancelCallback._resultCancelled(this); - } - } - }; - - Promise.prototype._invokeOnCancel = function() { - var onCancelCallback = this._onCancel(); - this._unsetOnCancel(); - async.invoke(this._doInvokeOnCancel, this, onCancelCallback); - }; - - Promise.prototype._invokeInternalOnCancel = function() { - if (this._isCancellable()) { - this._doInvokeOnCancel(this._onCancel(), true); - this._unsetOnCancel(); - } - }; - - Promise.prototype._resultCancelled = function() { - this.cancel(); - }; - - }; - - },{"./util":36}],7:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(NEXT_FILTER) { - var util = _dereq_("./util"); - var getKeys = _dereq_("./es5").keys; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - - function catchFilter(instances, cb, promise) { - return function(e) { - var boundTo = promise._boundValue(); - predicateLoop: for (var i = 0; i < instances.length; ++i) { - var item = instances[i]; - - if (item === Error || - (item != null && item.prototype instanceof Error)) { - if (e instanceof item) { - return tryCatch(cb).call(boundTo, e); - } - } else if (typeof item === "function") { - var matchesPredicate = tryCatch(item).call(boundTo, e); - if (matchesPredicate === errorObj) { - return matchesPredicate; - } else if (matchesPredicate) { - return tryCatch(cb).call(boundTo, e); - } - } else if (util.isObject(e)) { - var keys = getKeys(item); - for (var j = 0; j < keys.length; ++j) { - var key = keys[j]; - if (item[key] != e[key]) { - continue predicateLoop; - } - } - return tryCatch(cb).call(boundTo, e); - } - } - return NEXT_FILTER; - }; - } - - return catchFilter; - }; - - },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise) { - var longStackTraces = false; - var contextStack = []; - - Promise.prototype._promiseCreated = function() {}; - Promise.prototype._pushContext = function() {}; - Promise.prototype._popContext = function() {return null;}; - Promise._peekContext = Promise.prototype._peekContext = function() {}; - - function Context() { - this._trace = new Context.CapturedTrace(peekContext()); - } - Context.prototype._pushContext = function () { - if (this._trace !== undefined) { - this._trace._promiseCreated = null; - contextStack.push(this._trace); - } - }; - - Context.prototype._popContext = function () { - if (this._trace !== undefined) { - var trace = contextStack.pop(); - var ret = trace._promiseCreated; - trace._promiseCreated = null; - return ret; - } - return null; - }; - - function createContext() { - if (longStackTraces) return new Context(); - } - - function peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return undefined; - } - Context.CapturedTrace = null; - Context.create = createContext; - Context.deactivateLongStackTraces = function() {}; - Context.activateLongStackTraces = function() { - var Promise_pushContext = Promise.prototype._pushContext; - var Promise_popContext = Promise.prototype._popContext; - var Promise_PeekContext = Promise._peekContext; - var Promise_peekContext = Promise.prototype._peekContext; - var 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 = false; - }; - longStackTraces = true; - 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(); - if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; - }; - }; - return Context; - }; - - },{}],9:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, Context) { - var getDomain = Promise._getDomain; - var async = Promise._async; - var Warning = _dereq_("./errors").Warning; - var util = _dereq_("./util"); - var canAttachTrace = util.canAttachTrace; - var unhandledRejectionHandled; - var possiblyUnhandledRejection; - var bluebirdFramePattern = - /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; - var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; - var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; - var stackFramePattern = null; - var formatStack = null; - var indentStackFrames = false; - var printWarning; - var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && - (true || - util.env("BLUEBIRD_DEBUG") || - util.env("NODE_ENV") === "development")); - - var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && - (debugging || util.env("BLUEBIRD_WARNINGS"))); - - var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && - (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); - - var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && - (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); - - Promise.prototype.suppressUnhandledRejections = function() { - var target = this._target(); - target._bitField = ((target._bitField & (~1048576)) | - 524288); - }; - - Promise.prototype._ensurePossibleRejectionHandled = function () { - if ((this._bitField & 524288) !== 0) return; - this._setRejectionIsUnhandled(); - async.invokeLater(this._notifyUnhandledRejection, this, undefined); - }; - - Promise.prototype._notifyUnhandledRejectionIsHandled = function () { - fireRejectionEvent("rejectionHandled", - unhandledRejectionHandled, undefined, this); - }; - - Promise.prototype._setReturnedNonUndefined = function() { - this._bitField = this._bitField | 268435456; - }; - - Promise.prototype._returnedNonUndefined = function() { - return (this._bitField & 268435456) !== 0; - }; - - Promise.prototype._notifyUnhandledRejection = function () { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue(); - this._setUnhandledRejectionIsNotified(); - fireRejectionEvent("unhandledRejection", - possiblyUnhandledRejection, reason, this); - } - }; - - Promise.prototype._setUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField | 262144; - }; - - Promise.prototype._unsetUnhandledRejectionIsNotified = function () { - this._bitField = this._bitField & (~262144); - }; - - Promise.prototype._isUnhandledRejectionNotified = function () { - return (this._bitField & 262144) > 0; - }; - - Promise.prototype._setRejectionIsUnhandled = function () { - this._bitField = this._bitField | 1048576; - }; - - Promise.prototype._unsetRejectionIsUnhandled = function () { - this._bitField = this._bitField & (~1048576); - if (this._isUnhandledRejectionNotified()) { - this._unsetUnhandledRejectionIsNotified(); - this._notifyUnhandledRejectionIsHandled(); - } - }; - - Promise.prototype._isRejectionUnhandled = function () { - return (this._bitField & 1048576) > 0; - }; - - Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { - return warn(message, shouldUseOwnTrace, promise || this); - }; - - Promise.onPossiblyUnhandledRejection = function (fn) { - var domain = getDomain(); - possiblyUnhandledRejection = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; - }; - - Promise.onUnhandledRejectionHandled = function (fn) { - var domain = getDomain(); - unhandledRejectionHandled = - typeof fn === "function" ? (domain === null ? - fn : util.domainBind(domain, fn)) - : undefined; - }; - - var disableLongStackTraces = function() {}; - Promise.longStackTraces = function () { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (!config.longStackTraces && longStackTracesIsSupported()) { - var Promise_captureStackTrace = Promise.prototype._captureStackTrace; - var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; - config.longStackTraces = true; - disableLongStackTraces = function() { - if (async.haveItemsQueued() && !config.longStackTraces) { - throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - Promise.prototype._captureStackTrace = Promise_captureStackTrace; - Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; - Context.deactivateLongStackTraces(); - async.enableTrampoline(); - config.longStackTraces = false; - }; - Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; - Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; - Context.activateLongStackTraces(); - async.disableTrampolineIfNecessary(); - } - }; - - Promise.hasLongStackTraces = function () { - return config.longStackTraces && longStackTracesIsSupported(); - }; - - var fireDomEvent = (function() { - try { - if (typeof CustomEvent === "function") { - var event = new CustomEvent("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new CustomEvent(name.toLowerCase(), { - detail: event, - cancelable: true - }); - return !util.global.dispatchEvent(domEvent); - }; - } else if (typeof Event === "function") { - var event = new Event("CustomEvent"); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = new Event(name.toLowerCase(), { - cancelable: true - }); - domEvent.detail = event; - return !util.global.dispatchEvent(domEvent); - }; - } else { - var event = document.createEvent("CustomEvent"); - event.initCustomEvent("testingtheevent", false, true, {}); - util.global.dispatchEvent(event); - return function(name, event) { - var domEvent = document.createEvent("CustomEvent"); - domEvent.initCustomEvent(name.toLowerCase(), false, true, - event); - return !util.global.dispatchEvent(domEvent); - }; - } - } catch (e) {} - return function() { - return false; - }; - })(); - - var fireGlobalEvent = (function() { - if (util.isNode) { - return function() { - return process.emit.apply(process, arguments); - }; - } else { - if (!util.global) { - return function() { - return false; - }; - } - return function(name) { - var methodName = "on" + name.toLowerCase(); - var method = util.global[methodName]; - if (!method) return false; - method.apply(util.global, [].slice.call(arguments, 1)); - return true; - }; - } - })(); - - function generatePromiseLifecycleEventObject(name, promise) { - return {promise: promise}; - } - - var 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 - }; - - var activeFireEvent = function (name) { - var globalEventFired = false; - try { - globalEventFired = fireGlobalEvent.apply(null, arguments); - } catch (e) { - async.throwLater(e); - globalEventFired = true; - } - - var domEventFired = false; - try { - domEventFired = fireDomEvent(name, - eventToObjectGenerator[name].apply(null, arguments)); - } catch (e) { - async.throwLater(e); - domEventFired = true; - } - - return domEventFired || globalEventFired; - }; - - Promise.config = function(opts) { - opts = Object(opts); - if ("longStackTraces" in opts) { - if (opts.longStackTraces) { - Promise.longStackTraces(); - } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { - disableLongStackTraces(); - } - } - if ("warnings" in opts) { - var warningsOption = opts.warnings; - config.warnings = !!warningsOption; - wForgottenReturn = config.warnings; - - if (util.isObject(warningsOption)) { - if ("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 = true; - } - if ("monitoring" in opts) { - if (opts.monitoring && !config.monitoring) { - config.monitoring = true; - Promise.prototype._fireEvent = activeFireEvent; - } else if (!opts.monitoring && config.monitoring) { - config.monitoring = false; - Promise.prototype._fireEvent = defaultFireEvent; - } - } - }; - - function defaultFireEvent() { return false; } - - 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) { - ; - ; - }; - - function cancellationExecute(executor, resolve, reject) { - var promise = this; - try { - executor(resolve, reject, function(onCancel) { - if (typeof onCancel !== "function") { - 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(); - if (previousOnCancel !== undefined) { - if (util.isArray(previousOnCancel)) { - previousOnCancel.push(onCancel); - } else { - this._setOnCancel([previousOnCancel, onCancel]); - } - } else { - this._setOnCancel(onCancel); - } - } - - function cancellationOnCancel() { - return this._onCancelField; - } - - function cancellationSetOnCancel(onCancel) { - this._onCancelField = onCancel; - } - - function cancellationClearCancellationData() { - this._cancellationParent = undefined; - this._onCancelField = undefined; - } - - function cancellationPropagateFrom(parent, flags) { - if ((flags & 1) !== 0) { - this._cancellationParent = parent; - var branchesRemainingToCancel = parent._branchesRemainingToCancel; - if (branchesRemainingToCancel === undefined) { - branchesRemainingToCancel = 0; - } - parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; - } - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } - } - - function bindingPropagateFrom(parent, flags) { - if ((flags & 2) !== 0 && parent._isBound()) { - this._setBoundTo(parent._boundTo); - } - } - var propagateFromFunction = bindingPropagateFrom; - - function boundValueFunction() { - var ret = this._boundTo; - if (ret !== undefined) { - if (ret instanceof Promise) { - if (ret.isFulfilled()) { - return ret.value(); - } else { - return undefined; - } - } - } - return ret; - } - - function longStackTracesCaptureStackTrace() { - this._trace = new CapturedTrace(this._peekContext()); - } - - function longStackTracesAttachExtraTrace(error, ignoreSelf) { - if (canAttachTrace(error)) { - var trace = this._trace; - if (trace !== undefined) { - if (ignoreSelf) trace = trace._parent; - } - if (trace !== undefined) { - 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__", true); - } - } - } - - function checkForgottenReturns(returnValue, promiseCreated, name, promise, - parent) { - if (returnValue === undefined && promiseCreated !== null && - wForgottenReturn) { - if (parent !== undefined && parent._returnedNonUndefined()) return; - if ((promise._bitField & 65535) === 0) return; - - if (name) name = name + " "; - var handlerLine = ""; - var creatorLine = ""; - if (promiseCreated._trace) { - var traceLines = promiseCreated._trace.stack.split("\n"); - var stack = cleanStack(traceLines); - for (var i = stack.length - 1; i >= 0; --i) { - var line = stack[i]; - if (!nodeFramePattern.test(line)) { - var lineMatches = line.match(parseLinePattern); - if (lineMatches) { - handlerLine = "at " + lineMatches[1] + - ":" + lineMatches[2] + ":" + lineMatches[3] + " "; - } - break; - } - } - - if (stack.length > 0) { - var firstUserLine = stack[0]; - for (var i = 0; i < traceLines.length; ++i) { - - if (traceLines[i] === firstUserLine) { - if (i > 0) { - 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, true, promiseCreated); - } - } - - function deprecated(name, replacement) { - var message = name + - " is deprecated and will be removed in a future version."; - if (replacement) message += " Use " + replacement + " instead."; - return warn(message); - } - - function warn(message, shouldUseOwnTrace, promise) { - if (!config.warnings) return; - var warning = new Warning(message); - var ctx; - 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"); - } - - if (!activeFireEvent("warning", warning)) { - formatAndLogError(warning, "", true); - } - } - - function reconstructStack(message, stacks) { - for (var i = 0; i < stacks.length - 1; ++i) { - stacks[i].push("From previous event:"); - stacks[i] = stacks[i].join("\n"); - } - if (i < stacks.length) { - stacks[i] = stacks[i].join("\n"); - } - return message + "\n" + stacks.join("\n"); - } - - function removeDuplicateOrEmptyJumps(stacks) { - for (var i = 0; i < stacks.length; ++i) { - if (stacks[i].length === 0 || - ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { - stacks.splice(i, 1); - i--; - } - } - } - - function removeCommonRoots(stacks) { - var current = stacks[0]; - for (var i = 1; i < stacks.length; ++i) { - var prev = stacks[i]; - var currentLastIndex = current.length - 1; - var currentLastLine = current[currentLastIndex]; - var commonRootMeetPoint = -1; - - for (var j = prev.length - 1; j >= 0; --j) { - if (prev[j] === currentLastLine) { - commonRootMeetPoint = j; - break; - } - } - - for (var j = commonRootMeetPoint; j >= 0; --j) { - var line = prev[j]; - if (current[currentLastIndex] === line) { - current.pop(); - currentLastIndex--; - } else { - break; - } - } - current = prev; - } - } - - function cleanStack(stack) { - var ret = []; - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - var isTraceLine = " (No stack trace)" === line || - stackFramePattern.test(line); - var isInternalFrame = isTraceLine && shouldIgnore(line); - if (isTraceLine && !isInternalFrame) { - if (indentStackFrames && line.charAt(0) !== " ") { - line = " " + line; - } - ret.push(line); - } - } - return ret; - } - - function stackFramesAsArray(error) { - var stack = error.stack.replace(/\s+$/g, "").split("\n"); - for (var i = 0; i < stack.length; ++i) { - var line = stack[i]; - if (" (No stack trace)" === line || stackFramePattern.test(line)) { - break; - } - } - if (i > 0) { - stack = stack.slice(i); - } - return stack; - } - - function parseStackAndMessage(error) { - var stack = error.stack; - var message = error.toString(); - stack = typeof stack === "string" && stack.length > 0 - ? stackFramesAsArray(error) : [" (No stack trace)"]; - return { - message: message, - stack: cleanStack(stack) - }; - } - - function formatAndLogError(error, title, isSoft) { - if (typeof console !== "undefined") { - var message; - if (util.isObject(error)) { - var stack = error.stack; - message = title + formatStack(stack, error); - } else { - message = title + String(error); - } - if (typeof printWarning === "function") { - printWarning(message, isSoft); - } else if (typeof console.log === "function" || - typeof console.log === "object") { - console.log(message); - } - } - } - - function fireRejectionEvent(name, localHandler, reason, promise) { - var localEventFired = false; - try { - if (typeof localHandler === "function") { - localEventFired = true; - if (name === "rejectionHandled") { - localHandler(promise); - } else { - localHandler(reason, promise); - } - } - } catch (e) { - async.throwLater(e); - } - - if (name === "unhandledRejection") { - if (!activeFireEvent(name, reason, promise) && !localEventFired) { - formatAndLogError(reason, "Unhandled rejection "); - } - } else { - activeFireEvent(name, promise); - } - } - - function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } else { - str = obj && typeof obj.toString === "function" - ? 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) { - - } - } - if (str.length === 0) { - str = "(empty array)"; - } - } - return ("(<" + snip(str) + ">, no stack trace)"); - } - - function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; - } - return str.substr(0, maxChars - 3) + "..."; - } - - function longStackTracesIsSupported() { - return typeof captureStackTrace === "function"; - } - - var shouldIgnore = function() { return false; }; - var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; - function parseLineInfo(line) { - var matches = line.match(parseLineInfoRegex); - if (matches) { - return { - fileName: matches[1], - line: parseInt(matches[2], 10) - }; - } - } - - function setBounds(firstLineError, lastLineError) { - if (!longStackTracesIsSupported()) return; - var firstStackLines = firstLineError.stack.split("\n"); - var lastStackLines = lastLineError.stack.split("\n"); - var firstIndex = -1; - var lastIndex = -1; - var firstFileName; - var lastFileName; - for (var i = 0; i < firstStackLines.length; ++i) { - var result = parseLineInfo(firstStackLines[i]); - if (result) { - firstFileName = result.fileName; - firstIndex = result.line; - break; - } - } - for (var i = 0; i < lastStackLines.length; ++i) { - var result = parseLineInfo(lastStackLines[i]); - if (result) { - lastFileName = result.fileName; - lastIndex = result.line; - break; - } - } - if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || - firstFileName !== lastFileName || firstIndex >= lastIndex) { - return; - } - - shouldIgnore = function(line) { - if (bluebirdFramePattern.test(line)) return true; - var info = parseLineInfo(line); - if (info) { - if (info.fileName === firstFileName && - (firstIndex <= info.line && info.line <= lastIndex)) { - return true; - } - } - return false; - }; - } - - function CapturedTrace(parent) { - this._parent = parent; - this._promisesCreated = 0; - var length = this._length = 1 + (parent === undefined ? 0 : parent._length); - captureStackTrace(this, CapturedTrace); - if (length > 32) this.uncycle(); - } - util.inherits(CapturedTrace, Error); - Context.CapturedTrace = CapturedTrace; - - CapturedTrace.prototype.uncycle = function() { - var length = this._length; - if (length < 2) return; - var nodes = []; - var stackToIndex = {}; - - for (var i = 0, node = this; node !== undefined; ++i) { - nodes.push(node); - node = node._parent; - } - length = this._length = i; - for (var i = length - 1; i >= 0; --i) { - var stack = nodes[i].stack; - if (stackToIndex[stack] === undefined) { - stackToIndex[stack] = i; - } - } - for (var i = 0; i < length; ++i) { - var currentStack = nodes[i].stack; - var index = stackToIndex[currentStack]; - if (index !== undefined && index !== i) { - if (index > 0) { - nodes[index - 1]._parent = undefined; - nodes[index - 1]._length = 1; - } - nodes[i]._parent = undefined; - nodes[i]._length = 1; - var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; - - if (index < length - 1) { - cycleEdgeNode._parent = nodes[index + 1]; - cycleEdgeNode._parent.uncycle(); - cycleEdgeNode._length = - cycleEdgeNode._parent._length + 1; - } else { - cycleEdgeNode._parent = undefined; - cycleEdgeNode._length = 1; - } - var currentChildLength = cycleEdgeNode._length + 1; - for (var j = i - 2; j >= 0; --j) { - nodes[j]._length = currentChildLength; - currentChildLength++; - } - return; - } - } - }; - - CapturedTrace.prototype.attachExtraTrace = function(error) { - if (error.__stackCleaned__) return; - this.uncycle(); - var parsed = parseStackAndMessage(error); - var message = parsed.message; - var stacks = [parsed.stack]; - - var trace = this; - while (trace !== undefined) { - 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__", true); - }; - - var captureStackTrace = (function stackDetection() { - var v8stackFramePattern = /^\s*at\s*/; - var v8stackFormatter = function(stack, error) { - if (typeof stack === "string") return stack; - - if (error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - Error.stackTraceLimit += 6; - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - var captureStackTrace = Error.captureStackTrace; - - shouldIgnore = function(line) { - return bluebirdFramePattern.test(line); - }; - return function(receiver, ignoreUntil) { - Error.stackTraceLimit += 6; - captureStackTrace(receiver, ignoreUntil); - Error.stackTraceLimit -= 6; - }; - } - var err = new Error(); - - if (typeof err.stack === "string" && - err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { - stackFramePattern = /@/; - formatStack = v8stackFormatter; - indentStackFrames = true; - return function captureStackTrace(o) { - o.stack = new Error().stack; - }; - } - - var hasStackAfterThrow; - try { throw new Error(); } - catch(e) { - hasStackAfterThrow = ("stack" in e); - } - if (!("stack" in err) && hasStackAfterThrow && - typeof Error.stackTraceLimit === "number") { - stackFramePattern = v8stackFramePattern; - formatStack = v8stackFormatter; - return function captureStackTrace(o) { - Error.stackTraceLimit += 6; - try { throw new Error(); } - catch(e) { o.stack = e.stack; } - Error.stackTraceLimit -= 6; - }; - } - - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== undefined && - error.message !== undefined) { - return error.toString(); - } - return formatNonError(error); - }; - - return null; - - })([]); - - if (typeof console !== "undefined" && typeof console.warn !== "undefined") { - printWarning = function (message) { - console.warn(message); - }; - if (util.isNode && process.stderr.isTTY) { - printWarning = function(message, isSoft) { - var color = isSoft ? "\u001b[33m" : "\u001b[31m"; - console.warn(color + message + "\u001b[0m\n"); - }; - } else if (!util.isNode && typeof (new Error().stack) === "string") { - printWarning = function(message, isSoft) { - console.warn("%c" + message, - isSoft ? "color: darkorange" : "color: red"); - }; - } - } - - var config = { - warnings: warnings, - longStackTraces: false, - cancellation: false, - monitoring: false - }; - - if (longStackTraces) Promise.longStackTraces(); - - return { - 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){ - "use strict"; - module.exports = function(Promise) { - function returner() { - return this.value; - } - function thrower() { - throw this.reason; - } - - Promise.prototype["return"] = - Promise.prototype.thenReturn = function (value) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - returner, undefined, undefined, {value: value}, undefined); - }; - - Promise.prototype["throw"] = - Promise.prototype.thenThrow = function (reason) { - return this._then( - thrower, undefined, undefined, {reason: reason}, undefined); - }; - - Promise.prototype.catchThrow = function (reason) { - if (arguments.length <= 1) { - return this._then( - undefined, thrower, undefined, {reason: reason}, undefined); - } else { - var _reason = arguments[1]; - var handler = function() {throw _reason;}; - return this.caught(reason, handler); - } - }; - - Promise.prototype.catchReturn = function (value) { - if (arguments.length <= 1) { - if (value instanceof Promise) value.suppressUnhandledRejections(); - return this._then( - undefined, returner, undefined, {value: value}, undefined); - } else { - var _value = arguments[1]; - if (_value instanceof Promise) _value.suppressUnhandledRejections(); - var handler = function() {return _value;}; - return this.caught(value, handler); - } - }; - }; - - },{}],11:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL) { - var PromiseReduce = Promise.reduce; - var PromiseAll = Promise.all; - - function promiseAllThis() { - return PromiseAll(this); - } - - function PromiseMapSeries(promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, INTERNAL); - } - - Promise.prototype.each = function (fn) { - return PromiseReduce(this, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, this, undefined); - }; - - Promise.prototype.mapSeries = function (fn) { - return PromiseReduce(this, fn, INTERNAL, INTERNAL); - }; - - Promise.each = function (promises, fn) { - return PromiseReduce(promises, fn, INTERNAL, 0) - ._then(promiseAllThis, undefined, undefined, promises, undefined); - }; - - Promise.mapSeries = PromiseMapSeries; - }; - - - },{}],12:[function(_dereq_,module,exports){ - "use strict"; - var es5 = _dereq_("./es5"); - var Objectfreeze = es5.freeze; - var util = _dereq_("./util"); - var inherits = util.inherits; - var notEnumerableProp = util.notEnumerableProp; - - function subError(nameProperty, defaultMessage) { - function SubError(message) { - if (!(this instanceof SubError)) return new SubError(message); - notEnumerableProp(this, "message", - typeof message === "string" ? message : defaultMessage); - notEnumerableProp(this, "name", nameProperty); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } else { - Error.call(this); - } - } - inherits(SubError, Error); - return SubError; - } - - var _TypeError, _RangeError; - var Warning = subError("Warning", "warning"); - var CancellationError = subError("CancellationError", "cancellation error"); - var TimeoutError = subError("TimeoutError", "timeout error"); - var AggregateError = subError("AggregateError", "aggregate error"); - try { - _TypeError = TypeError; - _RangeError = RangeError; - } catch(e) { - _TypeError = subError("TypeError", "type error"); - _RangeError = subError("RangeError", "range error"); - } - - var methods = ("join pop push shift unshift slice filter forEach some " + - "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); - - for (var i = 0; i < methods.length; ++i) { - if (typeof Array.prototype[methods[i]] === "function") { - AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; - } - } - - es5.defineProperty(AggregateError.prototype, "length", { - value: 0, - configurable: false, - writable: true, - enumerable: true - }); - AggregateError.prototype["isOperational"] = true; - var level = 0; - AggregateError.prototype.toString = function() { - var indent = Array(level * 4 + 1).join(" "); - var ret = "\n" + indent + "AggregateError of:" + "\n"; - level++; - indent = Array(level * 4 + 1).join(" "); - for (var i = 0; i < this.length; ++i) { - var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; - var lines = str.split("\n"); - for (var j = 0; j < lines.length; ++j) { - lines[j] = indent + lines[j]; - } - str = lines.join("\n"); - ret += str + "\n"; - } - level--; - return ret; - }; - - function OperationalError(message) { - if (!(this instanceof OperationalError)) - return new OperationalError(message); - notEnumerableProp(this, "name", "OperationalError"); - notEnumerableProp(this, "message", message); - this.cause = message; - this["isOperational"] = true; - - if (message instanceof Error) { - notEnumerableProp(this, "message", message.message); - notEnumerableProp(this, "stack", message.stack); - } else if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - } - inherits(OperationalError, Error); - - var errorTypes = Error["__BluebirdErrorTypes__"]; - if (!errorTypes) { - errorTypes = Objectfreeze({ - CancellationError: CancellationError, - TimeoutError: TimeoutError, - OperationalError: OperationalError, - RejectionError: OperationalError, - AggregateError: AggregateError - }); - es5.defineProperty(Error, "__BluebirdErrorTypes__", { - value: errorTypes, - writable: false, - enumerable: false, - configurable: false - }); - } - - module.exports = { - Error: Error, - TypeError: _TypeError, - RangeError: _RangeError, - CancellationError: errorTypes.CancellationError, - OperationalError: errorTypes.OperationalError, - TimeoutError: errorTypes.TimeoutError, - AggregateError: errorTypes.AggregateError, - Warning: Warning - }; - - },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ - var isES5 = (function(){ - "use strict"; - return this === undefined; - })(); - - if (isES5) { - module.exports = { - freeze: Object.freeze, - defineProperty: Object.defineProperty, - getDescriptor: Object.getOwnPropertyDescriptor, - keys: Object.keys, - names: Object.getOwnPropertyNames, - getPrototypeOf: Object.getPrototypeOf, - isArray: Array.isArray, - isES5: isES5, - propertyIsWritable: function(obj, prop) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop); - return !!(!descriptor || descriptor.writable || descriptor.set); - } - }; - } else { - var has = {}.hasOwnProperty; - var str = {}.toString; - var proto = {}.constructor.prototype; - - var ObjectKeys = function (o) { - var ret = []; - for (var key in o) { - if (has.call(o, key)) { - ret.push(key); - } - } - return ret; - }; - - var ObjectGetDescriptor = function(o, key) { - return {value: o[key]}; - }; - - var ObjectDefineProperty = function (o, key, desc) { - o[key] = desc.value; - return o; - }; - - var ObjectFreeze = function (obj) { - return obj; - }; - - var ObjectGetPrototypeOf = function (obj) { - try { - return Object(obj).constructor.prototype; - } - catch (e) { - return proto; - } - }; - - var ArrayIsArray = function (obj) { - try { - return str.call(obj) === "[object Array]"; - } - catch(e) { - return false; - } - }; - - module.exports = { - isArray: ArrayIsArray, - keys: ObjectKeys, - names: ObjectKeys, - defineProperty: ObjectDefineProperty, - getDescriptor: ObjectGetDescriptor, - freeze: ObjectFreeze, - getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5, - propertyIsWritable: function() { - return true; - } - }; - } - - },{}],14:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL) { - var PromiseMap = Promise.map; - - Promise.prototype.filter = function (fn, options) { - return PromiseMap(this, fn, options, INTERNAL); - }; - - Promise.filter = function (promises, fn, options) { - return PromiseMap(promises, fn, options, INTERNAL); - }; - }; - - },{}],15:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, tryConvertToPromise) { - var util = _dereq_("./util"); - var CancellationError = Promise.CancellationError; - var errorObj = util.errorObj; - - function PassThroughHandlerContext(promise, type, handler) { - this.promise = promise; - this.type = type; - this.handler = handler; - this.called = false; - this.cancelPromise = null; - } - - PassThroughHandlerContext.prototype.isFinallyHandler = function() { - return this.type === 0; - }; - - function FinallyHandlerCancelReaction(finallyHandler) { - this.finallyHandler = finallyHandler; - } - - FinallyHandlerCancelReaction.prototype._resultCancelled = function() { - checkCancel(this.finallyHandler); - }; - - function checkCancel(ctx, reason) { - if (ctx.cancelPromise != null) { - if (arguments.length > 1) { - ctx.cancelPromise._reject(reason); - } else { - ctx.cancelPromise._cancel(); - } - ctx.cancelPromise = null; - return true; - } - return false; - } - - function succeed() { - return finallyHandler.call(this, this.promise._target()._settledValue()); - } - function fail(reason) { - if (checkCancel(this, reason)) return; - errorObj.e = reason; - return errorObj; - } - function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; - - if (!this.called) { - this.called = true; - var ret = this.isFinallyHandler() - ? handler.call(promise._boundValue()) - : handler.call(promise._boundValue(), reasonOrValue); - if (ret !== undefined) { - promise._setReturnedNonUndefined(); - var maybePromise = tryConvertToPromise(ret, promise); - if (maybePromise instanceof Promise) { - if (this.cancelPromise != null) { - if (maybePromise._isCancelled()) { - var reason = - new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - errorObj.e = reason; - return errorObj; - } else if (maybePromise.isPending()) { - maybePromise._attachCancellationCallback( - new FinallyHandlerCancelReaction(this)); - } - } - return maybePromise._then( - succeed, fail, undefined, this, undefined); - } - } - } - - if (promise.isRejected()) { - checkCancel(this); - errorObj.e = reasonOrValue; - return errorObj; - } else { - checkCancel(this); - return reasonOrValue; - } - } - - Promise.prototype._passThrough = function(handler, type, success, fail) { - if (typeof handler !== "function") return this.then(); - return this._then(success, - fail, - undefined, - new PassThroughHandlerContext(this, type, handler), - undefined); - }; - - 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); - }; - - return PassThroughHandlerContext; - }; - - },{"./util":36}],16:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { - var errors = _dereq_("./errors"); - var TypeError = errors.TypeError; - var util = _dereq_("./util"); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var yieldHandlers = []; - - function promiseFromYieldHandler(value, yieldHandlers, traceParent) { - for (var i = 0; i < yieldHandlers.length; ++i) { - traceParent._pushContext(); - var result = tryCatch(yieldHandlers[i])(value); - traceParent._popContext(); - if (result === errorObj) { - traceParent._pushContext(); - var ret = Promise.reject(errorObj.e); - traceParent._popContext(); - return ret; - } - var maybePromise = tryConvertToPromise(result, traceParent); - if (maybePromise instanceof Promise) return maybePromise; - } - return null; - } - - function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { - if (debug.cancellation()) { - var internal = new Promise(INTERNAL); - var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); - this._promise = internal.lastly(function() { - return _finallyPromise; - }); - internal._captureStackTrace(); - internal._setOnCancel(this); - } else { - var promise = this._promise = new Promise(INTERNAL); - promise._captureStackTrace(); - } - this._stack = stack; - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = undefined; - this._yieldHandlers = typeof yieldHandler === "function" - ? [yieldHandler].concat(yieldHandlers) - : yieldHandlers; - this._yieldedPromise = null; - this._cancellationPhase = false; - } - util.inherits(PromiseSpawn, Proxyable); - - PromiseSpawn.prototype._isResolved = function() { - return this._promise === null; - }; - - PromiseSpawn.prototype._cleanup = function() { - this._promise = this._generator = null; - if (debug.cancellation() && this._finallyPromise !== null) { - this._finallyPromise._fulfill(); - this._finallyPromise = null; - } - }; - - PromiseSpawn.prototype._promiseCancelled = function() { - if (this._isResolved()) return; - var implementsReturn = typeof this._generator["return"] !== "undefined"; - - var result; - if (!implementsReturn) { - var reason = new Promise.CancellationError( - "generator .return() sentinel"); - Promise.coroutine.returnSentinel = reason; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - result = tryCatch(this._generator["throw"]).call(this._generator, - reason); - this._promise._popContext(); - } else { - this._promise._pushContext(); - result = tryCatch(this._generator["return"]).call(this._generator, - undefined); - this._promise._popContext(); - } - this._cancellationPhase = true; - this._yieldedPromise = null; - this._continue(result); - }; - - PromiseSpawn.prototype._promiseFulfilled = function(value) { - this._yieldedPromise = null; - this._promise._pushContext(); - var result = tryCatch(this._generator.next).call(this._generator, value); - this._promise._popContext(); - this._continue(result); - }; - - PromiseSpawn.prototype._promiseRejected = function(reason) { - this._yieldedPromise = null; - this._promise._attachExtraTrace(reason); - this._promise._pushContext(); - var result = tryCatch(this._generator["throw"]) - .call(this._generator, reason); - this._promise._popContext(); - this._continue(result); - }; - - PromiseSpawn.prototype._resultCancelled = function() { - if (this._yieldedPromise instanceof Promise) { - var promise = this._yieldedPromise; - this._yieldedPromise = null; - promise.cancel(); - } - }; - - PromiseSpawn.prototype.promise = function () { - return this._promise; - }; - - PromiseSpawn.prototype._run = function () { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = undefined; - this._promiseFulfilled(undefined); - }; - - PromiseSpawn.prototype._continue = function (result) { - var promise = this._promise; - if (result === errorObj) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._rejectCallback(result.e, false); - } - } - - var value = result.value; - if (result.done === true) { - this._cleanup(); - if (this._cancellationPhase) { - return promise.cancel(); - } else { - return promise._resolveCallback(value); - } - } else { - var maybePromise = tryConvertToPromise(value, this._promise); - if (!(maybePromise instanceof Promise)) { - maybePromise = - promiseFromYieldHandler(maybePromise, - this._yieldHandlers, - this._promise); - if (maybePromise === null) { - this._promiseRejected( - new TypeError( - "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + - "From coroutine:\u000a" + - this._stack.split("\n").slice(1, -7).join("\n") - ) - ); - return; - } - } - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - this._yieldedPromise = maybePromise; - maybePromise._proxy(this, null); - } else if (((bitField & 33554432) !== 0)) { - Promise._async.invoke( - this._promiseFulfilled, this, maybePromise._value() - ); - } else if (((bitField & 16777216) !== 0)) { - Promise._async.invoke( - this._promiseRejected, this, maybePromise._reason() - ); - } else { - this._promiseCancelled(); - } - } - }; - - Promise.coroutine = function (generatorFunction, options) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var yieldHandler = Object(options).yieldHandler; - var PromiseSpawn$ = PromiseSpawn; - var stack = new Error().stack; - return function () { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, - stack); - var ret = spawn.promise(); - spawn._generator = generator; - spawn._promiseFulfilled(undefined); - return ret; - }; - }; - - Promise.coroutine.addYieldHandler = function(fn) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - yieldHandlers.push(fn); - }; - - Promise.spawn = function (generatorFunction) { - debug.deprecated("Promise.spawn()", "Promise.coroutine()"); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var spawn = new PromiseSpawn(generatorFunction, this); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; - }; - }; - - },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ - "use strict"; - module.exports = - function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { - var util = _dereq_("./util"); - var canEvaluate = util.canEvaluate; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var reject; - - if (false) { - if (canEvaluate) { - var thenCallback = function(i) { - return new Function("value", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = value; \n\ - holder.checkFulfillment(this); \n\ - ".replace(/Index/g, i)); - }; - - var promiseSetter = function(i) { - return new Function("promise", "holder", " \n\ - 'use strict'; \n\ - holder.pIndex = promise; \n\ - ".replace(/Index/g, i)); - }; - - var generateHolderClass = function(total) { - var props = new Array(total); - for (var i = 0; i < props.length; ++i) { - props[i] = "this.p" + (i+1); - } - var assignment = props.join(" = ") + " = null;"; - var cancellationCode= "var promise;\n" + props.map(function(prop) { - return " \n\ - promise = " + prop + "; \n\ - if (promise instanceof Promise) { \n\ - promise.cancel(); \n\ - } \n\ - "; - }).join("\n"); - var passedArguments = props.join(", "); - var name = "Holder$" + total; - - - var code = "return function(tryCatch, errorObj, Promise, async) { \n\ - 'use strict'; \n\ - function [TheName](fn) { \n\ - [TheProperties] \n\ - this.fn = fn; \n\ - this.asyncNeeded = true; \n\ - this.now = 0; \n\ - } \n\ - \n\ - [TheName].prototype._callFunction = function(promise) { \n\ - promise._pushContext(); \n\ - var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ - promise._popContext(); \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(ret.e, false); \n\ - } else { \n\ - promise._resolveCallback(ret); \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype.checkFulfillment = function(promise) { \n\ - var now = ++this.now; \n\ - if (now === [TheTotal]) { \n\ - if (this.asyncNeeded) { \n\ - async.invoke(this._callFunction, this, promise); \n\ - } else { \n\ - this._callFunction(promise); \n\ - } \n\ - \n\ - } \n\ - }; \n\ - \n\ - [TheName].prototype._resultCancelled = function() { \n\ - [CancellationCode] \n\ - }; \n\ - \n\ - return [TheName]; \n\ - }(tryCatch, errorObj, Promise, async); \n\ - "; - - code = code.replace(/\[TheName\]/g, name) - .replace(/\[TheTotal\]/g, total) - .replace(/\[ThePassedArguments\]/g, passedArguments) - .replace(/\[TheProperties\]/g, assignment) - .replace(/\[CancellationCode\]/g, cancellationCode); - - return new Function("tryCatch", "errorObj", "Promise", "async", code) - (tryCatch, errorObj, Promise, async); - }; - - var holderClasses = []; - var thenCallbacks = []; - var promiseSetters = []; - - for (var i = 0; i < 8; ++i) { - holderClasses.push(generateHolderClass(i + 1)); - thenCallbacks.push(thenCallback(i + 1)); - promiseSetters.push(promiseSetter(i + 1)); - } - - reject = function (reason) { - this._reject(reason); - }; - }} - - Promise.join = function () { - var last = arguments.length - 1; - var fn; - if (last > 0 && typeof arguments[last] === "function") { - fn = arguments[last]; - if (false) { - if (last <= 8 && canEvaluate) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - var HolderClass = holderClasses[last - 1]; - var holder = new HolderClass(fn); - var callbacks = thenCallbacks; - - for (var i = 0; i < last; ++i) { - var maybePromise = tryConvertToPromise(arguments[i], ret); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - maybePromise._then(callbacks[i], reject, - undefined, ret, holder); - promiseSetters[i](maybePromise, holder); - holder.asyncNeeded = false; - } else if (((bitField & 33554432) !== 0)) { - callbacks[i].call(ret, - maybePromise._value(), holder); - } else if (((bitField & 16777216) !== 0)) { - ret._reject(maybePromise._reason()); - } else { - ret._cancel(); - } - } else { - callbacks[i].call(ret, maybePromise, holder); - } - } - - if (!ret._isFateSealed()) { - if (holder.asyncNeeded) { - var domain = getDomain(); - if (domain !== null) { - holder.fn = util.domainBind(domain, holder.fn); - } - } - ret._setAsyncGuaranteed(); - ret._setOnCancel(holder); - } - return ret; - } - } - } - var args = [].slice.call(arguments);; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; - }; - - }; - - },{"./util":36}],18:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { - var getDomain = Promise._getDomain; - var util = _dereq_("./util"); - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - var async = Promise._async; - - function MappingPromiseArray(promises, fn, limit, _filter) { - this.constructor$(promises); - this._promise._captureStackTrace(); - var domain = getDomain(); - this._callback = domain === null ? 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, undefined); - } - util.inherits(MappingPromiseArray, PromiseArray); - - MappingPromiseArray.prototype._asyncInit = function() { - this._init$(undefined, -2); - }; - - MappingPromiseArray.prototype._init = function () {}; - - MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { - var values = this._values; - var length = this.length(); - var preservedValues = this._preservedValues; - var limit = this._limit; - - if (index < 0) { - index = (index * -1) - 1; - values[index] = value; - if (limit >= 1) { - this._inFlight--; - this._drainQueue(); - if (this._isResolved()) return true; - } - } else { - if (limit >= 1 && this._inFlight >= limit) { - values[index] = value; - this._queue.push(index); - return false; - } - if (preservedValues !== null) preservedValues[index] = value; - - var promise = this._promise; - var callback = this._callback; - var receiver = promise._boundValue(); - promise._pushContext(); - var ret = tryCatch(callback).call(receiver, value, index, length); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - preservedValues !== null ? "Promise.filter" : "Promise.map", - promise - ); - if (ret === errorObj) { - this._reject(ret.e); - return true; - } - - var maybePromise = tryConvertToPromise(ret, this._promise); - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - var bitField = maybePromise._bitField; - ; - if (((bitField & 50397184) === 0)) { - if (limit >= 1) this._inFlight++; - values[index] = maybePromise; - maybePromise._proxy(this, (index + 1) * -1); - return false; - } else if (((bitField & 33554432) !== 0)) { - ret = maybePromise._value(); - } else if (((bitField & 16777216) !== 0)) { - this._reject(maybePromise._reason()); - return true; - } else { - this._cancel(); - return true; - } - } - values[index] = ret; - } - var totalResolved = ++this._totalResolved; - if (totalResolved >= length) { - if (preservedValues !== null) { - this._filter(values, preservedValues); - } else { - this._resolve(values); - } - return true; - } - return false; - }; - - MappingPromiseArray.prototype._drainQueue = function () { - var queue = this._queue; - var limit = this._limit; - var values = this._values; - while (queue.length > 0 && this._inFlight < limit) { - if (this._isResolved()) return; - var index = queue.pop(); - this._promiseFulfilled(values[index], index); - } - }; - - MappingPromiseArray.prototype._filter = function (booleans, values) { - var len = values.length; - var ret = new Array(len); - var j = 0; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; - } - ret.length = j; - this._resolve(ret); - }; - - MappingPromiseArray.prototype.preservedValues = function () { - return this._preservedValues; - }; - - function map(promises, fn, options, _filter) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - - var limit = 0; - if (options !== undefined) { - if (typeof options === "object" && options !== null) { - if (typeof options.concurrency !== "number") { - return Promise.reject( - new TypeError("'concurrency' must be a number but it is " + - util.classString(options.concurrency))); - } - limit = options.concurrency; - } else { - return Promise.reject(new TypeError( - "options argument must be an object but it is " + - util.classString(options))); - } - } - limit = typeof limit === "number" && - isFinite(limit) && limit >= 1 ? limit : 0; - return new MappingPromiseArray(promises, fn, limit, _filter).promise(); - } - - Promise.prototype.map = function (fn, options) { - return map(this, fn, options, null); - }; - - Promise.map = function (promises, fn, options, _filter) { - return map(promises, fn, options, _filter); - }; - - - }; - - },{"./util":36}],19:[function(_dereq_,module,exports){ - "use strict"; - module.exports = - function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { - var util = _dereq_("./util"); - var tryCatch = util.tryCatch; - - Promise.method = function (fn) { - if (typeof fn !== "function") { - throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); - } - return function () { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value = tryCatch(fn).apply(this, arguments); - var promiseCreated = ret._popContext(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.method", ret); - ret._resolveFromSyncValue(value); - return ret; - }; - }; - - Promise.attempt = Promise["try"] = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._pushContext(); - var value; - if (arguments.length > 1) { - debug.deprecated("calling Promise.try with more than 1 argument"); - var arg = arguments[1]; - var 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(); - debug.checkForgottenReturns( - value, promiseCreated, "Promise.try", ret); - ret._resolveFromSyncValue(value); - return ret; - }; - - Promise.prototype._resolveFromSyncValue = function (value) { - if (value === util.errorObj) { - this._rejectCallback(value.e, false); - } else { - this._resolveCallback(value, true); - } - }; - }; - - },{"./util":36}],20:[function(_dereq_,module,exports){ - "use strict"; - var util = _dereq_("./util"); - var maybeWrapAsError = util.maybeWrapAsError; - var errors = _dereq_("./errors"); - var OperationalError = errors.OperationalError; - var es5 = _dereq_("./es5"); - - function isUntypedError(obj) { - return obj instanceof Error && - es5.getPrototypeOf(obj) === Error.prototype; - } - - var rErrorKey = /^(?:name|message|stack|cause)$/; - function wrapAsOperationalError(obj) { - var ret; - if (isUntypedError(obj)) { - ret = new OperationalError(obj); - ret.name = obj.name; - ret.message = obj.message; - ret.stack = obj.stack; - var keys = es5.keys(obj); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (!rErrorKey.test(key)) { - ret[key] = obj[key]; - } - } - return ret; - } - util.markAsOriginatingFromRejection(obj); - return obj; - } - - function nodebackForPromise(promise, multiArgs) { - return function(err, value) { - if (promise === null) return; - if (err) { - var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); - } else if (!multiArgs) { - promise._fulfill(value); - } else { - var args = [].slice.call(arguments, 1);; - promise._fulfill(args); - } - promise = null; - }; - } - - module.exports = nodebackForPromise; - - },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise) { - var util = _dereq_("./util"); - var async = Promise._async; - var tryCatch = util.tryCatch; - var errorObj = util.errorObj; - - function spreadAdapter(val, nodeback) { - var promise = this; - if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); - var ret = - tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } - - function successAdapter(val, nodeback) { - var promise = this; - var receiver = promise._boundValue(); - var ret = val === undefined - ? tryCatch(nodeback).call(receiver, null) - : tryCatch(nodeback).call(receiver, null, val); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } - function errorAdapter(reason, nodeback) { - var promise = this; - if (!reason) { - var newReason = new Error(reason + ""); - newReason.cause = reason; - reason = newReason; - } - var ret = tryCatch(nodeback).call(promise._boundValue(), reason); - if (ret === errorObj) { - async.throwLater(ret.e); - } - } - - Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, - options) { - if (typeof nodeback == "function") { - var adapter = successAdapter; - if (options !== undefined && Object(options).spread) { - adapter = spreadAdapter; - } - this._then( - adapter, - errorAdapter, - undefined, - this, - nodeback - ); - } - return this; - }; - }; - - },{"./util":36}],22:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function() { - var makeSelfResolutionError = function () { - return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - }; - var reflectHandler = function() { - return new Promise.PromiseInspection(this._target()); - }; - var apiRejection = function(msg) { - return Promise.reject(new TypeError(msg)); - }; - function Proxyable() {} - var UNDEFINED_BINDING = {}; - var util = _dereq_("./util"); - - var getDomain; - if (util.isNode) { - getDomain = function() { - var ret = process.domain; - if (ret === undefined) ret = null; - return ret; - }; - } else { - getDomain = function() { - return null; - }; - } - util.notEnumerableProp(Promise, "_getDomain", getDomain); - - var es5 = _dereq_("./es5"); - var Async = _dereq_("./async"); - var async = new Async(); - es5.defineProperty(Promise, "_async", {value: async}); - var errors = _dereq_("./errors"); - var TypeError = Promise.TypeError = errors.TypeError; - Promise.RangeError = errors.RangeError; - var CancellationError = Promise.CancellationError = errors.CancellationError; - Promise.TimeoutError = errors.TimeoutError; - Promise.OperationalError = errors.OperationalError; - Promise.RejectionError = errors.OperationalError; - Promise.AggregateError = errors.AggregateError; - var INTERNAL = function(){}; - var APPLY = {}; - var NEXT_FILTER = {}; - var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); - var PromiseArray = - _dereq_("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); - var Context = _dereq_("./context")(Promise); - /*jshint unused:false*/ - var createContext = Context.create; - var debug = _dereq_("./debuggability")(Promise, Context); - var CapturedTrace = debug.CapturedTrace; - var PassThroughHandlerContext = - _dereq_("./finally")(Promise, tryConvertToPromise); - var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - var nodebackForPromise = _dereq_("./nodeback"); - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - function check(self, executor) { - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - if (self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - } - - function Promise(executor) { - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - if (executor !== INTERNAL) { - check(this, executor); - this._resolveFromExecutor(executor); - } - this._promiseCreated(); - this._fireEvent("promiseCreated", this); - } - - Promise.prototype.toString = function () { - return "[object Promise]"; - }; - - Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { - var len = arguments.length; - if (len > 1) { - var catchInstances = new Array(len - 1), - j = 0, i; - for (i = 0; i < len - 1; ++i) { - var item = arguments[i]; - if (util.isObject(item)) { - catchInstances[j++] = item; - } else { - return apiRejection("expecting an object but got " + - "A catch statement predicate " + util.classString(item)); - } - } - catchInstances.length = j; - fn = arguments[i]; - return this.then(undefined, catchFilter(catchInstances, fn, this)); - } - return this.then(undefined, fn); - }; - - Promise.prototype.reflect = function () { - return this._then(reflectHandler, - reflectHandler, undefined, this, undefined); - }; - - Promise.prototype.then = function (didFulfill, didReject) { - if (debug.warnings() && arguments.length > 0 && - typeof didFulfill !== "function" && - typeof didReject !== "function") { - var msg = ".then() only accepts functions but was passed: " + - util.classString(didFulfill); - if (arguments.length > 1) { - msg += ", " + util.classString(didReject); - } - this._warn(msg); - } - return this._then(didFulfill, didReject, undefined, undefined, undefined); - }; - - Promise.prototype.done = function (didFulfill, didReject) { - var promise = - this._then(didFulfill, didReject, undefined, undefined, undefined); - promise._setIsFinal(); - }; - - Promise.prototype.spread = function (fn) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - return this.all()._then(fn, undefined, undefined, APPLY, undefined); - }; - - Promise.prototype.toJSON = function () { - var ret = { - isFulfilled: false, - isRejected: false, - fulfillmentValue: undefined, - rejectionReason: undefined - }; - if (this.isFulfilled()) { - ret.fulfillmentValue = this.value(); - ret.isFulfilled = true; - } else if (this.isRejected()) { - ret.rejectionReason = this.reason(); - ret.isRejected = true; - } - return ret; - }; - - Promise.prototype.all = function () { - if (arguments.length > 0) { - this._warn(".all() was passed arguments but it does not take any"); - } - return 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 - : false; - var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); - if (result === errorObj) { - ret._rejectCallback(result.e, true); - } - if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); - return ret; - }; - - Promise.all = function (promises) { - return new PromiseArray(promises).promise(); - }; - - Promise.cast = function (obj) { - var ret = tryConvertToPromise(obj); - if (!(ret instanceof Promise)) { - ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._setFulfilled(); - ret._rejectionHandler0 = obj; - } - return ret; - }; - - Promise.resolve = Promise.fulfilled = Promise.cast; - - Promise.reject = Promise.rejected = function (reason) { - var ret = new Promise(INTERNAL); - ret._captureStackTrace(); - ret._rejectCallback(reason, true); - return ret; - }; - - Promise.setScheduler = function(fn) { - if (typeof fn !== "function") { - 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 = internalData !== undefined; - var promise = haveInternalData ? internalData : new Promise(INTERNAL); - var target = this._target(); - var bitField = target._bitField; - - if (!haveInternalData) { - promise._propagateFrom(this, 3); - promise._captureStackTrace(); - if (receiver === undefined && - ((this._bitField & 2097152) !== 0)) { - if (!((bitField & 50397184) === 0)) { - receiver = this._boundValue(); - } else { - receiver = target === this ? undefined : this._boundTo; - } - } - this._fireEvent("promiseChained", this, promise); - } - - var domain = getDomain(); - if (!((bitField & 50397184) === 0)) { - var handler, value, settler = target._settlePromiseCtx; - if (((bitField & 33554432) !== 0)) { - value = target._rejectionHandler0; - handler = didFulfill; - } else if (((bitField & 16777216) !== 0)) { - value = target._fulfillmentHandler0; - handler = didReject; - target._unsetRejectionIsUnhandled(); - } else { - settler = target._settlePromiseLateCancellationObserver; - value = new CancellationError("late cancellation observer"); - target._attachExtraTrace(value); - handler = didReject; - } - - async.invoke(settler, target, { - handler: domain === null ? handler - : (typeof handler === "function" && - 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 this._bitField & 65535; - }; - - Promise.prototype._isFateSealed = function () { - return (this._bitField & 117506048) !== 0; - }; - - Promise.prototype._isFollowing = function () { - return (this._bitField & 67108864) === 67108864; - }; - - Promise.prototype._setLength = function (len) { - this._bitField = (this._bitField & -65536) | - (len & 65535); - }; - - Promise.prototype._setFulfilled = function () { - this._bitField = this._bitField | 33554432; - this._fireEvent("promiseFulfilled", this); - }; - - Promise.prototype._setRejected = function () { - this._bitField = this._bitField | 16777216; - this._fireEvent("promiseRejected", this); - }; - - Promise.prototype._setFollowing = function () { - this._bitField = this._bitField | 67108864; - this._fireEvent("promiseResolved", this); - }; - - Promise.prototype._setIsFinal = function () { - this._bitField = this._bitField | 4194304; - }; - - Promise.prototype._isFinal = function () { - return (this._bitField & 4194304) > 0; - }; - - Promise.prototype._unsetCancelled = function() { - this._bitField = this._bitField & (~65536); - }; - - Promise.prototype._setCancelled = function() { - this._bitField = this._bitField | 65536; - this._fireEvent("promiseCancelled", this); - }; - - Promise.prototype._setWillBeCancelled = function() { - this._bitField = this._bitField | 8388608; - }; - - Promise.prototype._setAsyncGuaranteed = function() { - if (async.hasCustomScheduler()) return; - this._bitField = this._bitField | 134217728; - }; - - Promise.prototype._receiverAt = function (index) { - var ret = index === 0 ? this._receiver0 : this[ - index * 4 - 4 + 3]; - if (ret === UNDEFINED_BINDING) { - return undefined; - } else if (ret === undefined && this._isBound()) { - return this._boundValue(); - } - return ret; - }; - - Promise.prototype._promiseAt = function (index) { - return this[ - index * 4 - 4 + 2]; - }; - - Promise.prototype._fulfillmentHandlerAt = function (index) { - return this[ - index * 4 - 4 + 0]; - }; - - Promise.prototype._rejectionHandlerAt = function (index) { - return this[ - index * 4 - 4 + 1]; - }; - - Promise.prototype._boundValue = function() {}; - - Promise.prototype._migrateCallback0 = function (follower) { - var bitField = follower._bitField; - var fulfill = follower._fulfillmentHandler0; - var reject = follower._rejectionHandler0; - var promise = follower._promise0; - var receiver = follower._receiverAt(0); - if (receiver === undefined) receiver = UNDEFINED_BINDING; - this._addCallbacks(fulfill, reject, promise, receiver, null); - }; - - Promise.prototype._migrateCallbackAt = function (follower, index) { - var fulfill = follower._fulfillmentHandlerAt(index); - var reject = follower._rejectionHandlerAt(index); - var promise = follower._promiseAt(index); - var receiver = follower._receiverAt(index); - if (receiver === undefined) 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 >= 65535 - 4) { - index = 0; - this._setLength(0); - } - - if (index === 0) { - this._promise0 = promise; - this._receiver0 = receiver; - if (typeof fulfill === "function") { - this._fulfillmentHandler0 = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this._rejectionHandler0 = - domain === null ? reject : util.domainBind(domain, reject); - } - } else { - var base = index * 4 - 4; - this[base + 2] = promise; - this[base + 3] = receiver; - if (typeof fulfill === "function") { - this[base + 0] = - domain === null ? fulfill : util.domainBind(domain, fulfill); - } - if (typeof reject === "function") { - this[base + 1] = - domain === null ? reject : util.domainBind(domain, reject); - } - } - this._setLength(index + 1); - return index; - }; - - Promise.prototype._proxy = function (proxyable, arg) { - this._addCallbacks(undefined, undefined, arg, proxyable, null); - }; - - Promise.prototype._resolveCallback = function(value, shouldBind) { - if (((this._bitField & 117506048) !== 0)) return; - if (value === this) - return this._rejectCallback(makeSelfResolutionError(), false); - var maybePromise = tryConvertToPromise(value, this); - if (!(maybePromise instanceof Promise)) return this._fulfill(value); - - if (shouldBind) this._propagateFrom(maybePromise, 2); - - var promise = maybePromise._target(); - - if (promise === this) { - this._reject(makeSelfResolutionError()); - return; - } - - var bitField = promise._bitField; - if (((bitField & 50397184) === 0)) { - var len = this._length(); - if (len > 0) promise._migrateCallback0(this); - for (var i = 1; i < len; ++i) { - promise._migrateCallbackAt(this, i); - } - this._setFollowing(); - this._setLength(0); - this._setFollowee(promise); - } else if (((bitField & 33554432) !== 0)) { - this._fulfill(promise._value()); - } else if (((bitField & 16777216) !== 0)) { - this._reject(promise._reason()); - } else { - var reason = new CancellationError("late cancellation observer"); - promise._attachExtraTrace(reason); - this._reject(reason); - } - }; - - Promise.prototype._rejectCallback = - function(reason, synchronous, ignoreNonErrorWarnings) { - var trace = util.ensureErrorObject(reason); - var hasStack = trace === reason; - if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { - var message = "a promise was rejected with a non-error: " + - util.classString(reason); - this._warn(message, true); - } - this._attachExtraTrace(trace, synchronous ? hasStack : false); - this._reject(reason); - }; - - Promise.prototype._resolveFromExecutor = function (executor) { - var promise = this; - this._captureStackTrace(); - this._pushContext(); - var synchronous = true; - var r = this._execute(executor, function(value) { - promise._resolveCallback(value); - }, function (reason) { - promise._rejectCallback(reason, synchronous); - }); - synchronous = false; - this._popContext(); - - if (r !== undefined) { - promise._rejectCallback(r, true); - } - }; - - Promise.prototype._settlePromiseFromHandler = function ( - handler, receiver, value, promise - ) { - var bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - promise._pushContext(); - var x; - if (receiver === APPLY) { - if (!value || typeof value.length !== "number") { - x = errorObj; - x.e = new TypeError("cannot .spread() a non-array: " + - util.classString(value)); - } else { - x = tryCatch(handler).apply(this._boundValue(), value); - } - } else { - x = tryCatch(handler).call(receiver, value); - } - var promiseCreated = promise._popContext(); - bitField = promise._bitField; - if (((bitField & 65536) !== 0)) return; - - if (x === NEXT_FILTER) { - promise._reject(value); - } else if (x === errorObj) { - promise._rejectCallback(x.e, false); - } else { - debug.checkForgottenReturns(x, promiseCreated, "", promise, this); - promise._resolveCallback(x); - } - }; - - Promise.prototype._target = function() { - var ret = this; - while (ret._isFollowing()) ret = ret._followee(); - return ret; - }; - - Promise.prototype._followee = function() { - return this._rejectionHandler0; - }; - - Promise.prototype._setFollowee = function(promise) { - this._rejectionHandler0 = promise; - }; - - Promise.prototype._settlePromise = function(promise, handler, receiver, value) { - var isPromise = promise instanceof Promise; - var bitField = this._bitField; - var asyncGuaranteed = ((bitField & 134217728) !== 0); - if (((bitField & 65536) !== 0)) { - if (isPromise) promise._invokeInternalOnCancel(); - - if (receiver instanceof PassThroughHandlerContext && - receiver.isFinallyHandler()) { - receiver.cancelPromise = promise; - if (tryCatch(handler).call(receiver, value) === errorObj) { - promise._reject(errorObj.e); - } - } else if (handler === reflectHandler) { - promise._fulfill(reflectHandler.call(receiver)); - } else if (receiver instanceof Proxyable) { - receiver._promiseCancelled(promise); - } else if (isPromise || promise instanceof PromiseArray) { - promise._cancel(); - } else { - receiver.cancel(); - } - } else if (typeof handler === "function") { - if (!isPromise) { - handler.call(receiver, value, promise); - } else { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (receiver instanceof Proxyable) { - if (!receiver._isResolved()) { - if (((bitField & 33554432) !== 0)) { - receiver._promiseFulfilled(value, promise); - } else { - receiver._promiseRejected(value, promise); - } - } - } else if (isPromise) { - if (asyncGuaranteed) promise._setAsyncGuaranteed(); - if (((bitField & 33554432) !== 0)) { - promise._fulfill(value); - } else { - promise._reject(value); - } - } - }; - - Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { - var handler = ctx.handler; - var promise = ctx.promise; - var receiver = ctx.receiver; - var value = ctx.value; - if (typeof handler === "function") { - if (!(promise instanceof Promise)) { - handler.call(receiver, value, promise); - } else { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - } else if (promise instanceof Promise) { - promise._reject(value); - } - }; - - Promise.prototype._settlePromiseCtx = function(ctx) { - this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); - }; - - Promise.prototype._settlePromise0 = function(handler, value, bitField) { - var promise = this._promise0; - var receiver = this._receiverAt(0); - this._promise0 = undefined; - this._receiver0 = undefined; - this._settlePromise(promise, handler, receiver, value); - }; - - Promise.prototype._clearCallbackDataAtIndex = function(index) { - var base = index * 4 - 4; - this[base + 2] = - this[base + 3] = - this[base + 0] = - this[base + 1] = undefined; - }; - - Promise.prototype._fulfill = function (value) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - if (value === this) { - var err = makeSelfResolutionError(); - this._attachExtraTrace(err); - return this._reject(err); - } - this._setFulfilled(); - this._rejectionHandler0 = value; - - if ((bitField & 65535) > 0) { - if (((bitField & 134217728) !== 0)) { - this._settlePromises(); - } else { - async.settlePromises(this); - } - } - }; - - Promise.prototype._reject = function (reason) { - var bitField = this._bitField; - if (((bitField & 117506048) >>> 16)) return; - this._setRejected(); - this._fulfillmentHandler0 = reason; - - if (this._isFinal()) { - return async.fatalError(reason, util.isNode); - } - - if ((bitField & 65535) > 0) { - async.settlePromises(this); - } else { - this._ensurePossibleRejectionHandled(); - } - }; - - Promise.prototype._fulfillPromises = function (len, value) { - for (var i = 1; i < len; i++) { - var handler = this._fulfillmentHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, value); - } - }; - - Promise.prototype._rejectPromises = function (len, reason) { - for (var i = 1; i < len; i++) { - var handler = this._rejectionHandlerAt(i); - var promise = this._promiseAt(i); - var receiver = this._receiverAt(i); - this._clearCallbackDataAtIndex(i); - this._settlePromise(promise, handler, receiver, reason); - } - }; - - Promise.prototype._settlePromises = function () { - var bitField = this._bitField; - var len = (bitField & 65535); - - if (len > 0) { - if (((bitField & 16842752) !== 0)) { - 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; - if (((bitField & 33554432) !== 0)) { - return this._rejectionHandler0; - } else if (((bitField & 16777216) !== 0)) { - return this._fulfillmentHandler0; - } - }; - - function deferResolve(v) {this.promise._resolveCallback(v);} - function deferReject(v) {this.promise._rejectCallback(v, false);} - - 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); - function fillTypes(value) { - var p = new Promise(INTERNAL); - p._fulfillmentHandler0 = value; - p._rejectionHandler0 = value; - p._promise0 = value; - p._receiver0 = value; - } - // Complete slack tracking, opt out of field-type tracking and - // stabilize map - fillTypes({a: 1}); - fillTypes({b: 2}); - fillTypes({c: 3}); - fillTypes(1); - fillTypes(function(){}); - fillTypes(undefined); - fillTypes(false); - fillTypes(new Promise(INTERNAL)); - debug.setBounds(Async.firstLineError, util.lastLineError); - return 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){ - "use strict"; - module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { - var util = _dereq_("./util"); - var isArray = util.isArray; - - function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - } - } - - function PromiseArray(values) { - var promise = this._promise = new Promise(INTERNAL); - if (values instanceof Promise) { - promise._propagateFrom(values, 3); - } - promise._setOnCancel(this); - this._values = values; - this._length = 0; - this._totalResolved = 0; - this._init(undefined, -2); - } - 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; - ; - this._values = values; - - if (((bitField & 50397184) === 0)) { - this._promise._setAsyncGuaranteed(); - return values._then( - init, - this._reject, - undefined, - this, - resolveValueIfEmpty - ); - } else if (((bitField & 33554432) !== 0)) { - values = values._value(); - } else if (((bitField & 16777216) !== 0)) { - return this._reject(values._reason()); - } else { - return this._cancel(); - } - } - values = util.asArray(values); - if (values === null) { - var err = apiRejection( - "expecting an array or an iterable object but got " + util.classString(values)).reason(); - this._promise._rejectCallback(err, false); - return; - } - - if (values.length === 0) { - if (resolveValueIfEmpty === -5) { - this._resolveEmptyArray(); - } - else { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - } - return; - } - 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; - var result = this._promise; - var isResolved = false; - var bitField = null; - for (var i = 0; i < len; ++i) { - var maybePromise = tryConvertToPromise(values[i], result); - - if (maybePromise instanceof Promise) { - maybePromise = maybePromise._target(); - bitField = maybePromise._bitField; - } else { - bitField = null; - } - - if (isResolved) { - if (bitField !== null) { - maybePromise.suppressUnhandledRejections(); - } - } else if (bitField !== null) { - if (((bitField & 50397184) === 0)) { - maybePromise._proxy(this, i); - this._values[i] = maybePromise; - } else if (((bitField & 33554432) !== 0)) { - isResolved = this._promiseFulfilled(maybePromise._value(), i); - } else if (((bitField & 16777216) !== 0)) { - isResolved = this._promiseRejected(maybePromise._reason(), i); - } else { - isResolved = this._promiseCancelled(i); - } - } else { - isResolved = this._promiseFulfilled(maybePromise, i); - } - } - if (!isResolved) result._setAsyncGuaranteed(); - }; - - PromiseArray.prototype._isResolved = function () { - return this._values === null; - }; - - PromiseArray.prototype._resolve = function (value) { - this._values = null; - this._promise._fulfill(value); - }; - - PromiseArray.prototype._cancel = function() { - if (this._isResolved() || !this._promise._isCancellable()) return; - this._values = null; - this._promise._cancel(); - }; - - PromiseArray.prototype._reject = function (reason) { - this._values = null; - this._promise._rejectCallback(reason, false); - }; - - PromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; - }; - - PromiseArray.prototype._promiseCancelled = function() { - this._cancel(); - return true; - }; - - PromiseArray.prototype._promiseRejected = function (reason) { - this._totalResolved++; - this._reject(reason); - return true; - }; - - PromiseArray.prototype._resultCancelled = function() { - if (this._isResolved()) return; - var values = this._values; - this._cancel(); - if (values instanceof Promise) { - values.cancel(); - } else { - for (var i = 0; i < values.length; ++i) { - if (values[i] instanceof Promise) { - values[i].cancel(); - } - } - } - }; - - PromiseArray.prototype.shouldCopyValues = function () { - return true; - }; - - PromiseArray.prototype.getActualLength = function (len) { - return len; - }; - - return PromiseArray; - }; - - },{"./util":36}],24:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL) { - var THIS = {}; - var util = _dereq_("./util"); - var nodebackForPromise = _dereq_("./nodeback"); - var withAppended = util.withAppended; - var maybeWrapAsError = util.maybeWrapAsError; - var canEvaluate = util.canEvaluate; - var TypeError = _dereq_("./errors").TypeError; - var defaultSuffix = "Async"; - var defaultPromisified = {__isPromisified__: true}; - var noCopyProps = [ - "arity", "length", - "name", - "arguments", - "caller", - "callee", - "prototype", - "__isPromisified__" - ]; - var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); - - var defaultFilter = function(name) { - return util.isIdentifier(name) && - name.charAt(0) !== "_" && - name !== "constructor"; - }; - - function propsFilter(key) { - return !noCopyPropsPattern.test(key); - } - - function isPromisified(fn) { - try { - return fn.__isPromisified__ === true; - } - catch (e) { - return false; - } - } - - function hasPromisified(obj, key, suffix) { - var val = util.getDataPropertyOrDefault(obj, key + suffix, - defaultPromisified); - return val ? isPromisified(val) : false; - } - function checkValid(ret, suffix, suffixRegexp) { - for (var i = 0; i < ret.length; i += 2) { - var key = ret[i]; - if (suffixRegexp.test(key)) { - var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); - for (var j = 0; j < ret.length; j += 2) { - if (ret[j] === keyWithoutAsyncSuffix) { - throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" - .replace("%s", suffix)); - } - } - } - } - } - - function promisifiableMethods(obj, suffix, suffixRegexp, filter) { - var keys = util.inheritedDataKeys(obj); - var ret = []; - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - var value = obj[key]; - var passesDefaultFilter = filter === defaultFilter - ? true : defaultFilter(key, value, obj); - if (typeof value === "function" && - !isPromisified(value) && - !hasPromisified(obj, key, suffix) && - filter(key, value, obj, passesDefaultFilter)) { - ret.push(key, value); - } - } - checkValid(ret, suffix, suffixRegexp); - return ret; - } - - var escapeIdentRegex = function(str) { - return str.replace(/([$])/, "\\$"); - }; - - var makeNodePromisifiedEval; - if (false) { - var switchCaseArgumentOrder = function(likelyArgumentCount) { - var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 3); - for(var i = likelyArgumentCount - 1; i >= min; --i) { - ret.push(i); - } - for(var i = likelyArgumentCount + 1; i <= 3; ++i) { - ret.push(i); - } - return ret; - }; - - var argumentSequence = function(argumentCount) { - return util.filledRange(argumentCount, "_arg", ""); - }; - - var parameterDeclaration = function(parameterCount) { - return util.filledRange( - Math.max(parameterCount, 3), "_arg", ""); - }; - - var parameterCount = function(fn) { - if (typeof fn.length === "number") { - return Math.max(Math.min(fn.length, 1023 + 1), 0); - } - return 0; - }; - - makeNodePromisifiedEval = - function(callback, receiver, originalName, fn, _, multiArgs) { - var newParameterCount = Math.max(0, parameterCount(fn) - 1); - var argumentOrder = switchCaseArgumentOrder(newParameterCount); - var shouldProxyThis = typeof callback === "string" || receiver === THIS; - - function generateCallForArgumentCount(count) { - var args = argumentSequence(count).join(", "); - var comma = count > 0 ? ", " : ""; - var ret; - if (shouldProxyThis) { - ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; - } else { - ret = receiver === undefined - ? "ret = callback({{args}}, nodeback); break;\n" - : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; - } - return ret.replace("{{args}}", args).replace(", ", comma); - } - - function generateArgumentSwitchCase() { - var ret = ""; - for (var i = 0; i < argumentOrder.length; ++i) { - ret += "case " + argumentOrder[i] +":" + - generateCallForArgumentCount(argumentOrder[i]); - } - - ret += " \n\ - default: \n\ - var args = new Array(len + 1); \n\ - var i = 0; \n\ - for (var i = 0; i < len; ++i) { \n\ - args[i] = arguments[i]; \n\ - } \n\ - args[i] = nodeback; \n\ - [CodeForCall] \n\ - break; \n\ - ".replace("[CodeForCall]", (shouldProxyThis - ? "ret = callback.apply(this, args);\n" - : "ret = callback.apply(receiver, args);\n")); - return ret; - } - - var getFunctionCode = typeof callback === "string" - ? ("this != null ? this['"+callback+"'] : fn") - : "fn"; - var body = "'use strict'; \n\ - var ret = function (Parameters) { \n\ - 'use strict'; \n\ - var len = arguments.length; \n\ - var promise = new Promise(INTERNAL); \n\ - promise._captureStackTrace(); \n\ - var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ - var ret; \n\ - var callback = tryCatch([GetFunctionCode]); \n\ - switch(len) { \n\ - [CodeForSwitchCase] \n\ - } \n\ - if (ret === errorObj) { \n\ - promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ - } \n\ - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ - return promise; \n\ - }; \n\ - notEnumerableProp(ret, '__isPromisified__', true); \n\ - return ret; \n\ - ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) - .replace("[GetFunctionCode]", getFunctionCode); - body = body.replace("Parameters", parameterDeclaration(newParameterCount)); - return new Function("Promise", - "fn", - "receiver", - "withAppended", - "maybeWrapAsError", - "nodebackForPromise", - "tryCatch", - "errorObj", - "notEnumerableProp", - "INTERNAL", - body)( - Promise, - fn, - receiver, - withAppended, - maybeWrapAsError, - nodebackForPromise, - util.tryCatch, - util.errorObj, - util.notEnumerableProp, - INTERNAL); - }; - } - - function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { - var defaultThis = (function() {return this;})(); - var method = callback; - if (typeof method === "string") { - callback = fn; - } - function promisified() { - var _receiver = receiver; - if (receiver === THIS) _receiver = this; - var promise = new Promise(INTERNAL); - promise._captureStackTrace(); - var cb = typeof method === "string" && this !== defaultThis - ? this[method] : callback; - var fn = nodebackForPromise(promise, multiArgs); - try { - cb.apply(_receiver, withAppended(arguments, fn)); - } catch(e) { - promise._rejectCallback(maybeWrapAsError(e), true, true); - } - if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); - return promise; - } - util.notEnumerableProp(promisified, "__isPromisified__", true); - return promisified; - } - - var makeNodePromisified = canEvaluate - ? makeNodePromisifiedEval - : makeNodePromisifiedClosure; - - function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { - var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); - var methods = - promisifiableMethods(obj, suffix, suffixRegexp, filter); - - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var promisifiedKey = key + suffix; - if (promisifier === makeNodePromisified) { - obj[promisifiedKey] = - makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); - } else { - var promisified = promisifier(fn, function() { - return makeNodePromisified(key, THIS, key, - fn, suffix, multiArgs); - }); - util.notEnumerableProp(promisified, "__isPromisified__", true); - obj[promisifiedKey] = promisified; - } - } - util.toFastProperties(obj); - return obj; - } - - function promisify(callback, receiver, multiArgs) { - return makeNodePromisified(callback, receiver, undefined, - callback, null, multiArgs); - } - - Promise.promisify = function (fn, options) { - if (typeof fn !== "function") { - throw new TypeError("expecting a function but got " + util.classString(fn)); - } - if (isPromisified(fn)) { - return fn; - } - options = Object(options); - var receiver = options.context === undefined ? THIS : options.context; - var multiArgs = !!options.multiArgs; - var ret = promisify(fn, receiver, multiArgs); - util.copyDescriptors(fn, ret, propsFilter); - return ret; - }; - - Promise.promisifyAll = function (target, options) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - options = Object(options); - var multiArgs = !!options.multiArgs; - var suffix = options.suffix; - if (typeof suffix !== "string") suffix = defaultSuffix; - var filter = options.filter; - if (typeof filter !== "function") filter = defaultFilter; - var promisifier = options.promisifier; - if (typeof promisifier !== "function") promisifier = makeNodePromisified; - - if (!util.isIdentifier(suffix)) { - throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - - var keys = util.inheritedDataKeys(target); - for (var i = 0; i < keys.length; ++i) { - var value = target[keys[i]]; - if (keys[i] !== "constructor" && - util.isClass(value)) { - promisifyAll(value.prototype, suffix, filter, promisifier, - multiArgs); - promisifyAll(value, suffix, filter, promisifier, multiArgs); - } - } - - return promisifyAll(target, suffix, filter, promisifier, multiArgs); - }; - }; - - - },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { - var util = _dereq_("./util"); - var isObject = util.isObject; - var es5 = _dereq_("./es5"); - var Es6Map; - if (typeof Map === "function") Es6Map = Map; - - var mapToEntries = (function() { - var index = 0; - var size = 0; - - function extractEntry(value, key) { - this[index] = value; - this[index + size] = key; - index++; - } - - return function mapToEntries(map) { - size = map.size; - index = 0; - var ret = new Array(map.size * 2); - map.forEach(extractEntry, ret); - return ret; - }; - })(); - - var entriesToMap = function(entries) { - var ret = new Es6Map(); - var length = entries.length / 2 | 0; - for (var i = 0; i < length; ++i) { - var key = entries[length + i]; - var value = entries[i]; - ret.set(key, value); - } - return ret; - }; - - function PropertiesPromiseArray(obj) { - var isMap = false; - var entries; - if (Es6Map !== undefined && obj instanceof Es6Map) { - entries = mapToEntries(obj); - isMap = true; - } else { - var keys = es5.keys(obj); - var len = keys.length; - entries = new Array(len * 2); - for (var i = 0; i < len; ++i) { - var key = keys[i]; - entries[i] = obj[key]; - entries[i + len] = key; - } - } - this.constructor$(entries); - this._isMap = isMap; - this._init$(undefined, -3); - } - util.inherits(PropertiesPromiseArray, PromiseArray); - - PropertiesPromiseArray.prototype._init = function () {}; - - PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { - this._values[index] = value; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - var val; - if (this._isMap) { - val = entriesToMap(this._values); - } else { - val = {}; - var keyOffset = this.length(); - for (var i = 0, len = this.length(); i < len; ++i) { - val[this._values[i + keyOffset]] = this._values[i]; - } - } - this._resolve(val); - return true; - } - return false; - }; - - PropertiesPromiseArray.prototype.shouldCopyValues = function () { - return false; - }; - - PropertiesPromiseArray.prototype.getActualLength = function (len) { - return len >> 1; - }; - - function props(promises) { - var ret; - var castValue = tryConvertToPromise(promises); - - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } else if (castValue instanceof Promise) { - ret = castValue._then( - Promise.props, undefined, undefined, undefined, undefined); - } else { - ret = new PropertiesPromiseArray(castValue).promise(); - } - - if (castValue instanceof Promise) { - ret._propagateFrom(castValue, 2); - } - return ret; - } - - Promise.prototype.props = function () { - return props(this); - }; - - Promise.props = function (promises) { - return props(promises); - }; - }; - - },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ - "use strict"; - function arrayMove(src, srcIndex, dst, dstIndex, len) { - for (var j = 0; j < len; ++j) { - dst[j + dstIndex] = src[j + srcIndex]; - src[j + srcIndex] = void 0; - } - } - - function Queue(capacity) { - this._capacity = capacity; - this._length = 0; - this._front = 0; - } - - Queue.prototype._willBeOverCapacity = function (size) { - return this._capacity < size; - }; - - Queue.prototype._pushOne = function (arg) { - var length = this.length(); - this._checkCapacity(length + 1); - var i = (this._front + length) & (this._capacity - 1); - this[i] = arg; - this._length = length + 1; - }; - - Queue.prototype._unshiftOne = function(value) { - var capacity = this._capacity; - this._checkCapacity(this.length() + 1); - var front = this._front; - var i = (((( front - 1 ) & - ( capacity - 1) ) ^ capacity ) - capacity ); - this[i] = value; - this._front = i; - this._length = this.length() + 1; - }; - - Queue.prototype.unshift = function(fn, receiver, arg) { - this._unshiftOne(arg); - this._unshiftOne(receiver); - this._unshiftOne(fn); - }; - - Queue.prototype.push = function (fn, receiver, arg) { - var length = this.length() + 3; - if (this._willBeOverCapacity(length)) { - this._pushOne(fn); - this._pushOne(receiver); - this._pushOne(arg); - return; - } - var j = this._front + length - 3; - this._checkCapacity(length); - var wrapMask = this._capacity - 1; - this[(j + 0) & wrapMask] = fn; - this[(j + 1) & wrapMask] = receiver; - this[(j + 2) & wrapMask] = arg; - this._length = length; - }; - - Queue.prototype.shift = function () { - var front = this._front, - ret = this[front]; - - this[front] = undefined; - this._front = (front + 1) & (this._capacity - 1); - this._length--; - return ret; - }; - - Queue.prototype.length = function () { - return this._length; - }; - - Queue.prototype._checkCapacity = function (size) { - if (this._capacity < size) { - this._resizeTo(this._capacity << 1); - } - }; - - Queue.prototype._resizeTo = function (capacity) { - var oldCapacity = this._capacity; - this._capacity = capacity; - var front = this._front; - var length = this._length; - var moveItemsCount = (front + length) & (oldCapacity - 1); - arrayMove(this, 0, this, oldCapacity, moveItemsCount); - }; - - module.exports = Queue; - - },{}],27:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { - var util = _dereq_("./util"); - - var raceLater = function (promise) { - return promise.then(function(array) { - return race(array, promise); - }); - }; - - function race(promises, parent) { - var maybePromise = tryConvertToPromise(promises); - - if (maybePromise instanceof Promise) { - return raceLater(maybePromise); - } else { - promises = util.asArray(promises); - if (promises === null) - return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); - } - - var ret = new Promise(INTERNAL); - if (parent !== undefined) { - ret._propagateFrom(parent, 3); - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; - - if (val === undefined && !(i in promises)) { - continue; - } - - Promise.cast(val)._then(fulfill, reject, undefined, ret, null); - } - return ret; - } - - Promise.race = function (promises) { - return race(promises, undefined); - }; - - Promise.prototype.race = function () { - return race(this, undefined); - }; - - }; - - },{"./util":36}],28:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { - var getDomain = Promise._getDomain; - var util = _dereq_("./util"); - var tryCatch = util.tryCatch; - - function ReductionPromiseArray(promises, fn, initialValue, _each) { - this.constructor$(promises); - var domain = getDomain(); - this._fn = domain === null ? fn : util.domainBind(domain, fn); - if (initialValue !== undefined) { - initialValue = Promise.resolve(initialValue); - initialValue._attachCancellationCallback(this); - } - this._initialValue = initialValue; - this._currentCancellable = null; - if(_each === INTERNAL) { - this._eachValues = Array(this._length); - } else if (_each === 0) { - this._eachValues = null; - } else { - this._eachValues = undefined; - } - this._promise._captureStackTrace(); - this._init$(undefined, -5); - } - util.inherits(ReductionPromiseArray, PromiseArray); - - ReductionPromiseArray.prototype._gotAccum = function(accum) { - if (this._eachValues !== undefined && - this._eachValues !== null && - accum !== INTERNAL) { - this._eachValues.push(accum); - } - }; - - ReductionPromiseArray.prototype._eachComplete = function(value) { - if (this._eachValues !== null) { - this._eachValues.push(value); - } - return this._eachValues; - }; - - ReductionPromiseArray.prototype._init = function() {}; - - ReductionPromiseArray.prototype._resolveEmptyArray = function() { - this._resolve(this._eachValues !== undefined ? this._eachValues - : this._initialValue); - }; - - ReductionPromiseArray.prototype.shouldCopyValues = function () { - return false; - }; - - ReductionPromiseArray.prototype._resolve = function(value) { - this._promise._resolveCallback(value); - this._values = null; - }; - - ReductionPromiseArray.prototype._resultCancelled = function(sender) { - if (sender === this._initialValue) return this._cancel(); - if (this._isResolved()) return; - this._resultCancelled$(); - if (this._currentCancellable instanceof Promise) { - this._currentCancellable.cancel(); - } - if (this._initialValue instanceof Promise) { - this._initialValue.cancel(); - } - }; - - ReductionPromiseArray.prototype._iterate = function (values) { - this._values = values; - var value; - var i; - var length = values.length; - if (this._initialValue !== undefined) { - value = this._initialValue; - i = 0; - } else { - value = Promise.resolve(values[0]); - i = 1; - } - - this._currentCancellable = value; - - if (!value.isRejected()) { - for (; i < length; ++i) { - var ctx = { - accum: null, - value: values[i], - index: i, - length: length, - array: this - }; - value = value._then(gotAccum, undefined, undefined, ctx, undefined); - } - } - - if (this._eachValues !== undefined) { - value = value - ._then(this._eachComplete, undefined, undefined, this, undefined); - } - value._then(completed, completed, undefined, value, this); - }; - - Promise.prototype.reduce = function (fn, initialValue) { - return reduce(this, fn, initialValue, null); - }; - - Promise.reduce = function (promises, fn, initialValue, _each) { - return reduce(promises, fn, initialValue, _each); - }; - - function completed(valueOrReason, array) { - if (this.isFulfilled()) { - array._resolve(valueOrReason); - } else { - array._reject(valueOrReason); - } - } - - function reduce(promises, fn, initialValue, _each) { - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var array = new ReductionPromiseArray(promises, fn, initialValue, _each); - return array.promise(); - } - - function gotAccum(accum) { - this.accum = accum; - this.array._gotAccum(accum); - var value = tryConvertToPromise(this.value, this.array._promise); - if (value instanceof Promise) { - this.array._currentCancellable = value; - return value._then(gotValue, undefined, undefined, this, undefined); - } else { - return gotValue.call(this, value); - } - } - - function gotValue(value) { - var array = this.array; - var promise = array._promise; - var fn = tryCatch(array._fn); - promise._pushContext(); - var ret; - if (array._eachValues !== undefined) { - ret = fn.call(promise._boundValue(), value, this.index, this.length); - } else { - ret = fn.call(promise._boundValue(), - this.accum, value, this.index, this.length); - } - if (ret instanceof Promise) { - array._currentCancellable = ret; - } - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, - promiseCreated, - array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", - promise - ); - return ret; - } - }; - - },{"./util":36}],29:[function(_dereq_,module,exports){ - "use strict"; - var util = _dereq_("./util"); - var schedule; - var noAsyncScheduler = function() { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - }; - var NativePromise = util.getNativePromise(); - if (util.isNode && typeof MutationObserver === "undefined") { - var GlobalSetImmediate = global.setImmediate; - var ProcessNextTick = process.nextTick; - schedule = util.isRecentNode - ? function(fn) { GlobalSetImmediate.call(global, fn); } - : function(fn) { ProcessNextTick.call(process, fn); }; - } else if (typeof NativePromise === "function" && - typeof NativePromise.resolve === "function") { - var nativePromise = NativePromise.resolve(); - schedule = function(fn) { - nativePromise.then(fn); - }; - } else if ((typeof MutationObserver !== "undefined") && - !(typeof window !== "undefined" && - window.navigator && - (window.navigator.standalone || window.cordova))) { - schedule = (function() { - var div = document.createElement("div"); - var opts = {attributes: true}; - var toggleScheduled = false; - var div2 = document.createElement("div"); - var o2 = new MutationObserver(function() { - div.classList.toggle("foo"); - toggleScheduled = false; - }); - o2.observe(div2, opts); - - var scheduleToggle = function() { - if (toggleScheduled) return; - toggleScheduled = true; - div2.classList.toggle("foo"); - }; - - return function schedule(fn) { - var o = new MutationObserver(function() { - o.disconnect(); - fn(); - }); - o.observe(div, opts); - scheduleToggle(); - }; - })(); - } else if (typeof setImmediate !== "undefined") { - schedule = function (fn) { - setImmediate(fn); - }; - } else if (typeof setTimeout !== "undefined") { - schedule = function (fn) { - setTimeout(fn, 0); - }; - } else { - schedule = noAsyncScheduler; - } - module.exports = schedule; - - },{"./util":36}],30:[function(_dereq_,module,exports){ - "use strict"; - module.exports = - function(Promise, PromiseArray, debug) { - var PromiseInspection = Promise.PromiseInspection; - var util = _dereq_("./util"); - - function SettledPromiseArray(values) { - this.constructor$(values); - } - util.inherits(SettledPromiseArray, PromiseArray); - - SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { - this._values[index] = inspection; - var totalResolved = ++this._totalResolved; - if (totalResolved >= this._length) { - this._resolve(this._values); - return true; - } - return false; - }; - - SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { - var ret = new PromiseInspection(); - ret._bitField = 33554432; - ret._settledValueField = value; - return this._promiseResolved(index, ret); - }; - SettledPromiseArray.prototype._promiseRejected = function (reason, index) { - var ret = new PromiseInspection(); - ret._bitField = 16777216; - ret._settledValueField = reason; - return this._promiseResolved(index, ret); - }; - - Promise.settle = function (promises) { - debug.deprecated(".settle()", ".reflect()"); - return new SettledPromiseArray(promises).promise(); - }; - - Promise.prototype.settle = function () { - return Promise.settle(this); - }; - }; - - },{"./util":36}],31:[function(_dereq_,module,exports){ - "use strict"; - module.exports = - function(Promise, PromiseArray, apiRejection) { - var util = _dereq_("./util"); - var RangeError = _dereq_("./errors").RangeError; - var AggregateError = _dereq_("./errors").AggregateError; - var isArray = util.isArray; - var CANCELLATION = {}; - - - function SomePromiseArray(values) { - this.constructor$(values); - this._howMany = 0; - this._unwrap = false; - this._initialized = false; - } - util.inherits(SomePromiseArray, PromiseArray); - - SomePromiseArray.prototype._init = function () { - if (!this._initialized) { - return; - } - if (this._howMany === 0) { - this._resolve([]); - return; - } - this._init$(undefined, -5); - var isArrayResolved = isArray(this._values); - if (!this._isResolved() && - isArrayResolved && - this._howMany > this._canPossiblyFulfill()) { - this._reject(this._getRangeError(this.length())); - } - }; - - SomePromiseArray.prototype.init = function () { - this._initialized = true; - this._init(); - }; - - SomePromiseArray.prototype.setUnwrap = function () { - this._unwrap = true; - }; - - SomePromiseArray.prototype.howMany = function () { - return this._howMany; - }; - - SomePromiseArray.prototype.setHowMany = function (count) { - this._howMany = count; - }; - - SomePromiseArray.prototype._promiseFulfilled = function (value) { - this._addFulfilled(value); - if (this._fulfilled() === this.howMany()) { - this._values.length = this.howMany(); - if (this.howMany() === 1 && this._unwrap) { - this._resolve(this._values[0]); - } else { - this._resolve(this._values); - } - return true; - } - return false; - - }; - SomePromiseArray.prototype._promiseRejected = function (reason) { - this._addRejected(reason); - return this._checkOutcome(); - }; - - SomePromiseArray.prototype._promiseCancelled = function () { - if (this._values instanceof Promise || this._values == null) { - return this._cancel(); - } - this._addRejected(CANCELLATION); - return this._checkOutcome(); - }; - - SomePromiseArray.prototype._checkOutcome = function() { - if (this.howMany() > this._canPossiblyFulfill()) { - var e = new AggregateError(); - for (var i = this.length(); i < this._values.length; ++i) { - if (this._values[i] !== CANCELLATION) { - e.push(this._values[i]); - } - } - if (e.length > 0) { - this._reject(e); - } else { - this._cancel(); - } - return true; - } - return false; - }; - - 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)); - }; - - function some(promises, howMany) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(howMany); - ret.init(); - return promise; - } - - 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){ - "use strict"; - module.exports = function(Promise) { - function PromiseInspection(promise) { - if (promise !== undefined) { - promise = promise._target(); - this._bitField = promise._bitField; - this._settledValueField = promise._isFateSealed() - ? promise._settledValue() : undefined; - } - else { - this._bitField = 0; - this._settledValueField = undefined; - } - } - - 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\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); - }; - - var reason = PromiseInspection.prototype.error = - PromiseInspection.prototype.reason = function () { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - return this._settledValue(); - }; - - var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { - return (this._bitField & 33554432) !== 0; - }; - - var isRejected = PromiseInspection.prototype.isRejected = function () { - return (this._bitField & 16777216) !== 0; - }; - - var isPending = PromiseInspection.prototype.isPending = function () { - return (this._bitField & 50397184) === 0; - }; - - var isResolved = PromiseInspection.prototype.isResolved = function () { - return (this._bitField & 50331648) !== 0; - }; - - PromiseInspection.prototype.isCancelled = function() { - return (this._bitField & 8454144) !== 0; - }; - - Promise.prototype.__isCancelled = function() { - return (this._bitField & 65536) === 65536; - }; - - Promise.prototype._isCancelled = function() { - return this._target().__isCancelled(); - }; - - Promise.prototype.isCancelled = function() { - return (this._target()._bitField & 8454144) !== 0; - }; - - 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(); - target._unsetRejectionIsUnhandled(); - return reason.call(target); - }; - - Promise.prototype._value = function() { - return this._settledValue(); - }; - - Promise.prototype._reason = function() { - this._unsetRejectionIsUnhandled(); - return this._settledValue(); - }; - - Promise.PromiseInspection = PromiseInspection; - }; - - },{}],33:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL) { - var util = _dereq_("./util"); - var errorObj = util.errorObj; - var isObject = util.isObject; - - function tryConvertToPromise(obj, context) { - if (isObject(obj)) { - if (obj instanceof Promise) return obj; - var then = getThen(obj); - if (then === errorObj) { - if (context) context._pushContext(); - var ret = Promise.reject(then.e); - if (context) context._popContext(); - return ret; - } else if (typeof then === "function") { - if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - obj._then( - ret._fulfill, - ret._reject, - undefined, - ret, - null - ); - return ret; - } - return doThenable(obj, then, context); - } - } - return obj; - } - - function doGetThen(obj) { - return obj.then; - } - - function getThen(obj) { - try { - return doGetThen(obj); - } catch (e) { - errorObj.e = e; - return errorObj; - } - } - - var hasProp = {}.hasOwnProperty; - function isAnyBluebirdPromise(obj) { - try { - return hasProp.call(obj, "_promise0"); - } catch (e) { - return false; - } - } - - function doThenable(x, then, context) { - var promise = new Promise(INTERNAL); - var ret = promise; - if (context) context._pushContext(); - promise._captureStackTrace(); - if (context) context._popContext(); - var synchronous = true; - var result = util.tryCatch(then).call(x, resolve, reject); - synchronous = false; - - if (promise && result === errorObj) { - promise._rejectCallback(result.e, true, true); - promise = null; - } - - function resolve(value) { - if (!promise) return; - promise._resolveCallback(value); - promise = null; - } - - function reject(reason) { - if (!promise) return; - promise._rejectCallback(reason, synchronous, true); - promise = null; - } - return ret; - } - - return tryConvertToPromise; - }; - - },{"./util":36}],34:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function(Promise, INTERNAL, debug) { - var util = _dereq_("./util"); - var TimeoutError = Promise.TimeoutError; - - function HandleWrapper(handle) { - this.handle = handle; - } - - HandleWrapper.prototype._resultCancelled = function() { - clearTimeout(this.handle); - }; - - var afterValue = function(value) { return delay(+this).thenReturn(value); }; - var delay = Promise.delay = function (ms, value) { - var ret; - var handle; - if (value !== undefined) { - ret = Promise.resolve(value) - ._then(afterValue, null, null, ms, undefined); - if (debug.cancellation() && value instanceof Promise) { - ret._setOnCancel(value); - } - } else { - ret = new Promise(INTERNAL); - handle = setTimeout(function() { ret._fulfill(); }, +ms); - if (debug.cancellation()) { - ret._setOnCancel(new HandleWrapper(handle)); - } - ret._captureStackTrace(); - } - ret._setAsyncGuaranteed(); - return ret; - }; - - Promise.prototype.delay = function (ms) { - return delay(ms, this); - }; - - var afterTimeout = function (promise, message, parent) { - var err; - if (typeof message !== "string") { - if (message instanceof Error) { - err = message; - } else { - err = new TimeoutError("operation timed out"); - } - } else { - err = new TimeoutError(message); - } - util.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._reject(err); - - if (parent != null) { - parent.cancel(); - } - }; - - function successClear(value) { - clearTimeout(this.handle); - return value; - } - - function failureClear(reason) { - clearTimeout(this.handle); - throw reason; - } - - Promise.prototype.timeout = function (ms, message) { - ms = +ms; - var ret, parent; - - var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { - if (ret.isPending()) { - afterTimeout(ret, message, parent); - } - }, ms)); - - if (debug.cancellation()) { - parent = this.then(); - ret = parent._then(successClear, failureClear, - undefined, handleWrapper, undefined); - ret._setOnCancel(handleWrapper); - } else { - ret = this._then(successClear, failureClear, - undefined, handleWrapper, undefined); - } - - return ret; - }; - - }; - - },{"./util":36}],35:[function(_dereq_,module,exports){ - "use strict"; - module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = _dereq_("./util"); - var TypeError = _dereq_("./errors").TypeError; - var inherits = _dereq_("./util").inherits; - var errorObj = util.errorObj; - var tryCatch = util.tryCatch; - var NULL = {}; - - function thrower(e) { - setTimeout(function(){throw e;}, 0); - } - - function castPreservingDisposable(thenable) { - var maybePromise = tryConvertToPromise(thenable); - if (maybePromise !== thenable && - typeof thenable._isDisposable === "function" && - typeof thenable._getDisposer === "function" && - thenable._isDisposable()) { - maybePromise._setDisposable(thenable._getDisposer()); - } - return maybePromise; - } - function dispose(resources, inspection) { - var i = 0; - var len = resources.length; - var ret = new Promise(INTERNAL); - 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(); - } - iterator(); - return ret; - } - - function Disposer(data, promise, context) { - this._data = data; - this._promise = promise; - this._context = context; - } - - Disposer.prototype.data = function () { - return this._data; - }; - - Disposer.prototype.promise = function () { - return this._promise; - }; - - Disposer.prototype.resource = function () { - if (this.promise().isFulfilled()) { - return this.promise().value(); - } - return NULL; - }; - - Disposer.prototype.tryDispose = function(inspection) { - var resource = this.resource(); - var context = this._context; - if (context !== undefined) context._pushContext(); - var ret = resource !== NULL - ? this.doDispose(resource, inspection) : null; - if (context !== undefined) context._popContext(); - this._promise._unsetDisposable(); - this._data = null; - return ret; - }; - - Disposer.isDisposer = function (d) { - return (d != null && - typeof d.resource === "function" && - typeof d.tryDispose === "function"); - }; - - function FunctionDisposer(fn, promise, context) { - this.constructor$(fn, promise, context); - } - inherits(FunctionDisposer, Disposer); - - FunctionDisposer.prototype.doDispose = function (resource, inspection) { - var fn = this.data(); - return fn.call(resource, resource, inspection); - }; - - function maybeUnwrapDisposer(value) { - if (Disposer.isDisposer(value)) { - this.resources[this.index]._setDisposable(value); - return value.promise(); - } - return value; - } - - function ResourceList(length) { - this.length = length; - this.promise = null; - this[length-1] = null; - } - - ResourceList.prototype._resultCancelled = function() { - var len = this.length; - for (var i = 0; i < len; ++i) { - var item = this[i]; - if (item instanceof Promise) { - item.cancel(); - } - } - }; - - Promise.using = function () { - var len = arguments.length; - if (len < 2) return apiRejection( - "you must pass at least 2 arguments to Promise.using"); - var fn = arguments[len - 1]; - if (typeof fn !== "function") { - return apiRejection("expecting a function but got " + util.classString(fn)); - } - var input; - var spreadArgs = true; - if (len === 2 && Array.isArray(arguments[0])) { - input = arguments[0]; - len = input.length; - spreadArgs = false; - } else { - input = arguments; - len--; - } - var resources = new ResourceList(len); - for (var i = 0; i < len; ++i) { - var resource = input[i]; - if (Disposer.isDisposer(resource)) { - var disposer = resource; - resource = resource.promise(); - resource._setDisposable(disposer); - } else { - var maybePromise = tryConvertToPromise(resource); - if (maybePromise instanceof Promise) { - resource = - maybePromise._then(maybeUnwrapDisposer, null, null, { - resources: resources, - index: i - }, undefined); - } - } - resources[i] = resource; - } - - var reflectedResources = new Array(resources.length); - for (var i = 0; i < reflectedResources.length; ++i) { - reflectedResources[i] = Promise.resolve(resources[i]).reflect(); - } - - var resultPromise = Promise.all(reflectedResources) - .then(function(inspections) { - for (var i = 0; i < inspections.length; ++i) { - var inspection = inspections[i]; - if (inspection.isRejected()) { - errorObj.e = inspection.error(); - return errorObj; - } else if (!inspection.isFulfilled()) { - resultPromise.cancel(); - return; - } - inspections[i] = inspection.value(); - } - promise._pushContext(); - - fn = tryCatch(fn); - var ret = spreadArgs - ? fn.apply(undefined, inspections) : fn(inspections); - var promiseCreated = promise._popContext(); - debug.checkForgottenReturns( - ret, promiseCreated, "Promise.using", promise); - return ret; - }); - - var promise = resultPromise.lastly(function() { - var inspection = new Promise.PromiseInspection(resultPromise); - return dispose(resources, inspection); - }); - resources.promise = promise; - promise._setOnCancel(resources); - return promise; - }; - - Promise.prototype._setDisposable = function (disposer) { - this._bitField = this._bitField | 131072; - this._disposer = disposer; - }; - - Promise.prototype._isDisposable = function () { - return (this._bitField & 131072) > 0; - }; - - Promise.prototype._getDisposer = function () { - return this._disposer; - }; - - Promise.prototype._unsetDisposable = function () { - this._bitField = this._bitField & (~131072); - this._disposer = undefined; - }; - - Promise.prototype.disposer = function (fn) { - if (typeof fn === "function") { - return new FunctionDisposer(fn, this, createContext()); - } - throw new TypeError(); - }; - - }; - - },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ - "use strict"; - var es5 = _dereq_("./es5"); - var canEvaluate = typeof navigator == "undefined"; - - var errorObj = {e: {}}; - var tryCatchTarget; - var globalObject = typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : - typeof global !== "undefined" ? global : - this !== undefined ? this : null; - - function tryCatcher() { - try { - var target = tryCatchTarget; - tryCatchTarget = null; - return target.apply(this, arguments); - } catch (e) { - errorObj.e = e; - return errorObj; - } - } - function tryCatch(fn) { - tryCatchTarget = fn; - return tryCatcher; - } - - var inherits = function(Child, Parent) { - var hasProp = {}.hasOwnProperty; - - function T() { - this.constructor = Child; - this.constructor$ = Parent; - for (var propertyName in Parent.prototype) { - if (hasProp.call(Parent.prototype, propertyName) && - propertyName.charAt(propertyName.length-1) !== "$" - ) { - this[propertyName + "$"] = Parent.prototype[propertyName]; - } - } - } - T.prototype = Parent.prototype; - Child.prototype = new T(); - return Child.prototype; - }; - - - function isPrimitive(val) { - return val == null || val === true || val === false || - typeof val === "string" || typeof val === "number"; - - } - - function isObject(value) { - return typeof value === "function" || - typeof value === "object" && value !== null; - } - - function maybeWrapAsError(maybeError) { - if (!isPrimitive(maybeError)) return maybeError; - - return new Error(safeToString(maybeError)); - } - - function withAppended(target, appendee) { - var len = target.length; - var ret = new Array(len + 1); - var i; - for (i = 0; i < len; ++i) { - ret[i] = target[i]; - } - ret[i] = appendee; - return ret; - } - - function getDataPropertyOrDefault(obj, key, defaultValue) { - if (es5.isES5) { - var desc = Object.getOwnPropertyDescriptor(obj, key); - - if (desc != null) { - return desc.get == null && desc.set == null - ? desc.value - : defaultValue; - } - } else { - return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; - } - } - - function notEnumerableProp(obj, name, value) { - if (isPrimitive(obj)) return obj; - var descriptor = { - value: value, - configurable: true, - enumerable: false, - writable: true - }; - es5.defineProperty(obj, name, descriptor); - return obj; - } - - function thrower(r) { - throw r; - } - - var inheritedDataKeys = (function() { - var excludedPrototypes = [ - Array.prototype, - Object.prototype, - Function.prototype - ]; - - var isExcludedProto = function(val) { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (excludedPrototypes[i] === val) { - return true; - } - } - return false; - }; - - if (es5.isES5) { - var getKeys = Object.getOwnPropertyNames; - return function(obj) { - var ret = []; - var visitedKeys = Object.create(null); - while (obj != null && !isExcludedProto(obj)) { - var keys; - try { - keys = getKeys(obj); - } catch (e) { - return ret; - } - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (visitedKeys[key]) continue; - visitedKeys[key] = true; - var desc = Object.getOwnPropertyDescriptor(obj, key); - if (desc != null && desc.get == null && desc.set == null) { - ret.push(key); - } - } - obj = es5.getPrototypeOf(obj); - } - return ret; - }; - } else { - var hasProp = {}.hasOwnProperty; - return function(obj) { - if (isExcludedProto(obj)) return []; - var ret = []; - - /*jshint forin:false */ - enumeration: for (var key in obj) { - if (hasProp.call(obj, key)) { - ret.push(key); - } else { - for (var i = 0; i < excludedPrototypes.length; ++i) { - if (hasProp.call(excludedPrototypes[i], key)) { - continue enumeration; - } - } - ret.push(key); - } - } - return ret; - }; - } - - })(); - - var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; - function isClass(fn) { - try { - if (typeof fn === "function") { - var keys = es5.names(fn.prototype); - - var hasMethods = es5.isES5 && keys.length > 1; - var hasMethodsOtherThanConstructor = keys.length > 0 && - !(keys.length === 1 && keys[0] === "constructor"); - var hasThisAssignmentAndStaticMethods = - thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; - - if (hasMethods || hasMethodsOtherThanConstructor || - hasThisAssignmentAndStaticMethods) { - return true; - } - } - return false; - } catch (e) { - return false; - } - } - - function toFastProperties(obj) { - /*jshint -W027,-W055,-W031*/ - function FakeConstructor() {} - FakeConstructor.prototype = obj; - var l = 8; - while (l--) new FakeConstructor(); - return obj; - eval(obj); - } - - var rident = /^[a-z$_][a-z$_0-9]*$/i; - function isIdentifier(str) { - return rident.test(str); - } - - function filledRange(count, prefix, suffix) { - var ret = new Array(count); - for(var i = 0; i < count; ++i) { - ret[i] = prefix + i + suffix; - } - return ret; - } - - function safeToString(obj) { - try { - return obj + ""; - } catch (e) { - return "[no string representation]"; - } - } - - function isError(obj) { - return obj !== null && - typeof obj === "object" && - typeof obj.message === "string" && - typeof obj.name === "string"; - } - - function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isOperational", true); - } - catch(ignore) {} - } - - function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || - e["isOperational"] === true); - } - - function canAttachTrace(obj) { - return isError(obj) && es5.propertyIsWritable(obj, "stack"); - } - - var ensureErrorObject = (function() { - if (!("stack" in new Error())) { - return function(value) { - if (canAttachTrace(value)) return value; - try {throw new Error(safeToString(value));} - catch(err) {return err;} - }; - } else { - return function(value) { - if (canAttachTrace(value)) return value; - return new Error(safeToString(value)); - }; - } - })(); - - function classString(obj) { - return {}.toString.call(obj); - } - - function copyDescriptors(from, to, filter) { - var keys = es5.names(from); - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (filter(key)) { - try { - es5.defineProperty(to, key, es5.getDescriptor(from, key)); - } catch (ignore) {} - } - } - } - - var asArray = function(v) { - if (es5.isArray(v)) { - return v; - } - return null; - }; - - if (typeof Symbol !== "undefined" && Symbol.iterator) { - var ArrayFrom = typeof Array.from === "function" ? function(v) { - return Array.from(v); - } : function(v) { - var ret = []; - var it = v[Symbol.iterator](); - var itResult; - while (!((itResult = it.next()).done)) { - ret.push(itResult.value); - } - return ret; - }; - - asArray = function(v) { - if (es5.isArray(v)) { - return v; - } else if (v != null && typeof v[Symbol.iterator] === "function") { - return ArrayFrom(v); - } - return null; - }; - } - - var isNode = typeof process !== "undefined" && - classString(process).toLowerCase() === "[object process]"; - - function env(key, def) { - return isNode ? process.env[key] : def; - } - - function getNativePromise() { - if (typeof Promise === "function") { - try { - var promise = new Promise(function(){}); - if ({}.toString.call(promise) === "[object Promise]") { - return Promise; - } - } catch (e) {} - } - } - - function domainBind(self, cb) { - return self.bind(cb); - } - - var ret = { - isClass: isClass, - isIdentifier: isIdentifier, - inheritedDataKeys: inheritedDataKeys, - getDataPropertyOrDefault: getDataPropertyOrDefault, - thrower: thrower, - isArray: es5.isArray, - asArray: asArray, - notEnumerableProp: notEnumerableProp, - isPrimitive: isPrimitive, - isObject: isObject, - isError: isError, - canEvaluate: canEvaluate, - errorObj: errorObj, - tryCatch: tryCatch, - inherits: inherits, - withAppended: withAppended, - maybeWrapAsError: maybeWrapAsError, - toFastProperties: toFastProperties, - filledRange: filledRange, - toString: safeToString, - canAttachTrace: canAttachTrace, - ensureErrorObject: ensureErrorObject, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - classString: classString, - copyDescriptors: copyDescriptors, - hasDevTools: typeof chrome !== "undefined" && chrome && - typeof chrome.loadTimes === "function", - isNode: isNode, - env: env, - global: globalObject, - getNativePromise: getNativePromise, - domainBind: domainBind - }; - ret.isRecentNode = ret.isNode && (function() { - var version = process.versions.node.split(".").map(Number); - return (version[0] === 0 && version[1] > 10) || (version[0] > 0); - })(); - - if (ret.isNode) ret.toFastProperties(process); - - try {throw new Error(); } catch (e) {ret.lastLineError = e;} - module.exports = ret; - - },{"./es5":13}]},{},[4])(4) - }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), (function() { return this; }()), __webpack_require__(3).setImmediate)) - -/***/ }, -/* 2 */ -/***/ function(module, exports) { - - // shim for using process in browser - - var process = module.exports = {}; - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = setTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - clearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - setTimeout(drainQueue, 0); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(setImmediate, clearImmediate) {var nextTick = __webpack_require__(2).nextTick; - var apply = Function.prototype.apply; - var slice = Array.prototype.slice; - var immediateIds = {}; - var nextImmediateId = 0; - - // DOM APIs, for completeness - - exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); - }; - exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); - }; - exports.clearTimeout = - exports.clearInterval = function(timeout) { timeout.close(); }; - - function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; - } - Timeout.prototype.unref = Timeout.prototype.ref = function() {}; - Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); - }; - - // Does not start the time, just sets up the members needed. - exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; - }; - - exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; - }; - - exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } - }; - - // That's not how node.js implements it but the exposed api is the same. - exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; - }; - - exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3).setImmediate, __webpack_require__(3).clearImmediate)) - /***/ } /******/ ]); \ No newline at end of file diff --git a/js/embark.js b/js/embark.js index 903e35b7..93b7e39f 100644 --- a/js/embark.js +++ b/js/embark.js @@ -1,4 +1,4 @@ -var Promise = require('bluebird'); +/*jshint esversion: 6 */ //var Ipfs = require('./ipfs.js'); var EmbarkJS = { @@ -10,7 +10,7 @@ EmbarkJS.Contract = function(options) { this.abi = options.abi; this.address = options.address; - this.code = options.code; + this.code = '0x' + options.code; this.web3 = options.web3 || web3; var ContractClass = this.web3.eth.contract(this.abi); @@ -59,40 +59,73 @@ EmbarkJS.Contract = function(options) { }; return true; } else if (typeof self._originalContractObject[p] === 'function') { - self[p] = Promise.promisify(self._originalContractObject[p]); + self[p] = function(_args) { + var args = Array.prototype.slice.call(arguments); + var fn = self._originalContractObject[p]; + var props = self.abi.find((x) => x.name == p); + + var promise = new Promise(function(resolve, reject) { + args.push(function(err, transaction) { + promise.tx = transaction; + if (err) { + return reject(err); + } + + var getConfirmation = function() { + self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) { + if (err) { + return reject(err); + } + + if (receipt !== null) { + return resolve(receipt); + } + + setTimeout(getConfirmation, 1000); + }); + }; + + if (typeof(transaction) !== "string" || props.constant) { + resolve(transaction); + } else { + getConfirmation(); + } + }); + + fn.apply(fn, args); + }); + + return promise; + }; return true; } return false; }); }; -EmbarkJS.Contract.prototype.deploy = function(args) { +EmbarkJS.Contract.prototype.deploy = function(args, _options) { var self = this; var contractParams; + var options = _options || {}; contractParams = args || []; contractParams.push({ from: this.web3.eth.accounts[0], data: this.code, - gas: 500000, - gasPrice: 10000000000000 + gas: options.gas || 800000 }); var contractObject = this.web3.eth.contract(this.abi); var promise = new Promise(function(resolve, reject) { contractParams.push(function(err, transaction) { - console.log("callback"); if (err) { - console.log("error"); reject(err); } else if (transaction.address !== undefined) { - console.log("address contract: " + transaction.address); resolve(new EmbarkJS.Contract({abi: self.abi, code: self.code, address: transaction.address})); } }); - console.log(contractParams); // returns promise // deploys contract @@ -109,13 +142,14 @@ EmbarkJS.IPFS = 'ipfs'; EmbarkJS.Storage = { }; -// EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) -//{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 +157,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 +181,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 +208,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) { @@ -186,20 +230,45 @@ EmbarkJS.Storage.getUrl = function(hash) { EmbarkJS.Messages = { }; -EmbarkJS.Messages.setProvider = function(provider) { +EmbarkJS.Messages.setProvider = function(provider, options) { + var self = this; + var ipfs; if (provider === 'whisper') { this.currentMessages = EmbarkJS.Messages.Whisper; + if (typeof variable === 'undefined') { + if (options === undefined) { + web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); + } else { + web3 = new Web3(new Web3.providers.HttpProvider("http://" + options.server + ':' + options.port)); + } + } + web3.version.getWhisper(function(err, res) { + if (err) { + console.log("whisper not available"); + } else { + self.currentMessages.identity = web3.shh.newIdentity(); + } + }); + } 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 = { @@ -208,9 +277,10 @@ 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; + var _topics; if (topics === undefined) { throw new Error("missing option: topic"); @@ -222,42 +292,41 @@ 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 }; - return web3.shh.post(message); + return web3.shh.post(message, function() {}); }; EmbarkJS.Messages.Whisper.listenTo = function(options) { var topics = options.topic || options.topics; + var _topics = []; if (typeof topics === 'string') { - topics = [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 @@ -275,17 +344,102 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) { return err; }; + messageEvents.prototype.stop = function() { + this.filter.stopWatching(); + }; + var promise = new messageEvents(); 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, + data: payload, + from: result.from, + time: (new Date(result.sent * 1000)) + }; + promise.cb(payload, data, result); } }); + promise.filter = filter; + + 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"); + } + + if (typeof topics === 'string') { + topics = topics; + } else { + // TODO: better to just send to different channels instead + topics = topics.join(','); + } + + 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; + + if (typeof topics === 'string') { + topics = topics; + } else { + topics = topics.join(','); + } + + this.orbit.join(topics); + + 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', (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: channel, + data: post.content, + from: post.meta.from.name, + time: (new Date(post.meta.ts)) + }; + promise.cb(post.content, data, post); + }); + }); + return promise; }; 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/js/web3.js b/js/web3.js index c3417254..b576349a 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.2" } },{}],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!'); @@ -2960,6 +2936,8 @@ var ContractFactory = function (eth, abi) { * @returns {Contract} returns contract instance */ this.new = function () { + /*jshint maxcomplexity: 7 */ + var contract = new Contract(this.eth, this.abi); // parse arguments @@ -2976,6 +2954,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 +3104,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 +3320,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 +3370,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 +3503,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 +3523,7 @@ var Filter = function (requestManager, options, methods, formatter, callback) { self.callbacks.forEach(function(cb){ cb(error); }); + filterCreationErrorCallback(error); } else { self.filterId = id; @@ -3571,11 +3562,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 +3624,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 +3691,7 @@ var inputCallFormatter = function (options){ options[key] = utils.fromDecimal(options[key]); }); - return options; + return options; }; /** @@ -3721,12 +3716,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 +3740,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 +3766,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 +3794,7 @@ var outputBlockFormatter = function(block) { /** * Formats the output of a log - * + * * @method outputLogFormatter * @param {Object} log object * @returns {Object} log @@ -3840,7 +3835,7 @@ var inputPostFormatter = function(post) { return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); }); - return post; + return post; }; /** @@ -3892,6 +3887,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 +3952,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 +4027,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 +4055,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 +4127,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 }; }; @@ -4187,31 +4201,27 @@ module.exports = SolidityFunction; * @date 2015 */ -"use strict"; 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 // 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 } +var XHR2 = require('xhr2'); // 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 +4232,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 +4267,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 +4281,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 +4331,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 +4359,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 +4789,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 +4806,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 +4828,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 +4847,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 +5408,10 @@ var properties = function () { name: 'blockNumber', getter: 'eth_blockNumber', outputFormatter: utils.toDecimal + }), + new Property({ + name: 'protocolVersion', + getter: 'eth_protocolVersion' }) ]; }; @@ -5421,7 +5440,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 +5494,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 +5555,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 +5572,7 @@ var methods = function () { return [ newAccount, unlockAccount, + sendTransaction, lockAccount ]; }; @@ -5562,7 +5589,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 +5677,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 +5940,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 +5981,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 +6022,7 @@ Property.prototype.setRequestManager = function (rm) { /** * Should be called to format input args of method - * + * * @method formatInput * @param {Array} * @return {Array} @@ -5865,7 +6039,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 +6058,7 @@ Property.prototype.extractCallback = function (args) { /** * Should attach function to method - * + * * @method attachToObject * @param {Object} * @param {Function} @@ -5892,7 +6066,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 +6090,7 @@ Property.prototype.buildGet = function () { return function get() { return property.formatOutput(property.requestManager.send({ method: property.getter - })); + })); }; }; @@ -5953,7 +6127,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 +6184,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 +6206,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 +6232,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 +6347,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 +6380,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 +6394,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 +6405,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 +6500,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 +6594,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 +6690,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 +6829,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 +7705,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 +7725,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 +7758,7 @@ module.exports = transfer; * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { - function F() {} + return { /** @@ -7583,8 +7781,7 @@ module.exports = transfer; */ extend: function (overrides) { // Spawn - F.prototype = this; - var subtype = new F(); + var subtype = create(this); // Augment if (overrides) { @@ -7592,7 +7789,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 +8466,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 +8557,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 +8752,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 +8885,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 +8952,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 +9096,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 +9115,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 +9192,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 +9461,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 +9540,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 +9657,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 +9716,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 +9757,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 +9812,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 +9862,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 +9907,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 +9948,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 +9979,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 +10025,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 +10171,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 +10362,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 +10555,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 +10695,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 +10963,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 +11114,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 +11195,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 +11395,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 +11719,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 +11803,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 +12127,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 +12898,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 +13203,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 +13363,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 +13390,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 +13418,7 @@ module.exports = transfer; /*--------------------------------------------------------------------------*/ var utf8 = { - 'version': '2.0.0', + 'version': '2.1.2', 'encode': utf8encode, 'decode': utf8decode }; @@ -13240,6 +13449,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 +16137,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 diff --git a/lib/abi.js b/lib/abi.js deleted file mode 100644 index 5abc6c57..00000000 --- a/lib/abi.js +++ /dev/null @@ -1,52 +0,0 @@ - -var ABIGenerator = function(blockchainConfig, contractsManager) { - this.blockchainConfig = blockchainConfig; - this.contractsManager = contractsManager; - this.rpcHost = blockchainConfig.rpcHost; - this.rpcPort = blockchainConfig.rpcPort; -}; - -ABIGenerator.prototype.generateProvider = function() { - var result = ""; - - result += "\nif (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {"; - result += '\n\tweb3 = new Web3(web3.currentProvider);'; - result += "\n} else if (typeof Web3 !== 'undefined') {"; - result += '\n\tweb3 = new Web3(new Web3.providers.HttpProvider("http://' + this.rpcHost + ':' + this.rpcPort + '"));'; - result += '\n}'; - result += "\nweb3.eth.defaultAccount = web3.eth.accounts[0];"; - - return result; -}; - -ABIGenerator.prototype.generateContracts = function(useEmbarkJS) { - var result = "\n"; - - for(var className in this.contractsManager.contracts) { - var contract = this.contractsManager.contracts[className]; - - var abi = JSON.stringify(contract.abiDefinition); - var gasEstimates = JSON.stringify(contract.gasEstimates); - - if (useEmbarkJS) { - result += "\n" + className + " = new EmbarkJS.Contract({abi: " + abi + ", address: '" + contract.deployedAddress + "', code: '" + contract.code + "', gasEstimates: " + gasEstimates + "});"; - } else { - result += "\n" + className + "Abi = " + abi + ";"; - result += "\n" + className + "Contract = web3.eth.contract(" + className + "Abi);"; - result += "\n" + className + " = " + className + "Contract.at('" + contract.deployedAddress + "');"; - } - } - - return result; -}; - -ABIGenerator.prototype.generateABI = function(options) { - var result = ""; - - result += this.generateProvider(); - result += this.generateContracts(options.useEmbarkJS); - - return result; -}; - -module.exports = ABIGenerator; diff --git a/lib/cmd.js b/lib/cmd.js index 91dcf314..a3440b97 100644 --- a/lib/cmd.js +++ b/lib/cmd.js @@ -1,9 +1,10 @@ var program = require('commander'); var colors = require('colors'); +var shelljs = require('shelljs'); var Cmd = function(Embark) { this.Embark = Embark; - program.version('2.1.4'); + program.version(Embark.version); }; Cmd.prototype.process = function(args) { @@ -14,8 +15,14 @@ Cmd.prototype.process = function(args) { this.blockchain(); this.simulator(); this.test(); - this.ipfs(); + this.upload(); this.otherCommands(); + + //If no arguments are passed display help by default + if (!process.argv.slice(2).length) { + program.help(); + } + program.parse(args); }; @@ -29,7 +36,7 @@ Cmd.prototype.newApp = function() { console.log("please specify your app Name".red); console.log("e.g embark new MyApp".green); console.log("e.g embark new --help for more information".green); - exit(); + process.exit(code); } self.Embark.generateTemplate('boilerplate', './', name); }); @@ -51,10 +58,7 @@ Cmd.prototype.build = function() { .command('build [environment]') .description('deploy and build dapp at dist/ (default: development)') .action(function(env, options) { - self.Embark.initConfig(env || 'development', { - embarkConfig: 'embark.json' - }); - self.Embark.build(env || 'development'); + self.Embark.build({env: env || 'development'}); }); }; @@ -62,13 +66,20 @@ 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)') + .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', { - embarkConfig: 'embark.json' + self.Embark.run({ + env: env || 'development', + serverPort: options.port, + serverHost: options.host, + runWebserver: !options.noserver, + useDashboard: !options.nodashboard }); - self.Embark.run({env: env || 'development', serverPort: options.port}); }); }; @@ -80,41 +91,27 @@ Cmd.prototype.blockchain = function() { .description('run blockchain server (default: development)') .action(function(env ,options) { self.Embark.initConfig(env || 'development', { - embarkConfig: 'embark.json' + embarkConfig: 'embark.json', + interceptLogs: false }); self.Embark.blockchain(env || 'development', options.client || 'geth'); }); }; Cmd.prototype.simulator = function() { + var self = this; program - .command('simulator') + .command('simulator [environment]') .description('run a fast ethereum rpc simulator') .option('--testrpc', 'use testrpc as the rpc simulator [default]') - .option('--ethersim', 'use ethersim as the rpc simulator') - .action(function(options) { - var Sim; - - if (options.ethersim) { - try { - Sim = require('ethersim'); - } catch(e) { - console.log('EtherSim not found; Please install it with "npm install ethersim --save"'); - console.log('For more information see https://github.com/iurimatias/ethersim'); - process.exit(1); - } - Sim.startServer(); - } - else { - try { - Sim = require('ethereumjs-testrpc'); - } catch(e) { - console.log('TestRPC not found; Please install it with "npm install -g ethereumjs-testrpc'); - console.log('For more information see https://github.com/ethereumjs/testrpc'); - process.exit(1); - } - exec('testrpc'); - } + .option('-p, --port [port]', 'port to run the rpc simulator (default: 8000)') + .option('-h, --host [host]', 'host to run the rpc simulator (default: localhost)') + .action(function(env, options) { + self.Embark.initConfig(env || 'development', { + embarkConfig: 'embark.json', + interceptLogs: false + }); + self.Embark.simulator({port: options.port, host: options.host}); }); }; @@ -123,17 +120,21 @@ Cmd.prototype.test = function() { .command('test') .description('run tests') .action(function() { - exec('mocha test/ --no-timeouts'); + shelljs.exec('mocha test/ --no-timeouts'); }); }; -Cmd.prototype.ipfs = function() { +Cmd.prototype.upload = function() { var self = this; program - .command('ipfs') - .description('deploy to IPFS') - .action(function() { - self.Embark.ipfs(); + .command('upload [platform] [environment]') + .description('upload your dapp to a decentralized storage. possible options: ipfs, swarm (e.g embark upload swarm)') + .action(function(platform, env, options) { + // TODO: get env in cmd line as well + self.Embark.initConfig(env || 'development', { + embarkConfig: 'embark.json', interceptLogs: false + }); + self.Embark.upload(platform); }); }; @@ -141,6 +142,8 @@ Cmd.prototype.otherCommands = function() { program .action(function(env){ console.log('unknown command "%s"'.red, env); + console.log("type embark --help to see the available commands"); + process.exit(0); }); }; diff --git a/lib/blockchain.js b/lib/cmds/blockchain/blockchain.js similarity index 65% rename from lib/blockchain.js rename to lib/cmds/blockchain/blockchain.js index 32fe06e5..e83167bc 100644 --- a/lib/blockchain.js +++ b/lib/cmds/blockchain/blockchain.js @@ -1,12 +1,18 @@ -var mkdirp = require('mkdirp'); -var wrench = require('wrench'); var colors = require('colors'); +var shelljs = require('shelljs'); + +var fs = require('../../core/fs.js'); + var GethCommands = require('./geth_commands.js'); -var Blockchain = function(blockchainConfig, Client) { - this.blockchainConfig = blockchainConfig; +/*eslint complexity: ["error", 22]*/ +var Blockchain = function(options) { + this.blockchainConfig = options.blockchainConfig; + this.env = options.env || 'development'; + this.client = options.client; this.config = { + geth_bin: this.blockchainConfig.geth_bin || 'geth', networkType: this.blockchainConfig.networkType || 'custom', genesisBlock: this.blockchainConfig.genesisBlock || false, datadir: this.blockchainConfig.datadir || false, @@ -18,43 +24,44 @@ 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, + maxpeers: ((this.blockchainConfig.maxpeers === 0) ? 0 : (this.blockchainConfig.maxpeers || 25)), + bootnodes: this.blockchainConfig.bootnodes || "", + rpcApi: (this.blockchainConfig.rpcApi || ['eth', 'web3', 'net']), + vmdebug: this.blockchainConfig.vmdebug || false }; - if (this.blockchainConfig.whisper === false) { - this.config.whisper = false; - } else { - this.config.whisper = (this.blockchainConfig.whisper || true); - } - - this.client = new Client({config: this.config}); + this.client = new options.client({config: this.config, env: this.env}); }; Blockchain.prototype.runCommand = function(cmd) { console.log(("running: " + cmd.underline).green); - return exec(cmd); + return shelljs.exec(cmd); }; Blockchain.prototype.run = function() { + var self = this; console.log("===============================================================================".magenta); console.log("===============================================================================".magenta); console.log(("Embark Blockchain Using: " + this.client.name.underline).magenta); console.log("===============================================================================".magenta); console.log("===============================================================================".magenta); var address = this.initChainAndGetAddress(); - var mainCommand = this.client.mainCommand(address); - this.runCommand(mainCommand); + this.client.mainCommand(address, function(cmd) { + self.runCommand(cmd); + }); }; Blockchain.prototype.initChainAndGetAddress = function() { var address = null, result; // ensure datadir exists, bypassing the interactive liabilities prompt. - this.datadir = '.embark/development/datadir'; - mkdirp.sync(this.datadir); + this.datadir = '.embark/' + this.env + '/datadir'; + fs.mkdirpSync(this.datadir); // copy mining script - wrench.copyDirSyncRecursive(__dirname + "/../js", ".embark/development/js", {forceDelete: true}); + fs.copySync(fs.embarkPath("js"), ".embark/" + this.env + "/js", {overwrite: true}); // check if an account already exists, create one if not, return address result = this.runCommand(this.client.listAccountsCommand()); @@ -75,9 +82,9 @@ Blockchain.prototype.initChainAndGetAddress = function() { return address; }; -var BlockchainClient = function(blockchainConfig, client) { +var BlockchainClient = function(blockchainConfig, client, env) { if (client === 'geth') { - return new Blockchain(blockchainConfig, GethCommands); + return new Blockchain({blockchainConfig: blockchainConfig, client: GethCommands, env: env}); } else { throw new Error('unknown client'); } diff --git a/lib/cmds/blockchain/geth_commands.js b/lib/cmds/blockchain/geth_commands.js new file mode 100644 index 00000000..f89c325a --- /dev/null +++ b/lib/cmds/blockchain/geth_commands.js @@ -0,0 +1,164 @@ +var async = require('async'); + +// TODO: make all of this async +var GethCommands = function(options) { + this.config = options.config; + this.env = options.env || 'development'; + this.name = "Go-Ethereum (https://github.com/ethereum/go-ethereum)"; + this.geth_bin = this.config.geth_bin || "geth"; +}; + +GethCommands.prototype.commonOptions = function() { + var config = this.config; + var cmd = ""; + + cmd += this.determineNetworkType(config); + + if (config.datadir) { + cmd += "--datadir=\"" + config.datadir + "\" "; + } + + if (config.light) { + cmd += "--light "; + } + + if (config.fast) { + cmd += "--fast "; + } + + if (config.account && config.account.password) { + cmd += "--password " + config.account.password + " "; + } + + return cmd; +}; + +GethCommands.prototype.determineNetworkType = function(config) { + var cmd = ""; + if (config.networkType === 'testnet') { + cmd += "--testnet "; + } else if (config.networkType === 'olympic') { + cmd += "--olympic "; + } else if (config.networkType === 'custom') { + cmd += "--networkid " + config.networkId + " "; + } + return cmd; +}; + +GethCommands.prototype.initGenesisCommmand = function() { + var config = this.config; + var cmd = this.geth_bin + " " + this.commonOptions(); + + if (config.genesisBlock) { + cmd += "init \"" + config.genesisBlock + "\" "; + } + + return cmd; +}; + +GethCommands.prototype.newAccountCommand = function() { + return this.geth_bin + " " + this.commonOptions() + "account new "; +}; + +GethCommands.prototype.listAccountsCommand = function() { + return this.geth_bin + " " + this.commonOptions() + "account list "; +}; + +GethCommands.prototype.determineRpcOptions = function(config) { + var cmd = ""; + + cmd += "--port " + config.port + " "; + cmd += "--rpc "; + cmd += "--rpcport " + config.rpcPort + " "; + cmd += "--rpcaddr " + config.rpcHost + " "; + if (config.rpcCorsDomain) { + if (config.rpcCorsDomain === '*') { + console.log('=================================='); + console.log('make sure you know what you are doing'); + console.log('=================================='); + } + cmd += "--rpccorsdomain=\"" + config.rpcCorsDomain + "\" "; + } else { + console.log('=================================='); + console.log('warning: cors is not set'); + console.log('=================================='); + } + + return cmd; +}; + +GethCommands.prototype.mainCommand = function(address, done) { + var self = this; + var config = this.config; + var rpc_api = (this.config.rpcApi || ['eth', 'web3', 'net']); + + async.series([ + function commonOptions(callback) { + var cmd = self.commonOptions(); + callback(null, cmd); + }, + function rpcOptions(callback) { + var cmd = self.determineRpcOptions(self.config); + callback(null, cmd); + }, + function dontGetPeers(callback) { + if (config.nodiscover) { + return callback(null, "--nodiscover"); + } + callback(null, ""); + }, + function vmDebug(callback) { + if (config.vmdebug) { + return callback(null, "--vmdebug"); + } + callback(null, ""); + }, + function maxPeers(callback) { + var cmd = "--maxpeers " + config.maxpeers; + callback(null, cmd); + }, + function mining(callback) { + if (config.mineWhenNeeded || config.mine) { + return callback(null, "--mine "); + } + callback(""); + }, + function bootnodes(callback) { + if (config.bootnodes && config.bootnodes !== "" && config.bootnodes !== []) { + return callback(null, "--bootnodes " + config.bootnodes); + } + callback(""); + }, + function whisper(callback) { + if (config.whisper) { + rpc_api.push('shh'); + return callback(null, "--shh "); + } + callback(""); + }, + function rpcApi(callback) { + callback(null, '--rpcapi "' + rpc_api.join(',') + '"'); + }, + function accountToUnlock(callback) { + var accountAddress = config.account.address || address; + if (accountAddress) { + return callback(null, "--unlock=" + accountAddress); + } + callback(null, ""); + }, + function mineWhenNeeded(callback) { + if (config.mineWhenNeeded) { + return callback(null, "js .embark/" + self.env + "/js/mine.js"); + } + callback(null, ""); + } + ], function(err, results) { + if (err) { + throw new Error(err.message); + } + done(self.geth_bin + " " + results.join(" ")); + }); +}; + +module.exports = GethCommands; + diff --git a/lib/cmds/simulator.js b/lib/cmds/simulator.js new file mode 100644 index 00000000..47554c12 --- /dev/null +++ b/lib/cmds/simulator.js @@ -0,0 +1,18 @@ +var shelljs = require('shelljs'); + +var Simulator = function(options) { + this.blockchainConfig = options.blockchainConfig; +}; + +Simulator.prototype.run = function(options) { + var cmds = []; + + cmds.push("-p " + (this.blockchainConfig.rpcPort || options.port || 8545)); + cmds.push("-h " + (this.blockchainConfig.rpcHost || options.host || 'localhost')); + cmds.push("-a " + (options.num || 10)); + + shelljs.exec('testrpc ' + cmds.join(' ')); +}; + +module.exports = Simulator; + diff --git a/lib/cmds/template_generator.js b/lib/cmds/template_generator.js new file mode 100644 index 00000000..a0aa482f --- /dev/null +++ b/lib/cmds/template_generator.js @@ -0,0 +1,32 @@ +var fs = require('../core/fs.js'); +var utils = require('../core/utils.js'); + +var TemplateGenerator = function(templateName) { + this.templateName = templateName; +}; + +TemplateGenerator.prototype.generate = function(destinationFolder, name) { + var templatePath = fs.embarkPath(this.templateName); + console.log('Initializing Embark Template....'.green); + + fs.copySync(templatePath, destinationFolder + name); + utils.cd(destinationFolder + name); + utils.sed('package.json', '%APP_NAME%', name); + + console.log('Installing packages.. this can take a few seconds'.green); + utils.runCmd('npm install'); + console.log('Init complete'.green); + console.log('\nApp ready at '.green + destinationFolder + name); + + if (name === 'embark_demo') { + console.log('-------------------'.yellow); + console.log('Next steps:'.green); + console.log(('-> ' + ('cd ' + destinationFolder + name).bold.cyan).green); + console.log('-> '.green + 'embark blockchain'.bold.cyan + ' or '.green + 'embark simulator'.bold.cyan); + console.log('open another console in the same directory and run'.green); + console.log('-> '.green + 'embark run'.bold.cyan); + console.log('For more info go to http://github.com/iurimatias/embark-framework'.green); + } +}; + +module.exports = TemplateGenerator; diff --git a/lib/compiler.js b/lib/compiler.js deleted file mode 100644 index 7a7cb0c4..00000000 --- a/lib/compiler.js +++ /dev/null @@ -1,112 +0,0 @@ -var shelljs = require('shelljs'); -var shelljs_global = require('shelljs/global'); -var fs = require('fs'); -var solc = require('solc'); - -var Compiler = function() { -}; - -Compiler.prototype.compile_solidity = function(contractFiles) { - var input = {}; - - for (var i = 0; i < contractFiles.length; i++){ - // TODO: this depends on the config - var filename = contractFiles[i].filename.replace('app/contracts/',''); - input[filename] = contractFiles[i].content.toString(); - } - - var output = solc.compile({sources: input}, 1); - - if (output.errors) { - throw new Error ("Solidity errors: " + output.errors); - } - - var json = output.contracts; - - compiled_object = {}; - - for (var className in json) { - var contract = json[className]; - - compiled_object[className] = {}; - compiled_object[className].code = contract.bytecode; - compiled_object[className].runtimeBytecode = contract.runtimeBytecode; - compiled_object[className].gasEstimates = contract.gasEstimates; - compiled_object[className].functionHashes = contract.functionHashes; - compiled_object[className].abiDefinition = JSON.parse(contract.interface); - } - - return compiled_object; -}; - -Compiler.prototype.compile_serpent = function(contractFiles) { - var cmd, result, output, json, compiled_object; - - //TODO: figure out how to compile multiple files and get the correct json - var contractFile = contractFiles[0]; - - cmd = "serpent compile " + contractFile; - - result = exec(cmd, {silent: true}); - code = result.output; - - if (result.code === 1) { - throw new Error(result.output); - } - - cmd = "serpent mk_full_signature " + contractFile; - result = exec(cmd, {silent: true}); - - if (result.code === 1) { - throw new Error(result.output); - } - - json = JSON.parse(result.output.trim()); - className = contractFile.split('.')[0].split("/").pop(); - - for (var i=0; i < json.length; i++) { - var elem = json[i]; - - if (elem.outputs.length > 0) { - elem.constant = true; - } - } - - compiled_object = {}; - compiled_object[className] = {}; - compiled_object[className].code = code.trim(); - compiled_object[className].info = {}; - compiled_object[className].abiDefinition = json; - - return compiled_object; -}; - -Compiler.prototype.compile = function(contractFiles) { - var solidity = [], serpent = []; - - for (var i = 0; i < contractFiles.length; i++) { - var contractParts = contractFiles[i].split('.'), - extension = contractParts[contractParts.length-1]; - - if (extension === 'sol') { - solidity.push(contractFiles[i]); - } - else if (extension === 'se') { - serpent.push(contractFiles[i]); - } - else { - throw new Error("extension not known, got " + extension); - } - } - - var contracts = []; - if (solidity.length > 0) { - contracts.concat(this.compile_solidity(solidity)); - } - if (serpent.length > 0) { - contracts.concat(this.compile_serpent(serpent)); - } - return contracts; -}; - -module.exports = Compiler; diff --git a/lib/config.js b/lib/config.js deleted file mode 100644 index bb06a942..00000000 --- a/lib/config.js +++ /dev/null @@ -1,97 +0,0 @@ -var fs = require('fs'); -var grunt = require('grunt'); -var merge = require('merge'); - -// TODO: add wrapper for fs so it can also work in the browser -// can work with both read and save -var Config = function(options) { - this.env = options.env; - this.blockchainConfig = {}; - this.contractsConfig = {}; - this.pipelineConfig = {}; - this.chainTracker = {}; - this.assetFiles = {}; - this.contractsFiles = []; - this.configDir = options.configDir || 'config/'; - this.chainsFile = options.chainsFile || './chains.json'; -}; - -Config.prototype.loadConfigFiles = function(options) { - this.embarkConfig = JSON.parse(fs.readFileSync(options.embarkConfig)); - - this.loadPipelineConfigFile(); - this.loadBlockchainConfigFile(); - this.loadContractsConfigFile(); - this.loadChainTrackerFile(); -}; - -Config.prototype.reloadConfig = function() { - this.loadPipelineConfigFile(); - this.loadBlockchainConfigFile(); - this.loadContractsConfigFile(); - this.loadChainTrackerFile(); -}; - -Config.prototype.loadBlockchainConfigFile = function() { - var defaultBlockchainConfig = JSON.parse(fs.readFileSync(this.configDir + "blockchain.json"))[this.env]; - this.blockchainConfig = defaultBlockchainConfig; -}; - -Config.prototype.loadContractsConfigFile = function() { - var contractsConfig = JSON.parse(fs.readFileSync(this.configDir + "contracts.json")); - var defaultContractsConfig = contractsConfig['default']; - var envContractsConfig = contractsConfig[this.env]; - - var mergedConfig = merge.recursive(defaultContractsConfig, envContractsConfig); - this.contractsConfig = mergedConfig; -}; - -Config.prototype.loadPipelineConfigFile = function() { - var contracts = this.embarkConfig.contracts; - this.contractsFiles = this.loadFiles(contracts); - - var assets = this.embarkConfig.app; - for(var targetFile in assets) { - this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]); - } - - this.buildDir = this.embarkConfig.buildDir; - this.configDir = this.embarkConfig.config; -}; - -Config.prototype.loadChainTrackerFile = function() { - //var self = this; - var chainTracker; - try { - chainTracker = JSON.parse(fs.readFileSync(this.chainsFile)); - } - catch(err) { - //self.logger.info(this.chainsFile + ' file not found, creating it...'); - chainTracker = {}; - fs.writeFileSync(this.chainsFile, '{}'); - } - this.chainTracker = chainTracker; -}; - -Config.prototype.loadFiles = function(files) { - var originalFiles = grunt.file.expand({nonull: true}, files); - var readFiles = []; - - originalFiles.filter(function(file) { - 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()}); - } else { - readFiles.push({filename: file, content: fs.readFileSync(file).toString()}); - } - }); - - return readFiles; -}; - -module.exports = Config; diff --git a/lib/console.js b/lib/console.js deleted file mode 100644 index 69e56ed2..00000000 --- a/lib/console.js +++ /dev/null @@ -1,35 +0,0 @@ -var Web3 = require('web3'); - -var Console = function(options) { -}; - -Console.prototype.runCode = function(code) { - eval(code); // jshint ignore:line -}; - -Console.prototype.executeCmd = function(cmd, callback) { - if (cmd === 'help') { - var helpText = [ - 'Welcome to Embark 2', - '', - 'possible commands are:', - 'quit - to immediatly exit', - '', - 'The web3 object and the interfaces for the deployed contrats and their methods are also available' - ]; - return callback(helpText.join('\n')); - } else if (cmd === 'quit') { - exit(); - } - - try { - var result = eval(cmd); // jshint ignore:line - return callback(result); - } - catch(e) { - return callback(e.message.red); - } -}; - -module.exports = Console; - diff --git a/lib/contracts.js b/lib/contracts.js deleted file mode 100644 index c8f5c245..00000000 --- a/lib/contracts.js +++ /dev/null @@ -1,214 +0,0 @@ -var Compiler = require('./compiler.js'); -var toposort = require('toposort'); - -// TODO: create a contract object - -var ContractsManager = function(options) { - this.contractFiles = options.contractFiles; - this.contractsConfig = options.contractsConfig; - this.contracts = {}; - this.logger = options.logger; - - this.contractDependencies = {}; -}; - -ContractsManager.prototype.compileContracts = function() { - var compiler = new Compiler(); - 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; - } - // 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; - - this.contracts[className] = contract; - } - - // 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; - } - - if (parentContract === undefined) { - this.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) { - 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] = []; - } - this.contractDependencies[className].push(arg.substr(1)); - } - } - } - -}; - -ContractsManager.prototype.getContract = function(className) { - return this.contracts[className]; -}; - -ContractsManager.prototype.sortContracts = function(contractList) { - var converted_dependencies = [], i; - - for(var contract in this.contractDependencies) { - var dependencies = this.contractDependencies[contract]; - for(i=0; i < dependencies.length; i++) { - converted_dependencies.push([contract, dependencies[i]]); - } - } - - var orderedDependencies = toposort(converted_dependencies).reverse(); - - var newList = contractList.sort(function(a,b) { - var order_a = orderedDependencies.indexOf(a.className); - var order_b = orderedDependencies.indexOf(b.className); - return order_a - order_b; - }); - - return newList; -}; - -// TODO: should be built contracts -ContractsManager.prototype.listContracts = function() { - var contracts = []; - for(var className in this.contracts) { - var contract = this.contracts[className]; - contracts.push(contract); - } - return this.sortContracts(contracts); -}; - -ContractsManager.prototype.contractsState = function() { - var data = []; - - for(var className in this.contracts) { - var contract = this.contracts[className]; - - var contractData; - - if (contract.deploy === false) { - contractData = [ - className.green, - 'Interface or set to not deploy'.green, - "\t\tn/a".green - ]; - } else if (contract.error) { - contractData = [ - className.green, - (contract.error).red, - '\t\tError'.red - ]; - } else { - contractData = [ - className.green, - (contract.deployedAddress || '...').green, - ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta) - ]; - } - - data.push(contractData); - } - - return data; -}; - -module.exports = ContractsManager; diff --git a/lib/contracts/abi.js b/lib/contracts/abi.js new file mode 100644 index 00000000..479b9f77 --- /dev/null +++ b/lib/contracts/abi.js @@ -0,0 +1,117 @@ + +var ABIGenerator = function(options) { + this.blockchainConfig = options.blockchainConfig || {}; + this.storageConfig = options.storageConfig || {}; + this.communicationConfig = options.communicationConfig || {}; + this.contractsManager = options.contractsManager; + this.rpcHost = options.blockchainConfig && options.blockchainConfig.rpcHost; + this.rpcPort = options.blockchainConfig && options.blockchainConfig.rpcPort; + this.plugins = options.plugins; +}; + +ABIGenerator.prototype.generateProvider = function() { + var self = this; + var result = ""; + var providerPlugins; + + if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) { + return ""; + } + + if (this.plugins) { + providerPlugins = this.plugins.getPluginsFor('clientWeb3Provider'); + } + + if (this.plugins && providerPlugins.length > 0) { + providerPlugins.forEach(function(plugin) { + result += plugin.generateProvider(self) + "\n"; + }); + } else { + result += "\nif (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {"; + result += '\n\tweb3 = new Web3(web3.currentProvider);'; + result += "\n} else if (typeof Web3 !== 'undefined') {"; + result += '\n\tweb3 = new Web3(new Web3.providers.HttpProvider("http://' + this.rpcHost + ':' + this.rpcPort + '"));'; + result += '\n}'; + result += "\nweb3.eth.defaultAccount = web3.eth.accounts[0];"; + } + + return result; +}; + +ABIGenerator.prototype.generateContracts = function(useEmbarkJS) { + var self = this; + var result = "\n"; + var contractsPlugins; + + if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) { + return ""; + } + + if (this.plugins) { + contractsPlugins = this.plugins.getPluginsFor('contractGeneration'); + } + + if (this.plugins && contractsPlugins.length > 0) { + contractsPlugins.forEach(function(plugin) { + result += plugin.generateContracts({contracts: self.contractsManager.contracts}); + }); + } else { + for(var className in this.contractsManager.contracts) { + var contract = this.contractsManager.contracts[className]; + + var abi = JSON.stringify(contract.abiDefinition); + var gasEstimates = JSON.stringify(contract.gasEstimates); + + if (useEmbarkJS) { + result += "\n" + className + " = new EmbarkJS.Contract({abi: " + abi + ", address: '" + contract.deployedAddress + "', code: '" + contract.code + "', gasEstimates: " + gasEstimates + "});"; + } else { + result += "\n" + className + "Abi = " + abi + ";"; + result += "\n" + className + "Contract = web3.eth.contract(" + className + "Abi);"; + result += "\n" + className + " = " + className + "Contract.at('" + contract.deployedAddress + "');"; + } + } + } + + return result; +}; + +ABIGenerator.prototype.generateStorageInitialization = function(useEmbarkJS) { + var self = this; + var result = "\n"; + + if (!useEmbarkJS || self.storageConfig === {}) return ""; + + if (self.storageConfig.provider === 'ipfs' && self.storageConfig.enabled === true) { + result += "\nEmbarkJS.Storage.setProvider('" + self.storageConfig.provider + "', {server: '" + self.storageConfig.host + "', port: '" + self.storageConfig.port + "'});"; + } + + return result; +}; + +ABIGenerator.prototype.generateCommunicationInitialization = function(useEmbarkJS) { + var self = this; + var result = "\n"; + + if (!useEmbarkJS || self.communicationConfig === {}) return ""; + + if (self.communicationConfig.provider === 'whisper' && self.communicationConfig.enabled === true) { + result += "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "');"; + } else if (self.communicationConfig.provider === 'orbit' && self.communicationConfig.enabled === true) { + result += "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "', {server: '" + self.communicationConfig.host + "', port: '" + self.communicationConfig.port + "'});"; + } + + return result; +}; + +ABIGenerator.prototype.generateABI = function(options) { + var result = ""; + + result += this.generateProvider(); + result += this.generateContracts(options.useEmbarkJS); + result += this.generateStorageInitialization(options.useEmbarkJS); + result += this.generateCommunicationInitialization(options.useEmbarkJS); + + return result; +}; + +module.exports = ABIGenerator; diff --git a/lib/contracts/compiler.js b/lib/contracts/compiler.js new file mode 100644 index 00000000..f7a7c70e --- /dev/null +++ b/lib/contracts/compiler.js @@ -0,0 +1,118 @@ +/*jshint esversion: 6, loopfunc: true */ +var async = require('async'); +var SolcW = require('./solcW.js'); + +function asyncEachObject(object, iterator, callback) { + async.each( + Object.keys(object || {}), + function(key, next){ + iterator(key, object[key], next); + }, + callback + ); +} +async.eachObject = asyncEachObject; + +var Compiler = function(options) { + this.plugins = options.plugins; + this.logger = options.logger; +}; + +Compiler.prototype.compile_contracts = function(contractFiles, cb) { + var self = this; + + var available_compilers = { + //".se": this.compile_serpent + ".sol": this.compile_solidity.bind(this) + }; + + if (this.plugins) { + var compilerPlugins = this.plugins.getPluginsFor('compilers'); + if (compilerPlugins.length > 0) { + compilerPlugins.forEach(function(plugin) { + plugin.compilers.forEach(function(compilerObject) { + available_compilers[compilerObject.extension] = compilerObject.cb; + }); + }); + } + } + + var compiledObject = {}; + + async.eachObject(available_compilers, + function(extension, compiler, callback) { + // TODO: warn about files it doesn't know how to compile + var matchingFiles = contractFiles.filter(function(file) { + return (file.filename.match(/\.[0-9a-z]+$/)[0] === extension); + }); + + compiler.call(compiler, matchingFiles || [], function(err, compileResult) { + Object.assign(compiledObject, compileResult); + callback(err, compileResult); + }); + }, + function (err) { + cb(err, compiledObject); + } + ); +}; + +Compiler.prototype.compile_solidity = function(contractFiles, cb) { + var self = this; + var input = {}; + var solcW; + async.waterfall([ + function prepareInput(callback) { + for (var i = 0; i < contractFiles.length; i++){ + // TODO: this depends on the config + var filename = contractFiles[i].filename.replace('app/contracts/',''); + input[filename] = contractFiles[i].content.toString(); + } + callback(); + }, + function loadCompiler(callback) { + // TODO: there ino need to load this twice + solcW = new SolcW(); + if (solcW.isCompilerLoaded()) { + return callback(); + } + + self.logger.info("loading solc compiler.."); + solcW.load_compiler(function(){ + callback(); + }); + }, + function compileContracts(callback) { + self.logger.info("compiling contracts..."); + solcW.compile({sources: input}, 1, function(output) { + if (output.errors) { + return callback(new Error ("Solidity errors: " + output.errors).message); + } + callback(null, output); + }); + }, + function createCompiledObject(output, callback) { + var json = output.contracts; + + compiled_object = {}; + + for (var className in json) { + var contract = json[className]; + + compiled_object[className] = {}; + compiled_object[className].code = contract.bytecode; + compiled_object[className].runtimeBytecode = contract.runtimeBytecode; + compiled_object[className].realRuntimeBytecode = contract.runtimeBytecode.slice(0, -68); + compiled_object[className].swarmHash = contract.runtimeBytecode.slice(-68).slice(0,64); + compiled_object[className].gasEstimates = contract.gasEstimates; + compiled_object[className].functionHashes = contract.functionHashes; + compiled_object[className].abiDefinition = JSON.parse(contract.interface); + } + callback(null, compiled_object); + } + ], function(err, result) { + cb(err, result); + }); +}; + +module.exports = Compiler; diff --git a/lib/contracts/contracts.js b/lib/contracts/contracts.js new file mode 100644 index 00000000..4123f543 --- /dev/null +++ b/lib/contracts/contracts.js @@ -0,0 +1,247 @@ +var toposort = require('toposort'); +var async = require('async'); + +var Compiler = require('./compiler.js'); + +// TODO: create a contract object + +var adjustGas = function(contract) { + var maxGas, adjustedGas; + if (contract.gas === 'auto') { + if (contract.deploy || contract.deploy === undefined) { + if (contract.gasEstimates.creation !== undefined) { + // TODO: should sum it instead + maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000); + } else { + maxGas = 500000; + } + } else { + maxGas = 500000; + } + // TODO: put a check so it doesn't go over the block limit + adjustedGas = Math.round(maxGas * 1.40); + adjustedGas += 25000; + contract.gas = adjustedGas; + } +}; + +var ContractsManager = function(options) { + this.contractFiles = options.contractFiles; + this.contractsConfig = options.contractsConfig; + this.contracts = {}; + this.logger = options.logger; + this.plugins = options.plugins; + + this.contractDependencies = {}; +}; + +ContractsManager.prototype.build = function(done) { + var self = this; + async.waterfall([ + function compileContracts(callback) { + var compiler = new Compiler({plugins: self.plugins, logger: self.logger}); + compiler.compile_contracts(self.contractFiles, function(err, compiledObject) { + self.compiledContracts = compiledObject; + callback(err); + }); + }, + function prepareContractsFromConfig(callback) { + var className, contract; + for(className in self.contractsConfig.contracts) { + contract = self.contractsConfig.contracts[className]; + + contract.className = className; + contract.args = contract.args || []; + + self.contracts[className] = contract; + } + 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; + for(className in self.compiledContracts) { + compiledContract = self.compiledContracts[className]; + contractConfig = self.contractsConfig.contracts[className]; + + contract = self.contracts[className] || {className: className, args: []}; + + contract.code = compiledContract.code; + contract.runtimeBytecode = compiledContract.runtimeBytecode; + contract.realRuntimeBytecode = (contract.realRuntimeBytecode || contract.runtimeBytecode); + contract.swarmHash = compiledContract.swarmHash; + contract.gasEstimates = compiledContract.gasEstimates; + contract.functionHashes = compiledContract.functionHashes; + contract.abiDefinition = compiledContract.abiDefinition; + + contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas || 'auto'; + adjustGas(contract); + + contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice; + contract.type = 'file'; + contract.className = className; + + self.contracts[className] = contract; + } + callback(); + }, + /*eslint complexity: ["error", 11]*/ + function dealWithSpecialConfigs(callback) { + var className, contract, parentContractName, parentContract; + + for(className in self.contracts) { + contract = self.contracts[className]; + + 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 (parentContract === undefined) { + self.logger.error(className + ": couldn't find instanceOf contract " + parentContractName); + continue; + } + + if (parentContract.args && parentContract.args.length > 0 && ((contract.args && contract.args.length === 0) || contract.args === undefined)) { + 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; + contract.type = 'instance'; + + } + 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] === "$") { + self.contractDependencies[className] = self.contractDependencies[className] || []; + self.contractDependencies[className].push(arg.substr(1)); + } + } + } + callback(); + } + ], function(err, result) { + if (err) { + self.logger.error("Error Compiling/Building contracts: " + err); + } + self.logger.trace("finished".underline); + done(err, self); + }); +}; + +ContractsManager.prototype.getContract = function(className) { + return this.contracts[className]; +}; + +ContractsManager.prototype.sortContracts = function(contractList) { + var converted_dependencies = [], i; + + for(var contract in this.contractDependencies) { + var dependencies = this.contractDependencies[contract]; + for(i=0; i < dependencies.length; i++) { + converted_dependencies.push([contract, dependencies[i]]); + } + } + + var orderedDependencies = toposort(converted_dependencies).reverse(); + + var newList = contractList.sort(function(a,b) { + var order_a = orderedDependencies.indexOf(a.className); + var order_b = orderedDependencies.indexOf(b.className); + return order_a - order_b; + }); + + return newList; +}; + +// TODO: should be built contracts +ContractsManager.prototype.listContracts = function() { + var contracts = []; + for(var className in this.contracts) { + var contract = this.contracts[className]; + contracts.push(contract); + } + return this.sortContracts(contracts); +}; + +ContractsManager.prototype.contractsState = function() { + var data = []; + + for(var className in this.contracts) { + var contract = this.contracts[className]; + + var contractData; + + if (contract.deploy === false) { + contractData = [ + className.green, + 'Interface or set to not deploy'.green, + "\t\tn/a".green + ]; + } else if (contract.error) { + contractData = [ + className.green, + (contract.error).red, + '\t\tError'.red + ]; + } else { + contractData = [ + className.green, + (contract.deployedAddress || '...').green, + ((contract.deployedAddress !== undefined) ? "\t\tDeployed".green : "\t\tPending".magenta) + ]; + } + + data.push(contractData); + } + + return data; +}; + +module.exports = ContractsManager; diff --git a/lib/deploy.js b/lib/contracts/deploy.js similarity index 67% rename from lib/deploy.js rename to lib/contracts/deploy.js index 8c73e565..5e3ae70a 100644 --- a/lib/deploy.js +++ b/lib/contracts/deploy.js @@ -1,8 +1,9 @@ var async = require('async'); -var Compiler = require('./compiler.js'); + +var RunCode = require('../core/runCode.js'); + var DeployTracker = require('./deploy_tracker.js'); var ABIGenerator = require('./abi.js'); -var web3; var Deploy = function(options) { this.web3 = options.web3; @@ -15,6 +16,23 @@ 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); + } + } + + return realArgs; +}; + Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { var self = this; var suppliedArgs; @@ -32,68 +50,41 @@ 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); + self.deployTracker.trackContract(contract.className, contract.realRuntimeBytecode, realArgs, contract.address); self.deployTracker.save(); self.logger.contractsState(self.contractsManager.contractsState()); return callback(); } - var trackedContract = self.deployTracker.getContract(contract.className, contract.code, contract.args); + var trackedContract = self.deployTracker.getContract(contract.className, contract.realRuntimeBytecode, contract.args); if (trackedContract && this.web3.eth.getCode(trackedContract.address) !== "0x") { - self.logger.info(contract.className + " already deployed " + trackedContract.address); + self.logger.info(contract.className.bold.cyan + " already deployed at ".green + trackedContract.address.bold.cyan); contract.deployedAddress = trackedContract.address; self.logger.contractsState(self.contractsManager.contractsState()); - 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) { - self.deployTracker.trackContract(contract.className, contract.code, realArgs, address); + if (err) { + return callback(new Error(err)); + } + self.deployTracker.trackContract(contract.className, contract.realRuntimeBytecode, realArgs, address); self.deployTracker.save(); self.logger.contractsState(self.contractsManager.contractsState()); - // TODO: replace evals with separate process so it's isolated and with - // a callback if (contract.onDeploy !== undefined) { self.logger.info('executing onDeploy commands'); - var abiGenerator = new ABIGenerator({}, self.contractsManager); - web3 = self.web3; + var abiGenerator = new ABIGenerator({contractsManager: self.contractsManager}); var abi = abiGenerator.generateContracts(false); - eval(abi); // jshint ignore:line - var cmds = contract.onDeploy.join(';\n'); - eval(cmds); // jshint ignore:line + + RunCode.doEval(abi + "\n" + cmds, self.web3); } callback(); @@ -109,7 +100,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 @@ -117,29 +110,29 @@ Deploy.prototype.deployContract = function(contract, params, callback) { contractParams.push({ //from: this.web3.eth.coinbase, from: accounts[0], - data: contract.code, + data: "0x" + contract.code, gas: contract.gas, gasPrice: contract.gasPrice }); - self.logger.info("deploying " + contract.className + " with " + contract.gas + " gas"); + self.logger.info("deploying " + contract.className.bold.cyan + " with ".green + contract.gas + " gas".green); contractParams.push(function(err, transaction) { self.logger.contractsState(self.contractsManager.contractsState()); if (err) { - self.logger.error("error deploying contract: " + contract.className); + self.logger.error("error deploying contract: " + contract.className.cyan); var errMsg = err.toString(); if (errMsg === 'Error: The contract code couldn\'t be stored, please check your gas amount.') { errMsg = 'The contract code couldn\'t be stored, out of gas or constructor error'; } 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); + self.logger.info(contract.className.bold.cyan + " deployed at ".green + transaction.address.bold.cyan); contract.deployedAddress = transaction.address; contract.transactionHash = transaction.transactionHash; - callback(null, transaction.address); + return callback(null, transaction.address); } }); @@ -157,7 +150,12 @@ Deploy.prototype.deployAll = function(done) { self.checkAndDeployContract(contract, null, callback); }, function(err, results) { - self.logger.info("finished"); + if (err) { + self.logger.error("error deploying contracts"); + self.logger.error(err.message); + self.logger.debug(err.stack); + } + self.logger.info("finished deploying contracts"); self.logger.trace(arguments); done(); } diff --git a/lib/contracts/deploy_manager.js b/lib/contracts/deploy_manager.js new file mode 100644 index 00000000..0293b97c --- /dev/null +++ b/lib/contracts/deploy_manager.js @@ -0,0 +1,85 @@ +var async = require('async'); +var Web3 = require('web3'); + +var Deploy = require('./deploy.js'); +var ContractsManager = require('./contracts.js'); + +var DeployManager = function(options) { + this.config = options.config; + this.logger = options.logger; + this.blockchainConfig = this.config.blockchainConfig; + this.plugins = options.plugins; + this.events = options.events; + this.web3 = options.web3; + this.chainConfig = (options.trackContracts !== false) ? this.config.chainTracker : false; +}; + +DeployManager.prototype.deployContracts = function(done) { + var self = this; + + if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) { + self.logger.info("Blockchain component is disabled in the config".underline); + self.events.emit('blockchainDisabled', {}); + return done(); + } + + async.waterfall([ + function buildContracts(callback) { + var contractsManager = new ContractsManager({ + contractFiles: self.config.contractsFiles, + contractsConfig: self.config.contractsConfig, + logger: self.logger, + plugins: self.plugins + }); + contractsManager.build(callback); + }, + function connectWithWeb3(contractsManager, callback) { + var web3; + if (self.web3) { + web3 = self.web3; + } else { + web3 = new Web3(); + var web3Endpoint = 'http://' + self.config.blockchainConfig.rpcHost + ':' + self.config.blockchainConfig.rpcPort; + web3.setProvider(new web3.providers.HttpProvider(web3Endpoint)); + if (!web3.isConnected()) { + self.logger.error(("Couldn't connect to " + web3Endpoint.underline + " are you sure it's on?").red); + self.logger.info("make sure you have an ethereum node or simulator running. e.g 'embark blockchain'".magenta); + return callback(Error("error connecting to blockchain node")); + } + } + callback(null, contractsManager, web3); + }, + function setDefaultAccount(contractsManager, web3, callback) { + web3.eth.getAccounts(function(err, accounts) { + if (err) { + return callback(new Error(err)); + } + var accountConfig = self.config.blockchainConfig.account; + var selectedAccount = accountConfig && accountConfig.address; + web3.eth.defaultAccount = (selectedAccount || accounts[0]); + callback(null, contractsManager, web3); + }); + }, + function deployAllContracts(contractsManager, web3, callback) { + var deploy = new Deploy({ + web3: web3, + contractsManager: contractsManager, + logger: self.logger, + chainConfig: self.chainConfig, + env: self.config.env + }); + deploy.deployAll(function() { + self.events.emit('contractsDeployed', contractsManager); + callback(null, contractsManager); + }); + } + ], function(err, result) { + if (err) { + done(err, null); + } else { + done(null, result); + } + }); +}; + +module.exports = DeployManager; diff --git a/lib/deploy_tracker.js b/lib/contracts/deploy_tracker.js similarity index 91% rename from lib/deploy_tracker.js rename to lib/contracts/deploy_tracker.js index 9f446a9c..79152057 100644 --- a/lib/deploy_tracker.js +++ b/lib/contracts/deploy_tracker.js @@ -1,5 +1,4 @@ -var fs = require('fs'); -var prettyJson = require("json-honey"); +var fs = require('../core/fs.js'); var DeployTracker = function(options) { this.logger = options.logger; @@ -12,6 +11,7 @@ var DeployTracker = function(options) { return; } + // TODO: need to make this async var block = this.web3.eth.getBlock(0); var chainId = block.hash; @@ -49,7 +49,7 @@ DeployTracker.prototype.getContract = function(contractName, code, args) { // chainConfig can be an abstract PersistentObject DeployTracker.prototype.save = function() { if (this.chainConfig === false) { return; } - fs.writeFileSync("./chains.json", prettyJson(this.chainConfig)); + fs.writeJSONSync("./chains.json", this.chainConfig); }; module.exports = DeployTracker; diff --git a/lib/contracts/solcP.js b/lib/contracts/solcP.js new file mode 100644 index 00000000..2332091f --- /dev/null +++ b/lib/contracts/solcP.js @@ -0,0 +1,18 @@ +var solc; + +process.on('message', function(msg) { + if (msg.action === 'loadCompiler') { + solc = require('solc'); + process.send({result: "loadedCompiler"}); + } + + if (msg.action === 'compile') { + var output = solc.compile(msg.obj, msg.optimize); + process.send({result: "compilation", output: output}); + } +}); + +process.on('exit', function() { + process.exit(0); +}); + diff --git a/lib/contracts/solcW.js b/lib/contracts/solcW.js new file mode 100644 index 00000000..eec22b10 --- /dev/null +++ b/lib/contracts/solcW.js @@ -0,0 +1,36 @@ +var utils = require('../core/utils.js'); +var solcProcess; +var compilerLoaded = false; + +var SolcW = function() { +}; + +SolcW.prototype.load_compiler = function(done) { + if (compilerLoaded) { done(); } + solcProcess = require('child_process').fork(utils.joinPath(__dirname, '/solcP.js')); + solcProcess.once('message', function(msg) { + if (msg.result !== 'loadedCompiler') { + return; + } + compilerLoaded = true; + done(); + }); + solcProcess.send({action: 'loadCompiler'}); +}; + +SolcW.prototype.isCompilerLoaded = function() { + return (compilerLoaded === true); +}; + +SolcW.prototype.compile = function(obj, optimize, done) { + solcProcess.once('message', function(msg) { + if (msg.result !== 'compilation') { + return; + } + done(msg.output); + }); + solcProcess.send({action: 'compile', obj: obj, optimize: optimize}); +}; + +module.exports = SolcW; + diff --git a/lib/core/config.js b/lib/core/config.js new file mode 100644 index 00000000..3db31a9a --- /dev/null +++ b/lib/core/config.js @@ -0,0 +1,309 @@ +var fs = require('./fs.js'); +var Plugins = require('./plugins.js'); +var utils = require('./utils.js'); + +// TODO: add wrapper for fs so it can also work in the browser +// can work with both read and save +var Config = function(options) { + this.env = options.env; + this.blockchainConfig = {}; + this.contractsConfig = {}; + this.pipelineConfig = {}; + this.webServerConfig = {}; + this.chainTracker = {}; + this.assetFiles = {}; + this.contractsFiles = []; + this.configDir = options.configDir || 'config/'; + this.chainsFile = options.chainsFile || './chains.json'; + this.plugins = options.plugins; + this.logger = options.logger; + this.events = options.events; +}; + +Config.prototype.loadConfigFiles = function(options) { + var interceptLogs = options.interceptLogs; + if (options.interceptLogs === undefined) { + interceptLogs = true; + } + + //Check if the config file exists + var embarkConfigExists = fs.existsSync(options.embarkConfig); + if(!embarkConfigExists){ + this.logger.error('Cannot find file ' + options.embarkConfig + '. Please ensure you are running this command inside the Dapp folder'); + process.exit(1); + } + + this.embarkConfig = fs.readJSONSync(options.embarkConfig); + this.embarkConfig.plugins = this.embarkConfig.plugins || {}; + + this.plugins = new Plugins({plugins: this.embarkConfig.plugins, logger: this.logger, interceptLogs: interceptLogs, events: this.events, config: this}); + this.plugins.loadPlugins(); + + this.loadEmbarkConfigFile(); + this.loadBlockchainConfigFile(); + this.loadStorageConfigFile(); + this.loadCommunicationConfigFile(); + + this.loadPipelineConfigFile(); + + this.loadContractsConfigFile(); + this.loadWebServerConfigFile(); + this.loadChainTrackerFile(); + this.loadPluginContractFiles(); +}; + +Config.prototype.reloadConfig = function() { + this.loadEmbarkConfigFile(); + this.loadBlockchainConfigFile(); + this.loadStorageConfigFile(); + this.loadCommunicationConfigFile(); + this.loadPipelineConfigFile(); + this.loadContractsConfigFile(); + this.loadChainTrackerFile(); +}; + +Config.prototype.loadBlockchainConfigFile = function() { + var defaultBlockchainConfig = fs.readJSONSync(this.configDir + "blockchain.json"); + this.blockchainConfig = defaultBlockchainConfig[this.env] || {}; + + if (this.blockchainConfig.enabled === undefined) { + this.blockchainConfig.enabled = true; + } +}; + +Config.prototype.loadContractsConfigFile = function() { + + var configObject = {}; + + var configPlugins = this.plugins.getPluginsFor('contractsConfig'); + if (configPlugins.length > 0) { + configPlugins.forEach(function(plugin) { + plugin.contractsConfigs.forEach(function(pluginConfig) { + configObject = utils.recursiveMerge(configObject, pluginConfig); + }); + }); + } + + var contractsConfig = fs.readJSONSync(this.configDir + "contracts.json"); + configObject = utils.recursiveMerge(configObject, contractsConfig); + var defaultContractsConfig = configObject['default']; + var envContractsConfig = configObject[this.env]; + + var mergedConfig = utils.recursiveMerge(defaultContractsConfig, envContractsConfig); + this.contractsConfig = mergedConfig; +}; + + +Config.prototype.loadStorageConfigFile = function() { + var configObject = { + "default": { + "enabled": true, + "available_providers": ["ipfs"], + "ipfs_bin": "ipfs", + "provider": "ipfs", + "host": "localhost", + "port": 5001 + }, + "development": { + } + }; + + //var configPlugins = this.plugins.getPluginsFor('storageConfig'); + //if (configPlugins.length > 0) { + // configPlugins.forEach(function(plugin) { + // plugin.contractsConfigs.forEach(function(pluginConfig) { + // configObject = utils.recursiveMerge(configObject, pluginConfig); + // }); + // }); + //} + + var storageConfig; + if (fs.existsSync(this.configDir + "storage.json")) { + storageConfig = fs.readJSONSync(this.configDir + "storage.json"); + configObject = utils.recursiveMerge(configObject, storageConfig); + } + + var defaultStorageConfig = configObject['default']; + var envStorageConfig = configObject[this.env]; + + var mergedConfig = utils.recursiveMerge(defaultStorageConfig, envStorageConfig); + this.storageConfig = mergedConfig || {}; + + if (this.storageConfig.enabled === undefined) { + this.storageConfig.enabled = true; + } + if (this.storageConfig.available_providers === undefined) { + this.storageConfig.available_providers = []; + } +}; + +Config.prototype.loadCommunicationConfigFile = function() { + var configObject = { + "default": { + "enabled": true, + "provider": "whisper", + "available_providers": ["whisper", "orbit"] + } + }; + + //var configPlugins = this.plugins.getPluginsFor('communicationConfig'); + //if (configPlugins.length > 0) { + // configPlugins.forEach(function(plugin) { + // plugin.contractsConfigs.forEach(function(pluginConfig) { + // configObject = utils.recursiveMerge(configObject, pluginConfig); + // }); + // }); + //} + + var communicationConfig; + + if (fs.existsSync(this.configDir + "communication.json")) { + communicationConfig = fs.readJSONSync(this.configDir + "communication.json"); + configObject = utils.recursiveMerge(configObject, communicationConfig); + } + + var defaultCommunicationConfig = configObject['default']; + var envCommunicationConfig = configObject[this.env]; + + var mergedConfig = utils.recursiveMerge(defaultCommunicationConfig, envCommunicationConfig); + this.communicationConfig = mergedConfig || {}; + + // TODO: probably not necessary if the default object is done right + if (this.communicationConfig.enabled === undefined) { + this.communicationConfig.enabled = true; + } + if (this.communicationConfig.available_providers === undefined) { + this.communicationConfig.available_providers = []; + } +}; + +Config.prototype.loadWebServerConfigFile = function() { + var webServerConfigJSON; + if (fs.existsSync(this.configDir + "webserver.json")) { + webServerConfigJSON = fs.readJSONSync(this.configDir + "webserver.json"); + } else { + webServerConfigJSON = {}; + } + var defaultWebConfig = { + "enabled": true, + "host": "localhost", + "port": 8000 + }; + this.webServerConfig = utils.recursiveMerge(defaultWebConfig, webServerConfigJSON); +}; + +Config.prototype.loadEmbarkConfigFile = function() { + var contracts = this.embarkConfig.contracts; + this.contractsFiles = this.loadFiles(contracts); + + this.buildDir = this.embarkConfig.buildDir; + this.configDir = this.embarkConfig.config; +}; + +Config.prototype.loadPipelineConfigFile = function() { + var assets = this.embarkConfig.app; + for(var targetFile in assets) { + this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]); + } +}; + +Config.prototype.loadChainTrackerFile = function() { + //var self = this; + var chainTracker; + try { + chainTracker = fs.readJSONSync(this.chainsFile); + } + catch(err) { + //self.logger.info(this.chainsFile + ' file not found, creating it...'); + chainTracker = {}; + fs.writeJSONSync(this.chainsFile, {}); + } + this.chainTracker = chainTracker; +}; + +Config.prototype.loadFiles = function(files) { + var self = this; + var originalFiles = utils.filesMatchingPattern(files); + var readFiles = []; + + // get embark.js object first + originalFiles.filter(function(file) { + return file.indexOf('.') >= 0; + }).filter(function(file) { + if (file === 'embark.js') { + + if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) { + readFiles.push({filename: 'web3.js', content: fs.readFileSync(fs.embarkPath("js/web3.js")).toString(), path: fs.embarkPath("js/web3.js")}); + } + + if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) { + readFiles.push({filename: 'ipfs.js', content: fs.readFileSync(fs.embarkPath("js/ipfs.js")).toString(), path: fs.embarkPath("js/ipfs.js")}); + } + + if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) { + // TODO: remove duplicated files if functionality is the same for storage and orbit + readFiles.push({filename: 'ipfs-api.js', content: fs.readFileSync(fs.embarkPath("js/ipfs-api.min.js")).toString(), path: fs.embarkPath("js/ipfs-api.min.js")}); + readFiles.push({filename: 'orbit.js', content: fs.readFileSync(fs.embarkPath("js/orbit.min.js")).toString(), path: fs.embarkPath("js/orbit.min.js")}); + } + + readFiles.push({filename: 'embark.js', content: fs.readFileSync(fs.embarkPath("js/build/embark.bundle.js")).toString(), path: fs.embarkPath("js/build/embark.bundle.js")}); + } + }); + + // get plugins + var filesFromPlugins = []; + + var filePlugins = self.plugins.getPluginsFor('pipelineFiles'); + + if (filePlugins.length > 0) { + filePlugins.forEach(function(plugin) { + try { + var fileObjects = plugin.runFilePipeline(); + for (var i=0; i < fileObjects.length; i++) { + var fileObject = fileObjects[i]; + filesFromPlugins.push(fileObject); + } + } + catch(err) { + self.logger.error(err.message); + } + }); + } + + filesFromPlugins.filter(function(file) { + if (utils.fileMatchesPattern(files, file.intendedPath)) { + readFiles.push(file); + } + }); + + // get user files + originalFiles.filter(function(file) { + return file.indexOf('.') >= 0; + }).filter(function(file) { + if (file === 'embark.js') { + return; + } else if (file === 'abi.js') { + readFiles.push({filename: file, content: "", path: file}); + } else { + readFiles.push({filename: file, content: fs.readFileSync(file).toString(), path: file}); + } + }); + + return readFiles; +}; + +Config.prototype.loadPluginContractFiles = function() { + var self = this; + + var contractsPlugins = this.plugins.getPluginsFor('contractFiles'); + if (contractsPlugins.length > 0) { + contractsPlugins.forEach(function(plugin) { + plugin.contractsFiles.forEach(function(file) { + var filename = file.replace('./',''); + self.contractsFiles.push({filename: filename, content: plugin.loadPluginFile(file), path: plugin.pathToFile(file)}); + }); + }); + } +}; + +module.exports = Config; diff --git a/lib/core/core.js b/lib/core/core.js new file mode 100644 index 00000000..424eda08 --- /dev/null +++ b/lib/core/core.js @@ -0,0 +1,5 @@ + +var Core = function() {}; + +module.exports = Core; + diff --git a/lib/core/debug_util.js b/lib/core/debug_util.js new file mode 100644 index 00000000..9fa0233f --- /dev/null +++ b/lib/core/debug_util.js @@ -0,0 +1,20 @@ +// util to map async method names + +function extend(filename, async) { + if (async._waterfall !== undefined) { + return; + } + async._waterfall = async.waterfall; + async.waterfall = function(_tasks, callback) { + var tasks = _tasks.map(function(t) { + var fn = function() { + console.log("async " + filename + ": " + t.name); + t.apply(t, arguments); + }; + return fn; + }); + async._waterfall(tasks, callback); + }; +} + +module.exports = extend; diff --git a/lib/core/engine.js b/lib/core/engine.js new file mode 100644 index 00000000..872d8fc7 --- /dev/null +++ b/lib/core/engine.js @@ -0,0 +1,147 @@ +var Events = require('./events.js'); +var Logger = require('./logger.js'); +var Config = require('./config.js'); + +var DeployManager = require('../contracts/deploy_manager.js'); +var ABIGenerator = require('../contracts/abi.js'); +var Dashboard = require('../dashboard/dashboard.js'); +var ServicesMonitor = require('./services.js'); +var Pipeline = require('../pipeline/pipeline.js'); +var Server = require('../pipeline/server.js'); +var Watch = require('../pipeline/watch.js'); + +var Engine = function(options) { + this.env = options.env; + this.embarkConfig = options.embarkConfig; + this.interceptLogs = options.interceptLogs; + this.version = "2.4.0"; +}; + +Engine.prototype.init = function(_options) { + var options = _options || {}; + this.events = new Events(); + this.logger = options.logger || new Logger({logLevel: 'debug'}); + this.config = new Config({env: this.env, logger: this.logger, events: this.events}); + this.config.loadConfigFiles({embarkConfig: this.embarkConfig, interceptLogs: this.interceptLogs}); + this.plugins = this.config.plugins; +}; + +Engine.prototype.startService = function(serviceName, _options) { + var options = _options || {}; + + var services = { + "monitor": this.monitorService, + "pipeline": this.pipelineService, + "abi": this.abiService, + "deployment": this.deploymentService, + "fileWatcher": this.fileWatchService, + "webServer": this.webServerService + }; + + var service = services[serviceName]; + + if (!service) { + throw new Error("unknown service: " + serviceName); + } + + // need to be careful with circular references due to passing the web3 object + //this.logger.trace("calling: " + serviceName + "(" + JSON.stringify(options) + ")"); + return service.apply(this, [options]); +}; + +Engine.prototype.monitorService = function(options) { + var servicesMonitor = new ServicesMonitor({ + logger: this.logger, + config: this.config, + serverHost: options.serverHost, + serverPort: options.serverPort, + runWebserver: options.runWebserver, + version: this.version + }); + servicesMonitor.startMonitor(); +}; + +Engine.prototype.pipelineService = function(options) { + var self = this; + this.logger.setStatus("Building Assets"); + var pipeline = new Pipeline({ + buildDir: this.config.buildDir, + contractsFiles: this.config.contractsFiles, + assetFiles: this.config.assetFiles, + logger: this.logger, + plugins: this.plugins + }); + this.events.on('abi', function(abi) { + self.currentAbi = abi; + pipeline.build(abi); + self.events.emit('outputDone'); + }); + this.events.on('file-event', function(fileType, path) { + if (fileType === 'asset') { + self.config.reloadConfig(); + pipeline.build(self.abi, path); + self.events.emit('outputDone'); + } + }); +}; + +Engine.prototype.abiService = function(options) { + var self = this; + var generateABICode = function(contractsManager) { + var abiGenerator = new ABIGenerator({ + blockchainConfig: self.config.blockchainConfig, + contractsManager: contractsManager, + plugins: self.plugins, + storageConfig: self.config.storageConfig, + communicationConfig: self.config.communicationConfig + }); + var embarkJSABI = abiGenerator.generateABI({useEmbarkJS: true}); + var vanillaABI = abiGenerator.generateABI({useEmbarkJS: false}); + var vanillaContractsABI = abiGenerator.generateContracts(false); + + self.events.emit('abi-contracts-vanila', vanillaContractsABI); + self.events.emit('abi-vanila', vanillaABI); + self.events.emit('abi', embarkJSABI); + }; + this.events.on('contractsDeployed', generateABICode); + this.events.on('blockchainDisabled', generateABICode); +}; + +Engine.prototype.deploymentService = function(options) { + var self = this; + this.deployManager = new DeployManager({ + web3: options.web3, + trackContracts: options.trackContracts, + config: this.config, + logger: this.logger, + plugins: this.plugins, + events: this.events + }); + + this.events.on('file-event', function(fileType, path) { + if (fileType === 'contract' || fileType === 'config') { + self.config.reloadConfig(); + self.deployManager.deployContracts(function() {}); + } + }); +}; + +Engine.prototype.fileWatchService = function(options) { + this.logger.setStatus("Watching for changes"); + var watch = new Watch({logger: this.logger, events: this.events}); + watch.start(); +}; + +Engine.prototype.webServerService = function(options) { + var webServerConfig = this.config.webServerConfig; + if (!webServerConfig.enabled) { return; } + this.logger.setStatus("Starting Server"); + var server = new Server({ + logger: this.logger, + host: options.host || webServerConfig.host, + port: options.port || webServerConfig.port + }); + server.start(function(){}); +}; + +module.exports = Engine; diff --git a/lib/core/events.js b/lib/core/events.js new file mode 100644 index 00000000..69e0177b --- /dev/null +++ b/lib/core/events.js @@ -0,0 +1,3 @@ +var EventEmitter = require('events'); + +module.exports = EventEmitter; diff --git a/lib/core/fs.js b/lib/core/fs.js new file mode 100644 index 00000000..dbbf7480 --- /dev/null +++ b/lib/core/fs.js @@ -0,0 +1,46 @@ +var fs = require('fs-extra'); +var utils = require('./utils.js'); + +function mkdirpSync() { + return fs.mkdirpSync.apply(fs.mkdirpSync, arguments); +} + +function copySync() { + return fs.copySync.apply(fs.copySync, arguments); +} + +function writeFileSync() { + return fs.writeFileSync.apply(fs.writeFileSync, arguments); +} + +function readFileSync() { + return fs.readFileSync.apply(fs.readFileSync, arguments); +} + +function readJSONSync() { + return fs.readJSONSync.apply(fs.readJSONSync, arguments); +} + +function writeJSONSync() { + return fs.writeJSONSync.apply(fs.writeJSONSync, arguments); +} + +function existsSync(){ + return fs.existsSync.apply(fs.existsSync, arguments); +} + +// returns embarks root directory +function embarkPath(fileOrDir) { + return utils.joinPath(__dirname, '/../../', fileOrDir); +} + +module.exports = { + mkdirpSync: mkdirpSync, + copySync: copySync, + readFileSync: readFileSync, + writeFileSync: writeFileSync, + readJSONSync: readJSONSync, + writeJSONSync: writeJSONSync, + existsSync: existsSync, + embarkPath: embarkPath +}; diff --git a/lib/logger.js b/lib/core/logger.js similarity index 83% rename from lib/logger.js rename to lib/core/logger.js index b93f005a..5007977c 100644 --- a/lib/logger.js +++ b/lib/core/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) { diff --git a/lib/core/plugin.js b/lib/core/plugin.js new file mode 100644 index 00000000..32765ea3 --- /dev/null +++ b/lib/core/plugin.js @@ -0,0 +1,159 @@ +/*jshint esversion: 6, loopfunc: true */ +var fs = require('./fs.js'); +var utils = require('./utils.js'); + +// TODO: pass other params like blockchainConfig, contract files, etc.. +var Plugin = function(options) { + this.name = options.name; + this.pluginModule = options.pluginModule; + this.pluginPath = options.pluginPath; + this.pluginConfig = options.pluginConfig; + this.shouldInterceptLogs = options.interceptLogs; + this.clientWeb3Providers = []; + this.contractsGenerators = []; + this.pipeline = []; + this.pipelineFiles = []; + this.console = []; + this.contractsConfigs = []; + this.contractsFiles = []; + this.compilers = []; + this.pluginTypes = []; + this.logger = options.logger; + this.events = options.events; + this.config = options.config; +}; + +Plugin.prototype.loadPlugin = function() { + if (this.shouldInterceptLogs) { + this.interceptLogs(this.pluginModule); + } + (this.pluginModule.call(this, this)); +}; + +Plugin.prototype.loadPluginFile = function(filename) { + return fs.readFileSync(this.pathToFile(filename)).toString(); +}; + +Plugin.prototype.pathToFile = function(filename) { + return utils.joinPath(this.pluginPath, filename); +}; + +Plugin.prototype.interceptLogs = function(context) { + var self = this; + // TODO: this is a bit nasty, figure out a better way + context.console = context.console || console; + + //context.console.error = function(txt) { + // // TODO: logger should support an array instead of a single argument + // //self.logger.error.apply(self.logger, arguments); + // self.logger.error(self.name + " > " + txt); + //}; + context.console.log = function(txt) { + self.logger.info(self.name + " > " + txt); + }; + context.console.warn = function(txt) { + self.logger.warn(self.name + " > " + txt); + }; + context.console.info = function(txt) { + self.logger.info(self.name + " > " + txt); + }; + context.console.debug = function(txt) { + // TODO: ue JSON.stringify + self.logger.debug(self.name + " > " + txt); + }; + context.console.trace = function(txt) { + self.logger.trace(self.name + " > " + txt); + }; +}; + +// TODO: add deploy provider +Plugin.prototype.registerClientWeb3Provider = function(cb) { + this.clientWeb3Providers.push(cb); + this.pluginTypes.push('clientWeb3Provider'); +}; + +Plugin.prototype.registerContractsGeneration = function(cb) { + this.contractsGenerators.push(cb); + this.pluginTypes.push('contractGeneration'); +}; + +Plugin.prototype.registerPipeline = function(matcthingFiles, cb) { + // TODO: generate error for more than one pipeline per plugin + this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb}); + this.pluginTypes.push('pipeline'); +}; + +Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) { + this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options}); + this.pluginTypes.push('pipelineFiles'); +}; + +Plugin.prototype.addContractFile = function(file) { + this.contractsFiles.push(file); + this.pluginTypes.push('contractFiles'); +}; + +Plugin.prototype.registerConsoleCommand = function(cb) { + this.console.push(cb); + this.pluginTypes.push('console'); +}; + +Plugin.prototype.has = function(pluginType) { + return this.pluginTypes.indexOf(pluginType) >= 0; +}; + +Plugin.prototype.generateProvider = function(args) { + return this.clientWeb3Providers.map(function(cb) { + return cb.call(this, args); + }).join("\n"); +}; + +Plugin.prototype.generateContracts = function(args) { + return this.contractsGenerators.map(function(cb) { + return cb.call(this, args); + }).join("\n"); +}; + +Plugin.prototype.registerContractConfiguration = function(config) { + this.contractsConfigs.push(config); + this.pluginTypes.push('contractsConfig'); +}; + +Plugin.prototype.registerCompiler = function(extension, cb) { + this.compilers.push({extension: extension, cb: cb}); + this.pluginTypes.push('compilers'); +}; + +Plugin.prototype.runCommands = function(cmd, options) { + return this.console.map(function(cb) { + return cb.call(this, cmd, options); + }).join("\n"); +}; + +Plugin.prototype.runFilePipeline = function() { + var self = this; + + return this.pipelineFiles.map(function(file) { + var obj = {}; + obj.filename = file.file.replace('./',''); + obj.content = self.loadPluginFile(file.file).toString(); + obj.intendedPath = file.intendedPath; + obj.options = file.options; + obj.path = self.pathToFile(obj.filename); + + return obj; + }); +}; + +Plugin.prototype.runPipeline = function(args) { + // TODO: should iterate the pipelines + var pipeline = this.pipeline[0]; + var shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile); + if (shouldRunPipeline) { + return pipeline.cb.call(this, args); + } else { + return args.source; + } +}; + +module.exports = Plugin; diff --git a/lib/core/plugins.js b/lib/core/plugins.js new file mode 100644 index 00000000..4132a280 --- /dev/null +++ b/lib/core/plugins.js @@ -0,0 +1,45 @@ +var Plugin = require('./plugin.js'); +var utils = require('./utils.js'); + +var Plugins = function(options) { + this.pluginList = options.plugins || []; + this.interceptLogs = options.interceptLogs; + this.plugins = []; + // TODO: need backup 'NullLogger' + this.logger = options.logger; + this.events = options.events; + this.config = options.config; +}; + +Plugins.prototype.loadPlugins = function() { + var pluginConfig; + for (var pluginName in this.pluginList) { + pluginConfig = this.pluginList[pluginName]; + this.loadPlugin(pluginName, pluginConfig); + } +}; + +Plugins.prototype.listPlugins = function() { + var list = []; + for (var className in this.pluginList) { + list.push(className); + } + return list; +}; + +Plugins.prototype.loadPlugin = function(pluginName, pluginConfig) { + var pluginPath = utils.joinPath(process.env.PWD, 'node_modules', pluginName); + var plugin = require(pluginPath); + + var pluginWrapper = new Plugin({name: pluginName, pluginModule: plugin, pluginConfig: pluginConfig, logger: this.logger, pluginPath: pluginPath, interceptLogs: this.interceptLogs, events: this.events, config: this.config}); + pluginWrapper.loadPlugin(); + this.plugins.push(pluginWrapper); +}; + +Plugins.prototype.getPluginsFor = function(pluginType) { + return this.plugins.filter(function(plugin) { + return plugin.has(pluginType); + }); +}; + +module.exports = Plugins; diff --git a/lib/core/runCode.js b/lib/core/runCode.js new file mode 100644 index 00000000..7134b94a --- /dev/null +++ b/lib/core/runCode.js @@ -0,0 +1,18 @@ +var Web3 = require('web3'); +var web3; + +// ====================== +// the eval is used for evaluating some of the contact calls for different purposes +// this should be at least moved to a different process and scope +// for now it is defined here +// ====================== +function doEval(code, _web3) { + if (_web3) { + web3 = _web3; + } + return eval(code); // jshint ignore:line +} + +module.exports = { + doEval: doEval +}; diff --git a/lib/core/services.js b/lib/core/services.js new file mode 100644 index 00000000..a04f672e --- /dev/null +++ b/lib/core/services.js @@ -0,0 +1,113 @@ +var Web3 = require('web3'); +var async = require('async'); +var http = require('http'); +var utils = require('./utils.js'); + +// TODO: needs a refactor and be done in a different way +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; + this.runWebserver = options.runWebserver; + this.version = options.version; +}; + +ServicesMonitor.prototype.startMonitor = function() { + this.check(); + this.monitor = setInterval(this.check.bind(this), this.interval); +}; + +ServicesMonitor.prototype.stopMonitor = function() { +}; + +ServicesMonitor.prototype.check = function() { + var self = this; + async.waterfall([ + function connectWeb3(callback) { + self.logger.trace('connectWeb3'); + var web3 = new Web3(); + var web3Endpoint = 'http://' + self.config.blockchainConfig.rpcHost + ':' + self.config.blockchainConfig.rpcPort; + web3.setProvider(new web3.providers.HttpProvider(web3Endpoint)); + callback(null, web3, []); + }, + function addEmbarkVersion(web3, result, callback) { + self.logger.trace('addEmbarkVersion'); + result.push(('Embark ' + self.version).green); + callback(null, web3, result); + }, + function checkEthereum(web3, result, callback) { + self.logger.trace('checkEthereum'); + var service; + if (web3.isConnected()) { + service = (web3.version.node.split("/")[0] + " " + web3.version.node.split("/")[1].split("-")[0] + " (Ethereum)").green; + } else { + service = "No Blockchain node found".red; + } + result.push(service); + callback(null, web3, result); + }, + function checkWhisper(web3, result, callback) { + self.logger.trace('checkWhisper'); + web3.version.getWhisper(function(err, res) { + var service = 'Whisper'; + result.push(err ? service.red : service.green); + callback(null, result); + }); + }, + function checkIPFS(result, callback) { + self.logger.trace('checkIPFS'); + + utils.checkIsAvailable('http://localhost:5001', function(available) { + if (available) { + //Ideally this method should be in an IPFS API JSONRPC wrapper + //The URL should also be flexible to accept non-default IPFS url + self.logger.trace("Checking IPFS version..."); + http.get('http://localhost:5001/api/v0/version', function(res) { + var body = ''; + res.on('data', function(d) { + body += d; + }); + res.on('end', function() { + var parsed = JSON.parse(body); + if(parsed.Version){ + result.push(("IPFS " + parsed.Version).green); + } + else{ + result.push("IPFS".green); + } + callback(null, result); + }); + res.on('error', function(err) { + self.logger.trace("Check IPFS version error: " + err); + result.push("IPFS".green); + callback(null, result); + }); + }); + } + else { + result.push('IPFS'.red); + return callback(null, result); + } + }); + }, + function checkDevServer(result, callback) { + var host = self.serverHost || self.config.webServerConfig.host; + var port = self.serverPort || self.config.webServerConfig.port; + self.logger.trace('checkDevServer'); + var devServer = 'Webserver (http://' + host + ':' + port + ')'; + devServer = (self.runWebserver) ? devServer.green : devServer.red; + result.push(devServer); + callback(null, result); + } + ], function(err, result) { + if (err) { + self.logger.error(err.message); + } else { + self.logger.availableServices(result); + } + }); +}; + +module.exports = ServicesMonitor; diff --git a/lib/core/test.js b/lib/core/test.js new file mode 100644 index 00000000..ac1b5e37 --- /dev/null +++ b/lib/core/test.js @@ -0,0 +1,102 @@ +var async = require('async'); +var Web3 = require('web3'); + +var Embark = require('../index.js'); + +var Engine = require('./engine.js'); + +var ABIGenerator = require('../contracts/abi.js'); +var ContractsManager = require('../contracts/contracts.js'); +var Deploy = require('../contracts/deploy.js'); + +var Config = require('./config.js'); +var RunCode = require('./runCode.js'); +var TestLogger = require('./test_logger.js'); + +var getSimulator = function() { + try { + var sim = require('ethereumjs-testrpc'); + return sim; + } catch (e) { + if (e.code === 'MODULE_NOT_FOUND') { + console.log('Simulator not found; Please install it with "npm install ethereumjs-testrpc --save"'); + console.log('IMPORTANT: if you using a NodeJS version older than 6.9.1 then you need to install an older version of testrpc "npm install ethereumjs-testrpc@2.0 --save"'); + console.log('For more information see https://github.com/ethereumjs/testrpc'); + // TODO: should throw exception instead + return process.exit(); + } + console.log("=============="); + console.log("Tried to load testrpc but an error occurred. This is a problem with testrpc"); + console.log('IMPORTANT: if you using a NodeJS version older than 6.9.1 then you need to install an older version of testrpc "npm install ethereumjs-testrpc@2.0 --save". Alternatively install node 6.9.1 and the testrpc 3.0'); + console.log("=============="); + throw e; + } +}; + +var Test = function(options) { + this.options = options || {}; + var simOptions = this.options.simulatorOptions || {}; + + this.engine = new Engine({ + env: this.options.env || 'test', + // TODO: confi will need to detect if this is a obj + embarkConfig: this.options.embarkConfig || 'embark.json', + interceptLogs: false + }); + + this.engine.init({ + logger: new TestLogger({logLevel: this.options.logLevel || 'debug'}) + }); + + this.sim = getSimulator(); + this.web3 = new Web3(); + this.web3.setProvider(this.sim.provider(simOptions)); +}; + +Test.prototype.deployAll = function(contractsConfig, cb) { + var self = this; + + async.waterfall([ + function getConfig(callback) { + self.engine.config.contractsConfig = {contracts: contractsConfig}; + callback(); + }, + function startServices(callback) { + //{abiType: 'contracts', embarkJS: false} + self.engine.startService("abi"); + self.engine.startService("deployment", { + web3: self.web3, + trackContracts: false + }); + callback(); + }, + function deploy(callback) { + self.engine.events.on('abi-contracts-vanila', function(vanillaABI) { + callback(null, vanillaABI); + }); + self.engine.deployManager.deployContracts(function(err, result) { + if (err) { + console.log(err); + callback(err); + } + }); + } + ], function(err, result) { + if (err) { + console.log("got error"); + process.exit(); + } + // this should be part of the waterfall and not just something done at the + // end + self.web3.eth.getAccounts(function(err, accounts) { + if (err) { + throw new Error(err); + } + self.web3.eth.defaultAccount = accounts[0]; + RunCode.doEval(result, self.web3); // jshint ignore:line + cb(); + }); + }); +}; + +module.exports = Test; diff --git a/lib/test_logger.js b/lib/core/test_logger.js similarity index 100% rename from lib/test_logger.js rename to lib/core/test_logger.js diff --git a/lib/core/utils.js b/lib/core/utils.js new file mode 100644 index 00000000..0870374e --- /dev/null +++ b/lib/core/utils.js @@ -0,0 +1,67 @@ +/*global exit */ +var path = require('path'); +var globule = require('globule'); +var merge = require('merge'); +var http = require('http'); +var shelljs = require('shelljs'); + +function joinPath() { + return path.join.apply(path.join, arguments); +} + +function filesMatchingPattern(files) { + return globule.find(files, {nonull: true}); +} + +function fileMatchesPattern(patterns, intendedPath) { + return globule.isMatch(patterns, intendedPath); +} + +function recursiveMerge(target, source) { + return merge.recursive(target, source); +} + +function checkIsAvailable(url, callback) { + http.get(url, function(res) { + callback(true); + }).on('error', function(res) { + callback(false); + }); +} + +function runCmd(cmd, options) { + var result = shelljs.exec(cmd, options || {silent: true}); + if (result.code !== 0) { + console.log("error doing.. " + cmd); + console.log(result.output); + if (result.stderr !== undefined) { + console.log(result.stderr); + } + exit(); + } +} + +function cd(folder) { + shelljs.cd(folder); +} + +function sed(file, pattern, replace) { + shelljs.sed('-i', pattern, replace, file); +} + +function exit(code) { + process.exit(code); +} + +module.exports = { + joinPath: joinPath, + filesMatchingPattern: filesMatchingPattern, + fileMatchesPattern: fileMatchesPattern, + recursiveMerge: recursiveMerge, + checkIsAvailable: checkIsAvailable, + runCmd: runCmd, + cd: cd, + sed: sed, + exit: exit +}; + diff --git a/lib/dashboard/command_history.js b/lib/dashboard/command_history.js new file mode 100644 index 00000000..43e1d2d9 --- /dev/null +++ b/lib/dashboard/command_history.js @@ -0,0 +1,28 @@ + +var CommandHistory = function() { + this.history = []; + this.pointer = -1; +}; + +CommandHistory.prototype.addCommand = function(cmd) { + this.history.push(cmd); + this.pointer = this.history.length; +}; + +CommandHistory.prototype.getPreviousCommand = function(cmd) { + if (this.pointer >= 0) { + this.pointer--; + } + return this.history[this.pointer]; +}; + +CommandHistory.prototype.getNextCommand = function(cmd) { + if (this.pointer >= this.history.length) { + this.pointer = this.history.length - 1; + return ''; + } + this.pointer++; + return this.history[this.pointer]; +}; + +module.exports = CommandHistory; diff --git a/lib/dashboard/console.js b/lib/dashboard/console.js new file mode 100644 index 00000000..c510f204 --- /dev/null +++ b/lib/dashboard/console.js @@ -0,0 +1,60 @@ +var utils = require('../core/utils.js'); +var RunCode = require('../core/runCode.js'); + +var Console = function(options) { + this.plugins = options.plugins; + this.version = options.version; +}; + +Console.prototype.runCode = function(code) { + RunCode.doEval(code); // jshint ignore:line +}; + +Console.prototype.processEmbarkCmd = function(cmd) { + if (cmd === 'help') { + var helpText = [ + 'Welcome to Embark ' + this.version, + '', + 'possible commands are:', + // TODO: only if the blockchain is actually active! + // will need to pass te current embark state here + 'web3 - instantiated web3.js object configured to the current environment', + 'quit - to immediatly exit', + '', + 'The web3 object and the interfaces for the deployed contracts and their methods are also available' + ]; + return helpText.join('\n'); + } else if (cmd === 'quit') { + utils.exit(); + } + return false; +}; + +Console.prototype.executeCmd = function(cmd, callback) { + var plugin, pluginOutput; + var plugins = this.plugins.getPluginsFor('console'); + for (var i = 0; i < plugins.length; i++) { + plugin = plugins[i]; + pluginOutput = plugin.runCommands(cmd, {}); + if (pluginOutput !== false && pluginOutput !== 'false') return callback(pluginOutput); + } + + var output = this.processEmbarkCmd(cmd); + if (output) { + return callback(output); + } + + try { + var result = RunCode.doEval(cmd); + return callback(result); + } + catch(e) { + if (e.message.indexOf('not defined') > 0) { + return callback(("error: " + e.message).red + ("\nType " + "help".bold + " to see the list of available commands").cyan); + } else { + return callback(e.message); + } + } +}; + +module.exports = Console; diff --git a/lib/dashboard/dashboard.js b/lib/dashboard/dashboard.js new file mode 100644 index 00000000..d67b142d --- /dev/null +++ b/lib/dashboard/dashboard.js @@ -0,0 +1,43 @@ +var async = require('async'); + +var Monitor = require('./monitor.js'); +var Console = require('./console.js'); + +var Dashboard = function(options) { + this.logger = options.logger; + this.plugins = options.plugins; + this.version = options.version; + this.env = options.env; +}; + +Dashboard.prototype.start = function(done) { + var console, monitor; + var self = this; + + async.waterfall([ + function startConsole(callback) { + console = new Console({plugins: self.plugins, version: self.version}); + callback(); + }, + function startMonitor(callback) { + monitor = new Monitor({env: self.env, console: console}); + self.logger.logFunction = monitor.logEntry; + self.logger.contractsState = monitor.setContracts; + self.logger.availableServices = monitor.availableServices; + self.logger.setStatus = monitor.setStatus.bind(monitor); + + self.logger.info('========================'.bold.green); + self.logger.info(('Welcome to Embark ' + self.version).yellow.bold); + self.logger.info('========================'.bold.green); + + // TODO: do this after monitor is rendered + callback(); + } + ], function() { + self.console = console; + self.monitor = monitor; + done(); + }); +}; + +module.exports = Dashboard; diff --git a/lib/monitor.js b/lib/dashboard/monitor.js similarity index 86% rename from lib/monitor.js rename to lib/dashboard/monitor.js index 94e94aaf..5468128b 100644 --- a/lib/monitor.js +++ b/lib/dashboard/monitor.js @@ -1,41 +1,16 @@ /*jshint esversion: 6 */ var blessed = require("blessed"); - -var CommandHistory = function() { - this.history = []; - this.pointer = -1; -}; - -CommandHistory.prototype.addCommand = function(cmd) { - this.history.push(cmd); - this.pointer = this.history.length; -}; - -CommandHistory.prototype.getPreviousCommand = function(cmd) { - if (this.pointer >= 0) { - this.pointer--; - } - return this.history[this.pointer]; -}; - -CommandHistory.prototype.getNextCommand = function(cmd) { - if (this.pointer >= this.history.length) { - this.pointer = this.history.length - 1; - return ''; - } - this.pointer++; - return this.history[this.pointer]; -}; +var CommandHistory = require('./command_history.js'); function Dashboard(options) { - var title = options && options.title || "Embark 2.0"; + var title = (options && options.title) || "Embark 2.4.0"; this.env = options.env; this.console = options.console; this.history = new CommandHistory(); - this.color = options && options.color || "green"; - this.minimal = options && options.minimal || false; + this.color = (options && options.color) || "green"; + this.minimal = (options && options.minimal) || false; this.screen = blessed.screen({ smartCSR: true, @@ -45,10 +20,10 @@ function Dashboard(options) { autoPadding: true }); - this.layoutLog.call(this); - this.layoutStatus.call(this); - this.layoutModules.call(this); - this.layoutCmd.call(this); + this.layoutLog(); + this.layoutStatus(); + this.layoutModules(); + this.layoutCmd(); this.screen.key(["C-c"], function() { process.exit(0); @@ -272,13 +247,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, @@ -358,7 +333,7 @@ Dashboard.prototype.layoutCmd = function() { this.input.on('submit', function(data) { if (data !== '') { self.history.addCommand(data); - self.logText.log('console> ' + data); + self.logText.log('console> '.bold.green + data); self.console.executeCmd(data, function(result) { self.logText.log(result); }); diff --git a/lib/geth_commands.js b/lib/geth_commands.js deleted file mode 100644 index 9b81fd7b..00000000 --- a/lib/geth_commands.js +++ /dev/null @@ -1,138 +0,0 @@ - -var GethCommands = function(options) { - this.config = options.config; - 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.listAccountsCommand = 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 list "; -}; - -GethCommands.prototype.mainCommand = function(address) { - var config = this.config; - 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 "; - } - - if (config.networkType === 'custom') { - cmd += "--networkid " + config.networkId + " "; - } - - if (config.account && config.account.password) { - cmd += "--password " + config.account.password + " "; - } - - cmd += "--port " + "30303" + " "; - cmd += "--rpc "; - cmd += "--rpcport " + config.rpcPort + " "; - cmd += "--rpcaddr " + config.rpcHost + " "; - if (config.rpcCorsDomain) { - if (config.rpcCorsDomain === '*') { - console.log('=================================='); - console.log('make sure you know what you are doing'); - console.log('=================================='); - } - cmd += "--rpccorsdomain=\"" + config.rpcCorsDomain + "\" "; - } else { - console.log('=================================='); - console.log('warning: cors is not set'); - console.log('=================================='); - } - - if (config.nodiscover) { - cmd += "--nodiscover "; - } - - if (config.mineWhenNeeded || config.mine) { - cmd += "--mine "; - } - - if (config.whisper) { - cmd += "--shh "; - rpc_api.push('shh'); - } - - cmd += '--rpcapi "' + rpc_api.join(',') + '" '; - - var accountAddress = config.account.address || address; - if (accountAddress) { - cmd += "--unlock=" + accountAddress + " "; - } - - if (config.mineWhenNeeded) { - cmd += "js .embark/development/js/mine.js"; - } - - return cmd; -}; - -module.exports = GethCommands; - diff --git a/lib/index.js b/lib/index.js index 74c7150f..97877acb 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,257 +1,172 @@ /*jshint esversion: 6 */ var async = require('async'); +//require("./core/debug_util.js")(__filename, async); + var Web3 = require('web3'); -var fs = require('fs'); -var grunt = require('grunt'); -var mkdirp = require('mkdirp'); var colors = require('colors'); -var chokidar = require('chokidar'); + +var Engine = require('./core/engine.js'); + +var Blockchain = require('./cmds/blockchain/blockchain.js'); +var Simulator = require('./cmds/simulator.js'); +var TemplateGenerator = require('./cmds/template_generator.js'); + +var Test = require('./core/test.js'); +var Logger = require('./core/logger.js'); +var Config = require('./core/config.js'); +var Events = require('./core/events.js'); + +var Dashboard = require('./dashboard/dashboard.js'); + +var IPFS = require('./upload/ipfs.js'); +var Swarm = require('./upload/swarm.js'); var Cmd = require('./cmd.js'); -var Deploy = require('./deploy.js'); -var ContractsManager = require('./contracts.js'); -var ABIGenerator = require('./abi.js'); -var TemplateGenerator = require('./template_generator.js'); -var Blockchain = require('./blockchain.js'); -var Server = require('./server.js'); -var Watch = require('./watch.js'); -var Pipeline = require('./pipeline.js'); -var Test = require('./test.js'); -var Logger = require('./logger.js'); -var Config = require('./config.js'); -var Monitor = require('./monitor.js'); -var ServicesMonitor = require('./services.js'); -var Console = require('./console.js'); -var IPFS = require('./ipfs.js'); var Embark = { + version: '2.4.0', + process: function(args) { var cmd = new Cmd(Embark); cmd.process(args); }, + initConfig: function(env, options) { + this.events = new Events(); + this.logger = new Logger({logLevel: 'debug'}); + + this.config = new Config({env: env, logger: this.logger, events: this.events}); + this.config.loadConfigFiles(options); + this.plugins = this.config.plugins; + }, + + blockchain: function(env, client) { + var blockchain = Blockchain(this.config.blockchainConfig, client, env); + blockchain.run(); + }, + + simulator: function(options) { + var simulator = new Simulator({blockchainConfig: this.config.blockchainConfig}); + simulator.run(options); + }, + generateTemplate: function(templateName, destinationFolder, name) { var templateGenerator = new TemplateGenerator(templateName); templateGenerator.generate(destinationFolder, name); }, - initConfig: function(env, options) { - 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) { - var self = this; - async.waterfall([ - function reloadFiles(callback) { - self.config.reloadConfig(); - callback(); - }, - self.buildDeployGenerate.bind(self) - ], function(err, result) { - self.logger.trace("finished".underline); - }); - }, - run: function(options) { var self = this; var env = options.env; - async.waterfall([ - function startConsole(callback) { - Embark.console = new Console(); - callback(); - }, - function startMonitor(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; - // TODO: do this after monitor is rendered - callback(); - }, - function monitorServices(callback) { - Embark.servicesMonitor = new ServicesMonitor({ - logger: Embark.logger, - config: Embark.config, - serverPort: options.serverPort - }); - Embark.servicesMonitor.startMonitor(); - callback(); - }, - self.buildDeployGenerate.bind(self), - function startAssetServer(callback) { - Embark.monitor.setStatus("Starting Server"); - var server = new Server({logger: self.logger, port: options.serverPort}); - server.start(callback); - }, - function watchFilesForChanges(callback) { - Embark.monitor.setStatus("Watching for changes"); - var watch = new Watch({logger: self.logger}); - watch.start(); - watch.on('redeploy', function() { - self.logger.info("received redeploy event"); - Embark.redeploy(); - }); - watch.on('rebuildAssets', function() { - self.logger.info("received rebuildAssets event"); - // TODO: make this more efficient - Embark.redeploy(); - }); - callback(); - } - ], function(err, result) { - Embark.monitor.setStatus("Ready".green); - self.logger.trace("finished".underline); + + var engine = new Engine({ + env: options.env, + embarkConfig: 'embark.json' }); - }, + engine.init(); - build: function(env) { - async.waterfall([ - function deployAndGenerateABI(callback) { - Embark.deploy(function(abi) { - callback(null, abi); - }); - }, - function buildPipeline(abi, callback) { - var pipeline = new Pipeline({}); - pipeline.build(abi); - callback(); - } - ], function(err, result) { - self.logger.trace("finished".underline); - }); - }, + if (!options.useDashboard) { + console.log('========================'.bold.green); + console.log(('Welcome to Embark ' + Embark.version).yellow.bold); + console.log('========================'.bold.green); + } - blockchain: function(env, client) { - var blockchain = Blockchain(this.config.blockchainConfig, client); - blockchain.run({env: env}); - }, - - buildAndDeploy: function(done) { - var self = this; - async.waterfall([ - function buildContracts(callback) { - var contractsManager = new ContractsManager({ - contractFiles: self.config.contractsFiles, - contractsConfig: self.config.contractsConfig, - logger: Embark.logger - }); - try { - contractsManager.build(); - callback(null, contractsManager); - } catch(err) { - callback(new Error(err.message)); - } - }, - function deployContracts(contractsManager, callback) { - - //TODO: figure out where to put this since the web3 can be passed along if needed - // perhaps it should go into the deploy object itself - // TODO: should come from the config object - var web3 = new Web3(); - var web3Endpoint = 'http://' + self.config.blockchainConfig.rpcHost + ':' + self.config.blockchainConfig.rpcPort; - web3.setProvider(new web3.providers.HttpProvider(web3Endpoint)); - - if (!web3.isConnected()) { - console.log(("Couldn't connect to " + web3Endpoint.underline + " are you sure it's on?").red); - console.log("make sure you have an ethereum node or simulator running. e.g 'embark blockchain'".magenta); - exit(); + async.parallel([ + function startDashboard(callback) { + if (!options.useDashboard) { + return callback(); } - web3.eth.getAccounts(function(err, accounts) { - web3.eth.defaultAccount = accounts[0]; - - var deploy = new Deploy({ - web3: web3, - contractsManager: contractsManager, - logger: Embark.logger, - chainConfig: self.config.chainTracker, - env: self.config.env - }); - deploy.deployAll(function() { - callback(null, contractsManager); - }); + var dashboard = new Dashboard({ + logger: engine.logger, + plugins: engine.plugins, + version: engine.version, + env: engine.env }); + dashboard.start(function() { + engine.events.on('abi-vanila', function(abi) { + dashboard.console.runCode(abi); + }); - } - ], function(err, result) { - if (err) { - done(err, null); - } else { - done(null, result); - } - }); - }, - - deploy: function(done) { - var self = this; - async.waterfall([ - function buildAndDeploy(callback) { - Embark.buildAndDeploy(function(contractsManager) { - callback(null, contractsManager); + callback(); }); }, - function generateABI(contractsManager, callback) { - var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager); - callback(null, abiGenerator.generateABI({useEmbarkJS: true})); - } - ], function(err, result) { - done(result); - }); - }, + function (callback) { + var pluginList = engine.plugins.listPlugins(); + if (pluginList.length > 0) { + engine.logger.info("loaded plugins: " + pluginList.join(", ")); + } + if (options.useDashboard) { + engine.startService("monitor", { + serverHost: options.serverHost, + serverPort: options.serverPort, + runWebserver: options.runWebserver + }); + } + engine.startService("pipeline"); + engine.startService("abi"); + engine.startService("deployment"); - buildDeployGenerate: function(done) { - var self = this; - - Embark.monitor.setStatus("Deploying...".magenta.underline); - async.waterfall([ - function deployAndBuildContractsManager(callback) { - Embark.buildAndDeploy(function(err, contractsManager) { - if (err) { - callback(err); - } else { - callback(null, contractsManager); + engine.deployManager.deployContracts(function() { + engine.startService("fileWatcher"); + if (options.runWebserver) { + engine.startService("webServer", { + host: options.serverHost, + port: options.serverPort + }); } + callback(); }); - }, - function generateConsoleABI(contractsManager, callback) { - var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager); - var consoleABI = abiGenerator.generateABI({useEmbarkJS: false}); - Embark.console.runCode(consoleABI); - callback(null, contractsManager); - }, - function generateABI(contractsManager, callback) { - var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager); - callback(null, abiGenerator.generateABI({useEmbarkJS: true})); - }, - function buildPipeline(abi, callback) { - Embark.monitor.setStatus("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(); } ], function(err, result) { if (err) { - self.logger.error("error deploying"); - self.logger.error(err.message); - Embark.monitor.setStatus("Deployment Error".red); + engine.logger.error(err.message); } else { - Embark.monitor.setStatus("Ready".green); + engine.logger.setStatus("Ready".green); + engine.logger.info("Looking for documentation? you can find it at ".cyan + "http://embark.readthedocs.io/".green.underline); + engine.logger.info("Ready".underline); + engine.events.emit('firstDeploymentDone'); } - done(result); + }); + }, + + build: function(options) { + var self = this; + + var engine = new Engine({ + env: options.env, + embarkConfig: 'embark.json', + interceptLogs: false + }); + engine.init(); + + async.waterfall([ + function startServices(callback) { + var pluginList = engine.plugins.listPlugins(); + if (pluginList.length > 0) { + engine.logger.info("loaded plugins: " + pluginList.join(", ")); + } + + engine.startService("pipeline"); + engine.startService("abi"); + engine.startService("deployment"); + callback(); + }, + function deploy(callback) { + engine.deployManager.deployContracts(function() { + callback(); + }); + } + ], function(err, result) { + if (err) { + engine.logger.error(err.message); + } else { + engine.logger.info("finished building".underline); + } + // needed due to child processes + process.exit(); }); }, @@ -260,9 +175,17 @@ 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/', plugins: this.plugins, storageConfig: this.config.storageConfig}); + ipfs.deploy(); + } else if (platform === 'swarm') { + var swarm = new Swarm({buildDir: 'dist/', plugins: this.plugins, storageConfig: this.config.storageConfig}); + swarm.deploy(); + } else { + console.log(("unknown platform: " + platform).red); + console.log('try "embark upload ipfs" or "embark upload swarm"'.green); + } } }; diff --git a/lib/ipfs.js b/lib/ipfs.js deleted file mode 100644 index 6333c2d6..00000000 --- a/lib/ipfs.js +++ /dev/null @@ -1,29 +0,0 @@ -var colors = require('colors'); - -var IPFS = function(options) { - this.options = options; - this.buildDir = options.buildDir || 'dist/'; -}; - -IPFS.prototype.deploy = function() { - 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"; - } - - var cmd = ipfs_bin + " add -r " + build_dir; - console.log(("=== adding " + cmd + " to ipfs").green); - - var result = exec(cmd); - 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); -}; - -module.exports = IPFS; - diff --git a/lib/pipeline.js b/lib/pipeline.js deleted file mode 100644 index a917c13b..00000000 --- a/lib/pipeline.js +++ /dev/null @@ -1,36 +0,0 @@ -/*jshint esversion: 6, loopfunc: true */ -var fs = require('fs'); -var grunt = require('grunt'); -var mkdirp = require('mkdirp'); - -var Pipeline = function(options) { - this.buildDir = options.buildDir; - this.contractsFiles = options.contractsFiles; - this.assetFiles = options.assetFiles; - this.logger = options.logger; -}; - -Pipeline.prototype.build = function(abi) { - var self = this; - for(var targetFile in this.assetFiles) { - - var content = this.assetFiles[targetFile].map(file => { - self.logger.info("reading " + file.filename); - if (file.filename === 'embark.js') { - return file.content + "\n" + abi; - } else { - return file.content; - } - }).join("\n"); - - var dir = targetFile.split('/').slice(0, -1).join('/'); - self.logger.info("creating dir " + this.buildDir + dir); - mkdirp.sync(this.buildDir + dir); - - self.logger.info("writing file " + this.buildDir + targetFile); - fs.writeFileSync(this.buildDir + targetFile, content); - } -}; - -module.exports = Pipeline; - diff --git a/lib/pipeline/pipeline.js b/lib/pipeline/pipeline.js new file mode 100644 index 00000000..08016070 --- /dev/null +++ b/lib/pipeline/pipeline.js @@ -0,0 +1,80 @@ +/*jshint esversion: 6, loopfunc: true */ +var fs = require('../core/fs.js'); + +var Pipeline = function(options) { + this.buildDir = options.buildDir; + this.contractsFiles = options.contractsFiles; + this.assetFiles = options.assetFiles; + this.logger = options.logger; + this.plugins = options.plugins; +}; + +Pipeline.prototype.build = function(abi, path) { + var self = this; + for(var targetFile in this.assetFiles) { + + var contentFiles = this.assetFiles[targetFile].map(file => { + self.logger.trace("reading " + file.filename); + + var pipelinePlugins = this.plugins.getPluginsFor('pipeline'); + + if (file.filename === 'embark.js') { + return {content: file.content + "\n" + abi, filename: file.filename, path: file.path, modified: true}; + } else if (file.filename === 'abi.js') { + return {content: abi, filename: file.filename, path: file.path, modified: true}; + } else if (['web3.js', 'ipfs.js', 'ipfs-api.js', 'orbit.js'].indexOf(file.filename) >= 0) { + file.modified = true; + return file; + } else { + + if (pipelinePlugins.length > 0) { + pipelinePlugins.forEach(function(plugin) { + try { + if (file.options && file.options.skipPipeline) { + return; + } + file.content = plugin.runPipeline({targetFile: file.filename, source: file.content}); + file.modified = true; + } + catch(err) { + self.logger.error(err.message); + } + }); + } + + return file; + } + }); + + var dir = targetFile.split('/').slice(0, -1).join('/'); + self.logger.trace("creating dir " + this.buildDir + dir); + fs.mkdirpSync(this.buildDir + dir); + + // if it's a directory + if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) { + var targetDir = targetFile; + + if (targetDir.slice(-1) !== '/') { + targetDir = targetDir + '/'; + } + + contentFiles.map(function(file) { + var filename = file.filename.replace('app/', ''); + filename = filename.replace(targetDir, ''); + self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim); + + fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true}); + }); + } else { + var content = contentFiles.map(function(file) { + return file.content; + }).join("\n"); + + self.logger.info("writing file " + (this.buildDir + targetFile).bold.dim); + fs.writeFileSync(this.buildDir + targetFile, content); + } + } +}; + +module.exports = Pipeline; + diff --git a/lib/server.js b/lib/pipeline/server.js similarity index 72% rename from lib/server.js rename to lib/pipeline/server.js index 4af23bb6..afbdad2a 100644 --- a/lib/server.js +++ b/lib/pipeline/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).bold.underline.green); + server.listen(this.port, this.hostname) ; callback(); }; diff --git a/lib/watch.js b/lib/pipeline/watch.js similarity index 72% rename from lib/watch.js rename to lib/pipeline/watch.js index 42092c8e..d1b1c8b7 100644 --- a/lib/watch.js +++ b/lib/pipeline/watch.js @@ -1,17 +1,20 @@ /*jshint esversion: 6 */ -var fs = require('fs'); var chokidar = require('chokidar'); +var fs = require('../core/fs.js'); + +// TODO: this should be receiving the config object not re-reading the +// embark.json file var Watch = function(options) { this.logger = options.logger; - this.events = {}; + this.events = options.events; }; Watch.prototype.start = function() { var self = this; // TODO: should come from the config object instead of reading the file // directly - var embarkConfig = JSON.parse(fs.readFileSync("embark.json")); + var embarkConfig = fs.readJSONSync("embark.json"); this.watchAssets(embarkConfig, function() { self.logger.trace('ready to watch asset changes'); @@ -25,7 +28,7 @@ Watch.prototype.start = function() { self.logger.trace('ready to watch config changes'); }); - this.logger.info("ready to watch changes"); + this.logger.info("ready to watch file changes"); }; Watch.prototype.watchAssets = function(embarkConfig, callback) { @@ -41,7 +44,8 @@ Watch.prototype.watchAssets = function(embarkConfig, callback) { filesToWatch, function(eventName, path) { self.logger.info(`${eventName}: ${path}`); - self.trigger('rebuildAssets', path); + self.events.emit('file-' + eventName, 'asset', path); + self.events.emit('file-event', 'asset', path); }, function() { callback(); @@ -55,7 +59,8 @@ Watch.prototype.watchContracts = function(embarkConfig, callback) { [embarkConfig.contracts], function(eventName, path) { self.logger.info(`${eventName}: ${path}`); - self.trigger('redeploy', path); + self.events.emit('file-' + eventName, 'contract', path); + self.events.emit('file-event', 'contract', path); }, function() { callback(); @@ -69,7 +74,8 @@ Watch.prototype.watchConfigs = function(callback) { "config/**/contracts.json", function(eventName, path) { self.logger.info(`${eventName}: ${path}`); - self.trigger('redeploy', path); + self.events.emit('file-' + eventName, 'config', path); + self.events.emit('file-event', 'config', path); }, function() { callback(); @@ -87,17 +93,9 @@ Watch.prototype.watchFiles = function(files, changeCallback, doneCallback) { configWatcher .on('add', path => changeCallback('add', path)) - .on('change', path => changeCallback('add', path)) - .on('unlink', path => changeCallback('add', path)) + .on('change', path => changeCallback('change', path)) + .on('unlink', path => changeCallback('remove', path)) .on('ready', doneCallback); }; -Watch.prototype.on = function(eventName, callback) { - this.events[eventName] = callback; -}; - -Watch.prototype.trigger = function(eventName, values) { - this.events[eventName](values); -}; - module.exports = Watch; diff --git a/lib/template_generator.js b/lib/template_generator.js deleted file mode 100644 index f140b104..00000000 --- a/lib/template_generator.js +++ /dev/null @@ -1,27 +0,0 @@ -// TODO: replace with something else more native to node -require('shelljs/global'); -var path = require('path'); -var wrench = require('wrench'); - -var run = function(cmd) { - if (exec(cmd).code !== 0) { - exit(); - } -}; - -var TemplateGenerator = function(templateName) { - this.templateName = templateName; -}; - -TemplateGenerator.prototype.generate = function(destinationFolder, name) { - var templatePath = path.join(__dirname + '/../' + this.templateName); - - wrench.copyDirSyncRecursive(templatePath, destinationFolder + name); - - cd(destinationFolder + name); - run('npm install'); - console.log('\n\ninit complete'.green); - console.log('\n\app ready at '.green + destinationFolder + name); -}; - -module.exports = TemplateGenerator; diff --git a/lib/test.js b/lib/test.js deleted file mode 100644 index 9667ae07..00000000 --- a/lib/test.js +++ /dev/null @@ -1,73 +0,0 @@ -var async = require('async'); -var Web3 = require('web3'); -var Embark = require('./index.js'); -var ContractsManager = require('./contracts.js'); -var Deploy = require('./deploy.js'); -var TestLogger = require('./test_logger.js'); -var Config = require('./config.js'); -var ABIGenerator = require('./abi.js'); - -var Test = function(options) { - try { - this.sim = require('ethereumjs-testrpc'); - } catch(e) { - this.sim = false; - } - - if (this.sim === false) { - console.log('Simulator not found; Please install it with "npm install -g ethereumjs-testrpc'); - console.log('For more information see https://github.com/ethereumjs/testrpc'); - exit(); - } -}; - -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([ - function buildContracts(callback) { - var config = new Config({env: 'test'}); - config.contractsFiles = config.loadFiles(["app/contracts/**"]); - config.contractsConfig = {contracts: contractsConfig} ; - - var contractsManager = new ContractsManager({ - contractFiles: config.contractsFiles, - contractsConfig: config.contractsConfig, - logger: logger - }); - contractsManager.build(); - callback(null, contractsManager); - }, - function deployContracts(contractsManager, callback) { - var deploy = new Deploy({ - web3: self.web3, - contractsManager: contractsManager, - logger: logger, - chainConfig: false, - env: 'test' - }); - deploy.deployAll(function() { - callback(null, contractsManager); - }); - }, - function generateABI(contractsManager, callback) { - var abiGenerator = new ABIGenerator({}, contractsManager); - var ABI = abiGenerator.generateContracts(false); - callback(null, ABI); - } - ], function(err, result) { - self.web3.eth.getAccounts(function(err, accounts) { - var web3 = self.web3; - web3.eth.defaultAccount = accounts[0]; - // TODO: replace evals with separate process so it's isolated and with - // a callback - eval(result); // jshint ignore:line - cb(); - }); - }); -}; - -module.exports = Test; diff --git a/lib/upload/ipfs.js b/lib/upload/ipfs.js new file mode 100644 index 00000000..09da3cf4 --- /dev/null +++ b/lib/upload/ipfs.js @@ -0,0 +1,56 @@ +var colors = require('colors'); +var async = require('async'); +var shelljs = require('shelljs'); + +var IPFS = function(options) { + this.options = options; + this.buildDir = options.buildDir || 'dist/'; + this.plugins = options.plugins; + this.storageConfig = options.storageConfig; + this.configIpfsBin = this.storageConfig.ipfs_bin || "ipfs"; +}; + +IPFS.prototype.deploy = function() { + var self = this; + async.waterfall([ + function findBinary(callback) { + var ipfs_bin = shelljs.exec('which ' + self.configIpfsBin).output.split("\n")[0]; + + if (ipfs_bin === 'ipfs not found' || ipfs_bin === ''){ + console.log(('=== WARNING: ' + self.configIpfsBin + ' not found or not in the path. Guessing ~/go/bin/ipfs for path').yellow); + ipfs_bin = "~/go/bin/ipfs"; + } + + 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 = shelljs.exec(cmd); + + 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]; + + 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/upload/swarm.js b/lib/upload/swarm.js new file mode 100644 index 00000000..667e0e6c --- /dev/null +++ b/lib/upload/swarm.js @@ -0,0 +1,55 @@ +var colors = require('colors'); +var async = require('async'); +var shelljs = require('shelljs'); + +var Swarm = function(options) { + this.options = options; + this.buildDir = options.buildDir || 'dist/'; +}; + +Swarm.prototype.deploy = function() { + var self = this; + async.waterfall([ + function findBinary(callback) { + var swarm_bin = shelljs.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"; + } + + 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 = shelljs.exec(cmd); + + return callback(null, result); + }, + function getHashFromOutput(result, callback) { + if (result.code !== 0) { + return callback("couldn't upload, is the swarm daemon running?"); + } + + 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; + diff --git a/package.json b/package.json index 6158b804..06833395 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "embark", - "version": "2.1.4", + "version": "2.4.0", "description": "Embark is a framework that allows you to easily develop and deploy DApps", "scripts": { "test": "grunt jshint && mocha test/ --no-timeouts" @@ -12,40 +12,49 @@ "directories": { "lib": "./lib" }, + "repository": { + "type": "git", + "url": "https://github.com/iurimatias/embark-framework.git" + }, "dependencies": { "async": "^2.0.1", - "bignumber.js": "debris/bignumber.js#master", "blessed": "^0.1.81", - "bluebird": "^3.4.1", "chokidar": "^1.6.0", "colors": "^1.1.2", "commander": "^2.8.1", "finalhandler": "^0.5.0", - "grunt": "^0.4.5", - "json-honey": "^0.4.1", + "fs-extra": "^2.0.0", + "globule": "^1.1.0", "merge": "^1.2.0", - "meteor-build-client": "^0.1.6", - "mkdirp": "^0.5.1", - "solc": "^0.4.4", - "read-yaml": "^1.0.0", - "request": "^2.75.0", "serve-static": "^1.11.1", "shelljs": "^0.5.0", - "toposort": "^0.2.10", - "web3": "^0.15.0", - "wrench": "^1.5.8" + "solc": "0.4.8", + "toposort": "^1.0.0", + "web3": "^0.18.2" }, "author": "Iuri Matias ", "contributors": [], - "license": "ISC", + "keywords": [ + "ethereum", + "dapps", + "ipfs", + "orbit", + "solidity", + "solc", + "blockchain", + "serverless" + ], + "homepage": "https://github.com/iurimatias/embark-framework", + "license": "MIT", "devDependencies": { - "grunt-cli": "^0.1.13", - "grunt-mocha-test": "^0.12.7", + "grunt": "^1.0.1", + "grunt-cli": "^1.2.0", "grunt-contrib-jshint": "^1.0.0", + "grunt-mocha-test": "^0.13.2", "matchdep": "^1.0.1", - "mocha": "^2.2.5", + "mocha": "^3.2.0", "mocha-sinon": "^1.1.4", "sinon": "^1.15.4", - "toposort": "^0.2.12" + "toposort": "^1.0.0" } } diff --git a/test/abi.js b/test/abi.js index 96351e1b..4d2533ba 100644 --- a/test/abi.js +++ b/test/abi.js @@ -1,5 +1,5 @@ /*globals describe, it*/ -var ABIGenerator = require('../lib/abi.js'); +var ABIGenerator = require('../lib/contracts/abi.js'); var assert = require('assert'); // TODO: instead 'eval' the code with a fake web3 object @@ -7,7 +7,7 @@ var assert = require('assert'); describe('embark.ABIGenerator', function() { describe('#generateProvider', function() { - var generator = new ABIGenerator({rpcHost: 'somehost', rpcPort: '1234'}, {}); + var generator = new ABIGenerator({blockchainConfig: {rpcHost: 'somehost', rpcPort: '1234'}, contractsManager: {}}); it('should generate code to connect to a provider', function() { var providerCode = "\nif (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {\n\tweb3 = new Web3(web3.currentProvider);\n} else if (typeof Web3 !== 'undefined') {\n\tweb3 = new Web3(new Web3.providers.HttpProvider(\"http://somehost:1234\"));\n}\nweb3.eth.defaultAccount = web3.eth.accounts[0];"; @@ -17,7 +17,7 @@ describe('embark.ABIGenerator', function() { }); describe('#generateContracts', function() { - var generator = new ABIGenerator({}, { + var generator = new ABIGenerator({blockchainConfig: {}, contractsManager: { contracts: { SimpleStorage: { 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"}], @@ -32,7 +32,7 @@ describe('embark.ABIGenerator', function() { code: '123456' } } - }); + }}); describe('with EmbarkJS', function() { var withEmbarkJS = true; diff --git a/test/blockchain.js b/test/blockchain.js index 45f1e3d9..43fefaf5 100644 --- a/test/blockchain.js +++ b/test/blockchain.js @@ -1,5 +1,5 @@ /*globals describe, it*/ -var Blockchain = require('../lib/blockchain.js'); +var Blockchain = require('../lib/cmds/blockchain/blockchain.js'); var assert = require('assert'); describe('embark.Blockchain', function() { @@ -14,17 +14,22 @@ describe('embark.Blockchain', function() { var config = { networkType: 'custom', genesisBlock: false, + geth_bin: 'geth', datadir: false, mineWhenNeeded: false, rpcHost: 'localhost', rpcPort: 8545, + rpcApi: ['eth', 'web3', 'net'], rpcCorsDomain: false, networkId: 12301, port: 30303, nodiscover: false, + maxpeers: 25, mine: false, + vmdebug: false, whisper: true, - account: {} + account: {}, + bootnodes: "" }; var blockchain = Blockchain(config, 'geth'); @@ -37,17 +42,22 @@ describe('embark.Blockchain', function() { var config = { networkType: 'livenet', genesisBlock: 'foo/bar/genesis.json', + geth_bin: 'geth', datadir: '/foo/datadir/', mineWhenNeeded: true, rpcHost: 'someserver', rpcPort: 12345, + rpcApi: ['eth', 'web3', 'net'], rpcCorsDomain: true, networkId: 1, port: 123456, nodiscover: true, + maxpeers: 25, mine: true, + vmdebug: false, whisper: false, - account: {} + account: {}, + bootnodes: "" }; var blockchain = Blockchain(config, 'geth'); diff --git a/test/compiler.js b/test/compiler.js index c86e1916..c44d3ed9 100644 --- a/test/compiler.js +++ b/test/compiler.js @@ -1,5 +1,6 @@ /*globals describe, it*/ -var Compiler = require('../lib/compiler.js'); +var Compiler = require('../lib/contracts/compiler.js'); +var TestLogger = require('../lib/core/test_logger.js'); var assert = require('assert'); var fs = require('fs'); @@ -8,21 +9,23 @@ var readFile = function(file) { }; describe('embark.Compiler', function() { - var compiler = new Compiler(); + var compiler = new Compiler({logger: new TestLogger({})}); describe('#compile_solidity', function() { - var compiledContracts = compiler.compile_solidity([ - readFile('test/contracts/simple_storage.sol'), - readFile('test/contracts/token.sol') - ]); - 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":"606060405234610000576040516020806100f083398101604052515b60008190555b505b60bf806100316000396000f300606060405263ffffffff60e060020a6000350416632a1afcd98114603657806360fe47b11460525780636d4ce63c146061575b6000565b346000576040607d565b60408051918252519081900360200190f35b34600057605f6004356083565b005b346000576040608c565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b905600a165627a7a72305820a250be048d43f54e9afbb37211dc73ba843d23b95863b60afe703903500077220029","realRuntimeBytecode": "606060405263ffffffff60e060020a6000350416632a1afcd98114603657806360fe47b11460525780636d4ce63c146061575b6000565b346000576040607d565b60408051918252519081900360200190f35b34600057605f6004356083565b005b346000576040608c565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b905600a165627a7a72305820","runtimeBytecode":"606060405263ffffffff60e060020a6000350416632a1afcd98114603657806360fe47b11460525780636d4ce63c146061575b6000565b346000576040607d565b60408051918252519081900360200190f35b34600057605f6004356083565b005b346000576040608c565b60408051918252519081900360200190f35b60005481565b60008190555b50565b6000545b905600a165627a7a72305820a250be048d43f54e9afbb37211dc73ba843d23b95863b60afe703903500077220029","swarmHash": "a250be048d43f54e9afbb37211dc73ba843d23b95863b60afe70390350007722","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"}]}; - it('should generate compiled code and abi', function() { - assert.deepEqual(compiledContracts, expectedObject); + expectedObject["Token"] = {"code":"6060604052346100005760405160208061048e83398101604052515b600160a060020a033316600090815260208190526040902081905560028190555b505b6104418061004d6000396000f3006060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461006157806318160ddd1461009157806323b872dd146100b057806370a08231146100e6578063a9059cbb14610111578063dd62ed3e14610141575b610000565b346100005761007d600160a060020a0360043516602435610172565b604080519115158252519081900360200190f35b346100005761009e6101dd565b60408051918252519081900360200190f35b346100005761007d600160a060020a03600435811690602435166044356101e4565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435166102f8565b60408051918252519081900360200190f35b346100005761007d600160a060020a0360043516602435610317565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435811690602435166103da565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a0383166000908152602081905260408120548290101561020a57610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561023e57610000565b600160a060020a0383166000908152602081905260409020546102619083610407565b151561026c57610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561033d57610000565b600160a060020a0383166000908152602081905260409020546103609083610407565b151561036b57610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b929150505600a165627a7a7230582017291fa7c1b9234972e866bb8b730096a40f8610da4684f7977498fc0ee8f75b0029","realRuntimeBytecode": "6060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461006157806318160ddd1461009157806323b872dd146100b057806370a08231146100e6578063a9059cbb14610111578063dd62ed3e14610141575b610000565b346100005761007d600160a060020a0360043516602435610172565b604080519115158252519081900360200190f35b346100005761009e6101dd565b60408051918252519081900360200190f35b346100005761007d600160a060020a03600435811690602435166044356101e4565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435166102f8565b60408051918252519081900360200190f35b346100005761007d600160a060020a0360043516602435610317565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435811690602435166103da565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a0383166000908152602081905260408120548290101561020a57610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561023e57610000565b600160a060020a0383166000908152602081905260409020546102619083610407565b151561026c57610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561033d57610000565b600160a060020a0383166000908152602081905260409020546103609083610407565b151561036b57610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b929150505600a165627a7a72305820","runtimeBytecode":"6060604052361561005c5763ffffffff60e060020a600035041663095ea7b3811461006157806318160ddd1461009157806323b872dd146100b057806370a08231146100e6578063a9059cbb14610111578063dd62ed3e14610141575b610000565b346100005761007d600160a060020a0360043516602435610172565b604080519115158252519081900360200190f35b346100005761009e6101dd565b60408051918252519081900360200190f35b346100005761007d600160a060020a03600435811690602435166044356101e4565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435166102f8565b60408051918252519081900360200190f35b346100005761007d600160a060020a0360043516602435610317565b604080519115158252519081900360200190f35b346100005761009e600160a060020a03600435811690602435166103da565b60408051918252519081900360200190f35b600160a060020a03338116600081815260016020908152604080832094871680845294825280832086905580518681529051929493927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060015b92915050565b6002545b90565b600160a060020a0383166000908152602081905260408120548290101561020a57610000565b600160a060020a03808516600090815260016020908152604080832033909416835292905220548290101561023e57610000565b600160a060020a0383166000908152602081905260409020546102619083610407565b151561026c57610000565b600160a060020a038085166000818152600160209081526040808320338616845282528083208054889003905583835282825280832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b9392505050565b600160a060020a0381166000908152602081905260409020545b919050565b600160a060020a0333166000908152602081905260408120548290101561033d57610000565b600160a060020a0383166000908152602081905260409020546103609083610407565b151561036b57610000565b600160a060020a0333811660008181526020818152604080832080548890039055938716808352918490208054870190558351868152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a35060015b92915050565b600160a060020a038083166000908152600160209081526040808320938516835292905220545b92915050565b808201829010155b929150505600a165627a7a7230582017291fa7c1b9234972e866bb8b730096a40f8610da4684f7977498fc0ee8f75b0029","swarmHash": "17291fa7c1b9234972e866bb8b730096a40f8610da4684f7977498fc0ee8f75b","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(done) { + compiler.compile_solidity([ + readFile('test/contracts/simple_storage.sol'), + readFile('test/contracts/token.sol') + ], function(err, compiledContracts) { + assert.deepEqual(compiledContracts, expectedObject); + done(); + }); }); }); diff --git a/test/config.js b/test/config.js index 3f3ef920..66945520 100644 --- a/test/config.js +++ b/test/config.js @@ -1,5 +1,6 @@ /*globals describe, it*/ -var Config = require('../lib/config.js'); +var Config = require('../lib/core/config.js'); +var Plugins = require('../lib/core/plugins.js'); var assert = require('assert'); var fs = require('fs'); @@ -8,11 +9,13 @@ describe('embark.Config', function() { env: 'myenv', configDir: './test/test1/config/' }); + config.plugins = new Plugins({plugins: {}}); describe('#loadBlockchainConfigFile', function() { it('should load blockchain config correctly', function() { config.loadBlockchainConfigFile(); var expectedConfig = { + "enabled": true, "networkType": "custom", "genesisBlock": "config/development/genesis.json", "datadir": ".embark/development/datadir", diff --git a/test/console.js b/test/console.js new file mode 100644 index 00000000..a1d987e1 --- /dev/null +++ b/test/console.js @@ -0,0 +1,24 @@ +/*globals describe, it*/ +var Console = require('../lib/dashboard/console.js'); +var Plugins = require('../lib/core/plugins.js'); +var assert = require('assert'); + +describe('embark.Console', function() { + var plugins = new Plugins({plugins: {}}); + var console = new Console({plugins: plugins, version: '2.3.1'}); + + describe('#executeCmd', function() { + + describe('command: help', function() { + + it('it 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.3.1'); + assert.equal(lines[2], 'possible commands are:'); + done(); + }); + }); + }); + }); +}); diff --git a/test/contracts.js b/test/contracts.js new file mode 100644 index 00000000..873383a1 --- /dev/null +++ b/test/contracts.js @@ -0,0 +1,163 @@ +/*globals describe, it*/ +var ContractsManager = require('../lib/contracts/contracts.js'); +var Logger = require('../lib/core/logger.js'); +var assert = require('assert'); +var fs = require('fs'); + +var readFile = function(file) { + return {filename: file, content: fs.readFileSync(file).toString()}; +}; + +describe('embark.Contratcs', function() { + describe('simple', function() { + var contractsManager = new ContractsManager({ + contractFiles: [ + readFile('test/contracts/simple_storage.sol'), + readFile('test/contracts/token.sol') + ], + contractsConfig: { + "gas": "auto", + "contracts": { + "Token": { + "args": [ + 100 + ] + }, + "SimpleStorage": { + "args": [ + 200 + ] + } + } + }, + logger: new Logger({}) + }); + + describe('#build', function() { + it('generate contracts', function(done) { + contractsManager.build(function(err, result) { + if (err) { + throw err; + } + + var contracts = contractsManager.listContracts(); + assert.equal(contracts.length, 2); + + assert.equal(contracts[0].deploy, true); + assert.deepEqual(contracts[0].args, [100]); + assert.equal(contracts[0].className, "Token"); + assert.deepEqual(contracts[0].gas, 725000); + //assert.equal(contracts[0].gasPrice, []); // TODO: test this one + assert.equal(contracts[0].type, 'file'); + //assert.equal(contracts[0].abiDefinition, ''); + //assert.equal(contracts[0].code, ''); + //assert.equal(contracts[0].runtimeBytecode, ''); + + assert.equal(contracts[1].deploy, true); + assert.deepEqual(contracts[1].args, [200]); + assert.equal(contracts[1].className, "SimpleStorage"); + assert.deepEqual(contracts[1].gas, 725000); + //assert.equal(contracts[1].gasPrice, []); // TODO: test this one + assert.equal(contracts[1].type, 'file'); + //assert.equal(contracts[1].abiDefinition, ''); + //assert.equal(contracts[1].code, ''); + //assert.equal(contracts[1].runtimeBytecode, ''); + done(); + }); + }); + }); + }); + + describe('config with contract instances', function() { + var contractsManager = new ContractsManager({ + contractFiles: [ + readFile('test/contracts/simple_storage.sol'), + readFile('test/contracts/token_storage.sol') + ], + contractsConfig: { + "gas": "auto", + "contracts": { + "TokenStorage": { + "args": [ + 100, + "$SimpleStorage" + ] + }, + "MySimpleStorage": { + "instanceOf": "SimpleStorage", + "args": [ + 300 + ] + }, + "SimpleStorage": { + "args": [ + 200 + ] + }, + "AnotherSimpleStorage": { + "instanceOf": "SimpleStorage" + } + } + }, + logger: new Logger({}) + }); + + describe('#build', function() { + it('generate contracts', function(done) { + contractsManager.build(function(err, result) { + if (err) { + throw err; + } + + var contracts = contractsManager.listContracts(); + assert.equal(contracts.length, 4); + + assert.equal(contracts[0].className, "MySimpleStorage"); + assert.equal(contracts[1].className, "AnotherSimpleStorage"); + assert.equal(contracts[2].className, "SimpleStorage"); + assert.equal(contracts[3].className, "TokenStorage"); + + // TokenStorage + assert.equal(contracts[3].deploy, true); + assert.deepEqual(contracts[3].args, [100, '$SimpleStorage']); + assert.deepEqual(contracts[3].gas, 725000); + assert.equal(contracts[3].type, 'file'); + //assert.equal(contracts[3].abiDefinition, ''); + //assert.equal(contracts[3].code, ''); + //assert.equal(contracts[3].runtimeBytecode, ''); + + var parentContract = contracts[2]; + + //MySimpleStorage + assert.equal(contracts[0].deploy, true); + assert.deepEqual(contracts[0].args, [300]); + assert.deepEqual(contracts[0].gas, 725000); + assert.equal(contracts[0].type, 'instance'); + assert.equal(contracts[0].abiDefinition, parentContract.abiDefinition); + assert.equal(contracts[0].code, parentContract.code); + assert.equal(contracts[0].runtimeBytecode, parentContract.runtimeBytecode); + + // SimpleStorage + assert.equal(contracts[2].deploy, true); + assert.deepEqual(contracts[2].args, [200]); + assert.deepEqual(contracts[2].gas, 725000); + assert.equal(contracts[2].type, 'file'); + //assert.equal(contracts[2].abiDefinition, ''); + //assert.equal(contracts[2].code, ''); + //assert.equal(contracts[2].runtimeBytecode, ''); + + // AnotherSimpleStorage + assert.equal(contracts[1].deploy, true); + assert.deepEqual(contracts[1].args, [200]); + assert.deepEqual(contracts[1].gas, 725000); + assert.equal(contracts[1].type, 'instance'); + assert.equal(contracts[1].abiDefinition, parentContract.abiDefinition); + assert.equal(contracts[1].code, parentContract.code); + assert.equal(contracts[1].runtimeBytecode, parentContract.runtimeBytecode); + done(); + }); + }); + }); + }); + +}); diff --git a/test/contracts/simple_storage.sol b/test/contracts/simple_storage.sol index 46e047eb..4b24a2fa 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.7; contract SimpleStorage { uint public storedData; diff --git a/test/contracts/token.sol b/test/contracts/token.sol index 58d182ad..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.2; +pragma solidity ^0.4.7; contract Token { event Transfer(address indexed from, address indexed to, uint value); diff --git a/test/contracts/token_storage.sol b/test/contracts/token_storage.sol new file mode 100644 index 00000000..dade953f --- /dev/null +++ b/test/contracts/token_storage.sol @@ -0,0 +1,67 @@ +// https://github.com/nexusdev/erc20/blob/master/contracts/base.sol + +pragma solidity ^0.4.7; +contract TokenStorage { + + event Transfer(address indexed from, address indexed to, uint value); + event Approval( address indexed owner, address indexed spender, uint value); + + mapping( address => uint ) _balances; + mapping( address => mapping( address => uint ) ) _approvals; + uint _supply; + address public addr; + function TokenStorage( uint initial_balance, address _addr) { + _balances[msg.sender] = initial_balance; + _supply = initial_balance; + addr = _addr; + } + function totalSupply() constant returns (uint supply) { + return _supply; + } + function balanceOf( address who ) constant returns (uint value) { + return _balances[who]; + } + function transfer( address to, uint value) returns (bool ok) { + if( _balances[msg.sender] < value ) { + throw; + } + if( !safeToAdd(_balances[to], value) ) { + throw; + } + _balances[msg.sender] -= value; + _balances[to] += value; + Transfer( msg.sender, to, value ); + return true; + } + function transferFrom( address from, address to, uint value) returns (bool ok) { + // if you don't have enough balance, throw + if( _balances[from] < value ) { + throw; + } + // if you don't have approval, throw + if( _approvals[from][msg.sender] < value ) { + throw; + } + if( !safeToAdd(_balances[to], value) ) { + throw; + } + // transfer and return true + _approvals[from][msg.sender] -= value; + _balances[from] -= value; + _balances[to] += value; + Transfer( from, to, value ); + return true; + } + function approve(address spender, uint value) returns (bool ok) { + // TODO: should increase instead + _approvals[msg.sender][spender] = value; + Approval( msg.sender, spender, value ); + return true; + } + function allowance(address owner, address spender) constant returns (uint _allowance) { + return _approvals[owner][spender]; + } + function safeToAdd(uint a, uint b) internal returns (bool) { + return (a + b >= a); + } +} diff --git a/test_app/.gitignore b/test_app/.gitignore new file mode 100644 index 00000000..77bcafb1 --- /dev/null +++ b/test_app/.gitignore @@ -0,0 +1,5 @@ +.embark/ +node_modules/ +dist/ +config/production/password +config/livenet/password diff --git a/test_app/README.md b/test_app/README.md new file mode 100644 index 00000000..47ad5712 --- /dev/null +++ b/test_app/README.md @@ -0,0 +1,8 @@ +Test App for integration testing purposes. + +```../bin/embark run``` to check if everything is behaving as expected + +```../bin/embark test``` to see tests are working as expected + +```dist/index.html``` and ```dist/test.html``` to check different functionality + diff --git a/test_app/app/contracts/another_storage.sol b/test_app/app/contracts/another_storage.sol new file mode 100644 index 00000000..ba837449 --- /dev/null +++ b/test_app/app/contracts/another_storage.sol @@ -0,0 +1,9 @@ +pragma solidity ^0.4.7; +contract AnotherStorage { + address public simpleStorageAddress; + + function AnotherStorage(address addr) { + simpleStorageAddress = addr; + } + +} diff --git a/test_app/app/contracts/simple_storage.sol b/test_app/app/contracts/simple_storage.sol new file mode 100644 index 00000000..7ca17d62 --- /dev/null +++ b/test_app/app/contracts/simple_storage.sol @@ -0,0 +1,21 @@ +pragma solidity ^0.4.7; +contract SimpleStorage { + uint public storedData; + + function SimpleStorage(uint initialValue) { + storedData = initialValue; + } + + function set(uint x) { + storedData = x; + } + + function get() constant returns (uint retVal) { + return storedData; + } + + function getS() constant returns (string d) { + return "hello"; + } + +} diff --git a/test_app/app/contracts/token.sol b/test_app/app/contracts/token.sol new file mode 100644 index 00000000..0eff9e71 --- /dev/null +++ b/test_app/app/contracts/token.sol @@ -0,0 +1,66 @@ +// https://github.com/nexusdev/erc20/blob/master/contracts/base.sol + +pragma solidity ^0.4.2; +contract Token { + + event Transfer(address indexed from, address indexed to, uint value); + event Approval( address indexed owner, address indexed spender, uint value); + + mapping( address => uint ) _balances; + mapping( address => mapping( address => uint ) ) _approvals; + uint public _supply; + //uint public _supply2; + function Token( uint initial_balance ) { + _balances[msg.sender] = initial_balance; + _supply = initial_balance; + } + function totalSupply() constant returns (uint supply) { + return _supply; + } + function balanceOf( address who ) constant returns (uint value) { + return _balances[who]; + } + function transfer( address to, uint value) returns (bool ok) { + if( _balances[msg.sender] < value ) { + throw; + } + if( !safeToAdd(_balances[to], value) ) { + throw; + } + _balances[msg.sender] -= value; + _balances[to] += value; + Transfer( msg.sender, to, value ); + return true; + } + function transferFrom( address from, address to, uint value) returns (bool ok) { + // if you don't have enough balance, throw + if( _balances[from] < value ) { + throw; + } + // if you don't have approval, throw + if( _approvals[from][msg.sender] < value ) { + throw; + } + if( !safeToAdd(_balances[to], value) ) { + throw; + } + // transfer and return true + _approvals[from][msg.sender] -= value; + _balances[from] -= value; + _balances[to] += value; + Transfer( from, to, value ); + return true; + } + function approve(address spender, uint value) returns (bool ok) { + // TODO: should increase instead + _approvals[msg.sender][spender] = value; + Approval( msg.sender, spender, value ); + return true; + } + function allowance(address owner, address spender) constant returns (uint _allowance) { + return _approvals[owner][spender]; + } + function safeToAdd(uint a, uint b) internal returns (bool) { + return (a + b >= a); + } +} diff --git a/test_app/app/css/.gitkeep b/test_app/app/css/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/test_app/app/css/bootstrap-theme.css b/test_app/app/css/bootstrap-theme.css new file mode 100644 index 00000000..ebe57fbf --- /dev/null +++ b/test_app/app/css/bootstrap-theme.css @@ -0,0 +1,587 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ +.btn-default, +.btn-primary, +.btn-success, +.btn-info, +.btn-warning, +.btn-danger { + text-shadow: 0 -1px 0 rgba(0, 0, 0, .2); + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 1px rgba(0, 0, 0, .075); +} +.btn-default:active, +.btn-primary:active, +.btn-success:active, +.btn-info:active, +.btn-warning:active, +.btn-danger:active, +.btn-default.active, +.btn-primary.active, +.btn-success.active, +.btn-info.active, +.btn-warning.active, +.btn-danger.active { + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); +} +.btn-default.disabled, +.btn-primary.disabled, +.btn-success.disabled, +.btn-info.disabled, +.btn-warning.disabled, +.btn-danger.disabled, +.btn-default[disabled], +.btn-primary[disabled], +.btn-success[disabled], +.btn-info[disabled], +.btn-warning[disabled], +.btn-danger[disabled], +fieldset[disabled] .btn-default, +fieldset[disabled] .btn-primary, +fieldset[disabled] .btn-success, +fieldset[disabled] .btn-info, +fieldset[disabled] .btn-warning, +fieldset[disabled] .btn-danger { + -webkit-box-shadow: none; + box-shadow: none; +} +.btn-default .badge, +.btn-primary .badge, +.btn-success .badge, +.btn-info .badge, +.btn-warning .badge, +.btn-danger .badge { + text-shadow: none; +} +.btn:active, +.btn.active { + background-image: none; +} +.btn-default { + text-shadow: 0 1px 0 #fff; + background-image: -webkit-linear-gradient(top, #fff 0%, #e0e0e0 100%); + background-image: -o-linear-gradient(top, #fff 0%, #e0e0e0 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#e0e0e0)); + background-image: linear-gradient(to bottom, #fff 0%, #e0e0e0 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #dbdbdb; + border-color: #ccc; +} +.btn-default:hover, +.btn-default:focus { + background-color: #e0e0e0; + background-position: 0 -15px; +} +.btn-default:active, +.btn-default.active { + background-color: #e0e0e0; + border-color: #dbdbdb; +} +.btn-default.disabled, +.btn-default[disabled], +fieldset[disabled] .btn-default, +.btn-default.disabled:hover, +.btn-default[disabled]:hover, +fieldset[disabled] .btn-default:hover, +.btn-default.disabled:focus, +.btn-default[disabled]:focus, +fieldset[disabled] .btn-default:focus, +.btn-default.disabled.focus, +.btn-default[disabled].focus, +fieldset[disabled] .btn-default.focus, +.btn-default.disabled:active, +.btn-default[disabled]:active, +fieldset[disabled] .btn-default:active, +.btn-default.disabled.active, +.btn-default[disabled].active, +fieldset[disabled] .btn-default.active { + background-color: #e0e0e0; + background-image: none; +} +.btn-primary { + background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#265a88)); + background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #245580; +} +.btn-primary:hover, +.btn-primary:focus { + background-color: #265a88; + background-position: 0 -15px; +} +.btn-primary:active, +.btn-primary.active { + background-color: #265a88; + border-color: #245580; +} +.btn-primary.disabled, +.btn-primary[disabled], +fieldset[disabled] .btn-primary, +.btn-primary.disabled:hover, +.btn-primary[disabled]:hover, +fieldset[disabled] .btn-primary:hover, +.btn-primary.disabled:focus, +.btn-primary[disabled]:focus, +fieldset[disabled] .btn-primary:focus, +.btn-primary.disabled.focus, +.btn-primary[disabled].focus, +fieldset[disabled] .btn-primary.focus, +.btn-primary.disabled:active, +.btn-primary[disabled]:active, +fieldset[disabled] .btn-primary:active, +.btn-primary.disabled.active, +.btn-primary[disabled].active, +fieldset[disabled] .btn-primary.active { + background-color: #265a88; + background-image: none; +} +.btn-success { + background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%); + background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#419641)); + background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #3e8f3e; +} +.btn-success:hover, +.btn-success:focus { + background-color: #419641; + background-position: 0 -15px; +} +.btn-success:active, +.btn-success.active { + background-color: #419641; + border-color: #3e8f3e; +} +.btn-success.disabled, +.btn-success[disabled], +fieldset[disabled] .btn-success, +.btn-success.disabled:hover, +.btn-success[disabled]:hover, +fieldset[disabled] .btn-success:hover, +.btn-success.disabled:focus, +.btn-success[disabled]:focus, +fieldset[disabled] .btn-success:focus, +.btn-success.disabled.focus, +.btn-success[disabled].focus, +fieldset[disabled] .btn-success.focus, +.btn-success.disabled:active, +.btn-success[disabled]:active, +fieldset[disabled] .btn-success:active, +.btn-success.disabled.active, +.btn-success[disabled].active, +fieldset[disabled] .btn-success.active { + background-color: #419641; + background-image: none; +} +.btn-info { + background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); + background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#2aabd2)); + background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #28a4c9; +} +.btn-info:hover, +.btn-info:focus { + background-color: #2aabd2; + background-position: 0 -15px; +} +.btn-info:active, +.btn-info.active { + background-color: #2aabd2; + border-color: #28a4c9; +} +.btn-info.disabled, +.btn-info[disabled], +fieldset[disabled] .btn-info, +.btn-info.disabled:hover, +.btn-info[disabled]:hover, +fieldset[disabled] .btn-info:hover, +.btn-info.disabled:focus, +.btn-info[disabled]:focus, +fieldset[disabled] .btn-info:focus, +.btn-info.disabled.focus, +.btn-info[disabled].focus, +fieldset[disabled] .btn-info.focus, +.btn-info.disabled:active, +.btn-info[disabled]:active, +fieldset[disabled] .btn-info:active, +.btn-info.disabled.active, +.btn-info[disabled].active, +fieldset[disabled] .btn-info.active { + background-color: #2aabd2; + background-image: none; +} +.btn-warning { + background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); + background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#eb9316)); + background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #e38d13; +} +.btn-warning:hover, +.btn-warning:focus { + background-color: #eb9316; + background-position: 0 -15px; +} +.btn-warning:active, +.btn-warning.active { + background-color: #eb9316; + border-color: #e38d13; +} +.btn-warning.disabled, +.btn-warning[disabled], +fieldset[disabled] .btn-warning, +.btn-warning.disabled:hover, +.btn-warning[disabled]:hover, +fieldset[disabled] .btn-warning:hover, +.btn-warning.disabled:focus, +.btn-warning[disabled]:focus, +fieldset[disabled] .btn-warning:focus, +.btn-warning.disabled.focus, +.btn-warning[disabled].focus, +fieldset[disabled] .btn-warning.focus, +.btn-warning.disabled:active, +.btn-warning[disabled]:active, +fieldset[disabled] .btn-warning:active, +.btn-warning.disabled.active, +.btn-warning[disabled].active, +fieldset[disabled] .btn-warning.active { + background-color: #eb9316; + background-image: none; +} +.btn-danger { + background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%); + background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c12e2a)); + background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-color: #b92c28; +} +.btn-danger:hover, +.btn-danger:focus { + background-color: #c12e2a; + background-position: 0 -15px; +} +.btn-danger:active, +.btn-danger.active { + background-color: #c12e2a; + border-color: #b92c28; +} +.btn-danger.disabled, +.btn-danger[disabled], +fieldset[disabled] .btn-danger, +.btn-danger.disabled:hover, +.btn-danger[disabled]:hover, +fieldset[disabled] .btn-danger:hover, +.btn-danger.disabled:focus, +.btn-danger[disabled]:focus, +fieldset[disabled] .btn-danger:focus, +.btn-danger.disabled.focus, +.btn-danger[disabled].focus, +fieldset[disabled] .btn-danger.focus, +.btn-danger.disabled:active, +.btn-danger[disabled]:active, +fieldset[disabled] .btn-danger:active, +.btn-danger.disabled.active, +.btn-danger[disabled].active, +fieldset[disabled] .btn-danger.active { + background-color: #c12e2a; + background-image: none; +} +.thumbnail, +.img-thumbnail { + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075); + box-shadow: 0 1px 2px rgba(0, 0, 0, .075); +} +.dropdown-menu > li > a:hover, +.dropdown-menu > li > a:focus { + background-color: #e8e8e8; + background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); + background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); + background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); + background-repeat: repeat-x; +} +.dropdown-menu > .active > a, +.dropdown-menu > .active > a:hover, +.dropdown-menu > .active > a:focus { + background-color: #2e6da4; + background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); + background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); + background-repeat: repeat-x; +} +.navbar-default { + background-image: -webkit-linear-gradient(top, #fff 0%, #f8f8f8 100%); + background-image: -o-linear-gradient(top, #fff 0%, #f8f8f8 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f8f8f8)); + background-image: linear-gradient(to bottom, #fff 0%, #f8f8f8 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 5px rgba(0, 0, 0, .075); +} +.navbar-default .navbar-nav > .open > a, +.navbar-default .navbar-nav > .active > a { + background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); + background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#e2e2e2)); + background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0); + background-repeat: repeat-x; + -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075); + box-shadow: inset 0 3px 9px rgba(0, 0, 0, .075); +} +.navbar-brand, +.navbar-nav > li > a { + text-shadow: 0 1px 0 rgba(255, 255, 255, .25); +} +.navbar-inverse { + background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222 100%); + background-image: -o-linear-gradient(top, #3c3c3c 0%, #222 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#3c3c3c), to(#222)); + background-image: linear-gradient(to bottom, #3c3c3c 0%, #222 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0); + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); + background-repeat: repeat-x; + border-radius: 4px; +} +.navbar-inverse .navbar-nav > .open > a, +.navbar-inverse .navbar-nav > .active > a { + background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%); + background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#080808), to(#0f0f0f)); + background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0); + background-repeat: repeat-x; + -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25); + box-shadow: inset 0 3px 9px rgba(0, 0, 0, .25); +} +.navbar-inverse .navbar-brand, +.navbar-inverse .navbar-nav > li > a { + text-shadow: 0 -1px 0 rgba(0, 0, 0, .25); +} +.navbar-static-top, +.navbar-fixed-top, +.navbar-fixed-bottom { + border-radius: 0; +} +@media (max-width: 767px) { + .navbar .navbar-nav .open .dropdown-menu > .active > a, + .navbar .navbar-nav .open .dropdown-menu > .active > a:hover, + .navbar .navbar-nav .open .dropdown-menu > .active > a:focus { + color: #fff; + background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); + background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); + background-repeat: repeat-x; + } +} +.alert { + text-shadow: 0 1px 0 rgba(255, 255, 255, .2); + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .25), 0 1px 2px rgba(0, 0, 0, .05); +} +.alert-success { + background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); + background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#c8e5bc)); + background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0); + background-repeat: repeat-x; + border-color: #b2dba1; +} +.alert-info { + background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%); + background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#b9def0)); + background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0); + background-repeat: repeat-x; + border-color: #9acfea; +} +.alert-warning { + background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); + background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#f8efc0)); + background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0); + background-repeat: repeat-x; + border-color: #f5e79e; +} +.alert-danger { + background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); + background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#e7c3c3)); + background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0); + background-repeat: repeat-x; + border-color: #dca7a7; +} +.progress { + background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); + background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#f5f5f5)); + background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar { + background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#286090)); + background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar-success { + background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%); + background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#449d44)); + background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar-info { + background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); + background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#31b0d5)); + background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar-warning { + background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); + background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#ec971f)); + background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar-danger { + background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%); + background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c9302c)); + background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0); + background-repeat: repeat-x; +} +.progress-bar-striped { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); +} +.list-group { + border-radius: 4px; + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .075); + box-shadow: 0 1px 2px rgba(0, 0, 0, .075); +} +.list-group-item.active, +.list-group-item.active:hover, +.list-group-item.active:focus { + text-shadow: 0 -1px 0 #286090; + background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2b669a)); + background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0); + background-repeat: repeat-x; + border-color: #2b669a; +} +.list-group-item.active .badge, +.list-group-item.active:hover .badge, +.list-group-item.active:focus .badge { + text-shadow: none; +} +.panel { + -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .05); + box-shadow: 0 1px 2px rgba(0, 0, 0, .05); +} +.panel-default > .panel-heading { + background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); + background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); + background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); + background-repeat: repeat-x; +} +.panel-primary > .panel-heading { + background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); + background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); + background-repeat: repeat-x; +} +.panel-success > .panel-heading { + background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); + background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#d0e9c6)); + background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0); + background-repeat: repeat-x; +} +.panel-info > .panel-heading { + background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); + background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#c4e3f3)); + background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0); + background-repeat: repeat-x; +} +.panel-warning > .panel-heading { + background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); + background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#faf2cc)); + background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0); + background-repeat: repeat-x; +} +.panel-danger > .panel-heading { + background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%); + background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#ebcccc)); + background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0); + background-repeat: repeat-x; +} +.well { + background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); + background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); + background-image: -webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#f5f5f5)); + background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0); + background-repeat: repeat-x; + border-color: #dcdcdc; + -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1); + box-shadow: inset 0 1px 3px rgba(0, 0, 0, .05), 0 1px 0 rgba(255, 255, 255, .1); +} +/*# sourceMappingURL=bootstrap-theme.css.map */ diff --git a/test_app/app/css/bootstrap.css b/test_app/app/css/bootstrap.css new file mode 100644 index 00000000..42c79d6e --- /dev/null +++ b/test_app/app/css/bootstrap.css @@ -0,0 +1,6760 @@ +/*! + * Bootstrap v3.3.6 (http://getbootstrap.com) + * Copyright 2011-2015 Twitter, Inc. + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + */ +/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */ +html { + font-family: sans-serif; + -webkit-text-size-adjust: 100%; + -ms-text-size-adjust: 100%; +} +body { + margin: 0; +} +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +main, +menu, +nav, +section, +summary { + display: block; +} +audio, +canvas, +progress, +video { + display: inline-block; + vertical-align: baseline; +} +audio:not([controls]) { + display: none; + height: 0; +} +[hidden], +template { + display: none; +} +a { + background-color: transparent; +} +a:active, +a:hover { + outline: 0; +} +abbr[title] { + border-bottom: 1px dotted; +} +b, +strong { + font-weight: bold; +} +dfn { + font-style: italic; +} +h1 { + margin: .67em 0; + font-size: 2em; +} +mark { + color: #000; + background: #ff0; +} +small { + font-size: 80%; +} +sub, +sup { + position: relative; + font-size: 75%; + line-height: 0; + vertical-align: baseline; +} +sup { + top: -.5em; +} +sub { + bottom: -.25em; +} +img { + border: 0; +} +svg:not(:root) { + overflow: hidden; +} +figure { + margin: 1em 40px; +} +hr { + height: 0; + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; +} +pre { + overflow: auto; +} +code, +kbd, +pre, +samp { + font-family: monospace, monospace; + font-size: 1em; +} +button, +input, +optgroup, +select, +textarea { + margin: 0; + font: inherit; + color: inherit; +} +button { + overflow: visible; +} +button, +select { + text-transform: none; +} +button, +html input[type="button"], +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; + cursor: pointer; +} +button[disabled], +html input[disabled] { + cursor: default; +} +button::-moz-focus-inner, +input::-moz-focus-inner { + padding: 0; + border: 0; +} +input { + line-height: normal; +} +input[type="checkbox"], +input[type="radio"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + padding: 0; +} +input[type="number"]::-webkit-inner-spin-button, +input[type="number"]::-webkit-outer-spin-button { + height: auto; +} +input[type="search"] { + -webkit-box-sizing: content-box; + -moz-box-sizing: content-box; + box-sizing: content-box; + -webkit-appearance: textfield; +} +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} +fieldset { + padding: .35em .625em .75em; + margin: 0 2px; + border: 1px solid #c0c0c0; +} +legend { + padding: 0; + border: 0; +} +textarea { + overflow: auto; +} +optgroup { + font-weight: bold; +} +table { + border-spacing: 0; + border-collapse: collapse; +} +td, +th { + padding: 0; +} +/*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */ +@media print { + *, + *:before, + *:after { + color: #000 !important; + text-shadow: none !important; + background: transparent !important; + -webkit-box-shadow: none !important; + box-shadow: none !important; + } + a, + a:visited { + text-decoration: underline; + } + a[href]:after { + content: " (" attr(href) ")"; + } + abbr[title]:after { + content: " (" attr(title) ")"; + } + a[href^="#"]:after, + a[href^="javascript:"]:after { + content: ""; + } + pre, + blockquote { + border: 1px solid #999; + + page-break-inside: avoid; + } + thead { + display: table-header-group; + } + tr, + img { + page-break-inside: avoid; + } + img { + max-width: 100% !important; + } + p, + h2, + h3 { + orphans: 3; + widows: 3; + } + h2, + h3 { + page-break-after: avoid; + } + .navbar { + display: none; + } + .btn > .caret, + .dropup > .btn > .caret { + border-top-color: #000 !important; + } + .label { + border: 1px solid #000; + } + .table { + border-collapse: collapse !important; + } + .table td, + .table th { + background-color: #fff !important; + } + .table-bordered th, + .table-bordered td { + border: 1px solid #ddd !important; + } +} +@font-face { + font-family: 'Glyphicons Halflings'; + + src: url('../fonts/glyphicons-halflings-regular.eot'); + src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); +} +.glyphicon { + position: relative; + top: 1px; + display: inline-block; + font-family: 'Glyphicons Halflings'; + font-style: normal; + font-weight: normal; + line-height: 1; + + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} +.glyphicon-asterisk:before { + content: "\002a"; +} +.glyphicon-plus:before { + content: "\002b"; +} +.glyphicon-euro:before, +.glyphicon-eur:before { + content: "\20ac"; +} +.glyphicon-minus:before { + content: "\2212"; +} +.glyphicon-cloud:before { + content: "\2601"; +} +.glyphicon-envelope:before { + content: "\2709"; +} +.glyphicon-pencil:before { + content: "\270f"; +} +.glyphicon-glass:before { + content: "\e001"; +} +.glyphicon-music:before { + content: "\e002"; +} +.glyphicon-search:before { + content: "\e003"; +} +.glyphicon-heart:before { + content: "\e005"; +} +.glyphicon-star:before { + content: "\e006"; +} +.glyphicon-star-empty:before { + content: "\e007"; +} +.glyphicon-user:before { + content: "\e008"; +} +.glyphicon-film:before { + content: "\e009"; +} +.glyphicon-th-large:before { + content: "\e010"; +} +.glyphicon-th:before { + content: "\e011"; +} +.glyphicon-th-list:before { + content: "\e012"; +} +.glyphicon-ok:before { + content: "\e013"; +} +.glyphicon-remove:before { + content: "\e014"; +} +.glyphicon-zoom-in:before { + content: "\e015"; +} +.glyphicon-zoom-out:before { + content: "\e016"; +} +.glyphicon-off:before { + content: "\e017"; +} +.glyphicon-signal:before { + content: "\e018"; +} +.glyphicon-cog:before { + content: "\e019"; +} +.glyphicon-trash:before { + content: "\e020"; +} +.glyphicon-home:before { + content: "\e021"; +} +.glyphicon-file:before { + content: "\e022"; +} +.glyphicon-time:before { + content: "\e023"; +} +.glyphicon-road:before { + content: "\e024"; +} +.glyphicon-download-alt:before { + content: "\e025"; +} +.glyphicon-download:before { + content: "\e026"; +} +.glyphicon-upload:before { + content: "\e027"; +} +.glyphicon-inbox:before { + content: "\e028"; +} +.glyphicon-play-circle:before { + content: "\e029"; +} +.glyphicon-repeat:before { + content: "\e030"; +} +.glyphicon-refresh:before { + content: "\e031"; +} +.glyphicon-list-alt:before { + content: "\e032"; +} +.glyphicon-lock:before { + content: "\e033"; +} +.glyphicon-flag:before { + content: "\e034"; +} +.glyphicon-headphones:before { + content: "\e035"; +} +.glyphicon-volume-off:before { + content: "\e036"; +} +.glyphicon-volume-down:before { + content: "\e037"; +} +.glyphicon-volume-up:before { + content: "\e038"; +} +.glyphicon-qrcode:before { + content: "\e039"; +} +.glyphicon-barcode:before { + content: "\e040"; +} +.glyphicon-tag:before { + content: "\e041"; +} +.glyphicon-tags:before { + content: "\e042"; +} +.glyphicon-book:before { + content: "\e043"; +} +.glyphicon-bookmark:before { + content: "\e044"; +} +.glyphicon-print:before { + content: "\e045"; +} +.glyphicon-camera:before { + content: "\e046"; +} +.glyphicon-font:before { + content: "\e047"; +} +.glyphicon-bold:before { + content: "\e048"; +} +.glyphicon-italic:before { + content: "\e049"; +} +.glyphicon-text-height:before { + content: "\e050"; +} +.glyphicon-text-width:before { + content: "\e051"; +} +.glyphicon-align-left:before { + content: "\e052"; +} +.glyphicon-align-center:before { + content: "\e053"; +} +.glyphicon-align-right:before { + content: "\e054"; +} +.glyphicon-align-justify:before { + content: "\e055"; +} +.glyphicon-list:before { + content: "\e056"; +} +.glyphicon-indent-left:before { + content: "\e057"; +} +.glyphicon-indent-right:before { + content: "\e058"; +} +.glyphicon-facetime-video:before { + content: "\e059"; +} +.glyphicon-picture:before { + content: "\e060"; +} +.glyphicon-map-marker:before { + content: "\e062"; +} +.glyphicon-adjust:before { + content: "\e063"; +} +.glyphicon-tint:before { + content: "\e064"; +} +.glyphicon-edit:before { + content: "\e065"; +} +.glyphicon-share:before { + content: "\e066"; +} +.glyphicon-check:before { + content: "\e067"; +} +.glyphicon-move:before { + content: "\e068"; +} +.glyphicon-step-backward:before { + content: "\e069"; +} +.glyphicon-fast-backward:before { + content: "\e070"; +} +.glyphicon-backward:before { + content: "\e071"; +} +.glyphicon-play:before { + content: "\e072"; +} +.glyphicon-pause:before { + content: "\e073"; +} +.glyphicon-stop:before { + content: "\e074"; +} +.glyphicon-forward:before { + content: "\e075"; +} +.glyphicon-fast-forward:before { + content: "\e076"; +} +.glyphicon-step-forward:before { + content: "\e077"; +} +.glyphicon-eject:before { + content: "\e078"; +} +.glyphicon-chevron-left:before { + content: "\e079"; +} +.glyphicon-chevron-right:before { + content: "\e080"; +} +.glyphicon-plus-sign:before { + content: "\e081"; +} +.glyphicon-minus-sign:before { + content: "\e082"; +} +.glyphicon-remove-sign:before { + content: "\e083"; +} +.glyphicon-ok-sign:before { + content: "\e084"; +} +.glyphicon-question-sign:before { + content: "\e085"; +} +.glyphicon-info-sign:before { + content: "\e086"; +} +.glyphicon-screenshot:before { + content: "\e087"; +} +.glyphicon-remove-circle:before { + content: "\e088"; +} +.glyphicon-ok-circle:before { + content: "\e089"; +} +.glyphicon-ban-circle:before { + content: "\e090"; +} +.glyphicon-arrow-left:before { + content: "\e091"; +} +.glyphicon-arrow-right:before { + content: "\e092"; +} +.glyphicon-arrow-up:before { + content: "\e093"; +} +.glyphicon-arrow-down:before { + content: "\e094"; +} +.glyphicon-share-alt:before { + content: "\e095"; +} +.glyphicon-resize-full:before { + content: "\e096"; +} +.glyphicon-resize-small:before { + content: "\e097"; +} +.glyphicon-exclamation-sign:before { + content: "\e101"; +} +.glyphicon-gift:before { + content: "\e102"; +} +.glyphicon-leaf:before { + content: "\e103"; +} +.glyphicon-fire:before { + content: "\e104"; +} +.glyphicon-eye-open:before { + content: "\e105"; +} +.glyphicon-eye-close:before { + content: "\e106"; +} +.glyphicon-warning-sign:before { + content: "\e107"; +} +.glyphicon-plane:before { + content: "\e108"; +} +.glyphicon-calendar:before { + content: "\e109"; +} +.glyphicon-random:before { + content: "\e110"; +} +.glyphicon-comment:before { + content: "\e111"; +} +.glyphicon-magnet:before { + content: "\e112"; +} +.glyphicon-chevron-up:before { + content: "\e113"; +} +.glyphicon-chevron-down:before { + content: "\e114"; +} +.glyphicon-retweet:before { + content: "\e115"; +} +.glyphicon-shopping-cart:before { + content: "\e116"; +} +.glyphicon-folder-close:before { + content: "\e117"; +} +.glyphicon-folder-open:before { + content: "\e118"; +} +.glyphicon-resize-vertical:before { + content: "\e119"; +} +.glyphicon-resize-horizontal:before { + content: "\e120"; +} +.glyphicon-hdd:before { + content: "\e121"; +} +.glyphicon-bullhorn:before { + content: "\e122"; +} +.glyphicon-bell:before { + content: "\e123"; +} +.glyphicon-certificate:before { + content: "\e124"; +} +.glyphicon-thumbs-up:before { + content: "\e125"; +} +.glyphicon-thumbs-down:before { + content: "\e126"; +} +.glyphicon-hand-right:before { + content: "\e127"; +} +.glyphicon-hand-left:before { + content: "\e128"; +} +.glyphicon-hand-up:before { + content: "\e129"; +} +.glyphicon-hand-down:before { + content: "\e130"; +} +.glyphicon-circle-arrow-right:before { + content: "\e131"; +} +.glyphicon-circle-arrow-left:before { + content: "\e132"; +} +.glyphicon-circle-arrow-up:before { + content: "\e133"; +} +.glyphicon-circle-arrow-down:before { + content: "\e134"; +} +.glyphicon-globe:before { + content: "\e135"; +} +.glyphicon-wrench:before { + content: "\e136"; +} +.glyphicon-tasks:before { + content: "\e137"; +} +.glyphicon-filter:before { + content: "\e138"; +} +.glyphicon-briefcase:before { + content: "\e139"; +} +.glyphicon-fullscreen:before { + content: "\e140"; +} +.glyphicon-dashboard:before { + content: "\e141"; +} +.glyphicon-paperclip:before { + content: "\e142"; +} +.glyphicon-heart-empty:before { + content: "\e143"; +} +.glyphicon-link:before { + content: "\e144"; +} +.glyphicon-phone:before { + content: "\e145"; +} +.glyphicon-pushpin:before { + content: "\e146"; +} +.glyphicon-usd:before { + content: "\e148"; +} +.glyphicon-gbp:before { + content: "\e149"; +} +.glyphicon-sort:before { + content: "\e150"; +} +.glyphicon-sort-by-alphabet:before { + content: "\e151"; +} +.glyphicon-sort-by-alphabet-alt:before { + content: "\e152"; +} +.glyphicon-sort-by-order:before { + content: "\e153"; +} +.glyphicon-sort-by-order-alt:before { + content: "\e154"; +} +.glyphicon-sort-by-attributes:before { + content: "\e155"; +} +.glyphicon-sort-by-attributes-alt:before { + content: "\e156"; +} +.glyphicon-unchecked:before { + content: "\e157"; +} +.glyphicon-expand:before { + content: "\e158"; +} +.glyphicon-collapse-down:before { + content: "\e159"; +} +.glyphicon-collapse-up:before { + content: "\e160"; +} +.glyphicon-log-in:before { + content: "\e161"; +} +.glyphicon-flash:before { + content: "\e162"; +} +.glyphicon-log-out:before { + content: "\e163"; +} +.glyphicon-new-window:before { + content: "\e164"; +} +.glyphicon-record:before { + content: "\e165"; +} +.glyphicon-save:before { + content: "\e166"; +} +.glyphicon-open:before { + content: "\e167"; +} +.glyphicon-saved:before { + content: "\e168"; +} +.glyphicon-import:before { + content: "\e169"; +} +.glyphicon-export:before { + content: "\e170"; +} +.glyphicon-send:before { + content: "\e171"; +} +.glyphicon-floppy-disk:before { + content: "\e172"; +} +.glyphicon-floppy-saved:before { + content: "\e173"; +} +.glyphicon-floppy-remove:before { + content: "\e174"; +} +.glyphicon-floppy-save:before { + content: "\e175"; +} +.glyphicon-floppy-open:before { + content: "\e176"; +} +.glyphicon-credit-card:before { + content: "\e177"; +} +.glyphicon-transfer:before { + content: "\e178"; +} +.glyphicon-cutlery:before { + content: "\e179"; +} +.glyphicon-header:before { + content: "\e180"; +} +.glyphicon-compressed:before { + content: "\e181"; +} +.glyphicon-earphone:before { + content: "\e182"; +} +.glyphicon-phone-alt:before { + content: "\e183"; +} +.glyphicon-tower:before { + content: "\e184"; +} +.glyphicon-stats:before { + content: "\e185"; +} +.glyphicon-sd-video:before { + content: "\e186"; +} +.glyphicon-hd-video:before { + content: "\e187"; +} +.glyphicon-subtitles:before { + content: "\e188"; +} +.glyphicon-sound-stereo:before { + content: "\e189"; +} +.glyphicon-sound-dolby:before { + content: "\e190"; +} +.glyphicon-sound-5-1:before { + content: "\e191"; +} +.glyphicon-sound-6-1:before { + content: "\e192"; +} +.glyphicon-sound-7-1:before { + content: "\e193"; +} +.glyphicon-copyright-mark:before { + content: "\e194"; +} +.glyphicon-registration-mark:before { + content: "\e195"; +} +.glyphicon-cloud-download:before { + content: "\e197"; +} +.glyphicon-cloud-upload:before { + content: "\e198"; +} +.glyphicon-tree-conifer:before { + content: "\e199"; +} +.glyphicon-tree-deciduous:before { + content: "\e200"; +} +.glyphicon-cd:before { + content: "\e201"; +} +.glyphicon-save-file:before { + content: "\e202"; +} +.glyphicon-open-file:before { + content: "\e203"; +} +.glyphicon-level-up:before { + content: "\e204"; +} +.glyphicon-copy:before { + content: "\e205"; +} +.glyphicon-paste:before { + content: "\e206"; +} +.glyphicon-alert:before { + content: "\e209"; +} +.glyphicon-equalizer:before { + content: "\e210"; +} +.glyphicon-king:before { + content: "\e211"; +} +.glyphicon-queen:before { + content: "\e212"; +} +.glyphicon-pawn:before { + content: "\e213"; +} +.glyphicon-bishop:before { + content: "\e214"; +} +.glyphicon-knight:before { + content: "\e215"; +} +.glyphicon-baby-formula:before { + content: "\e216"; +} +.glyphicon-tent:before { + content: "\26fa"; +} +.glyphicon-blackboard:before { + content: "\e218"; +} +.glyphicon-bed:before { + content: "\e219"; +} +.glyphicon-apple:before { + content: "\f8ff"; +} +.glyphicon-erase:before { + content: "\e221"; +} +.glyphicon-hourglass:before { + content: "\231b"; +} +.glyphicon-lamp:before { + content: "\e223"; +} +.glyphicon-duplicate:before { + content: "\e224"; +} +.glyphicon-piggy-bank:before { + content: "\e225"; +} +.glyphicon-scissors:before { + content: "\e226"; +} +.glyphicon-bitcoin:before { + content: "\e227"; +} +.glyphicon-btc:before { + content: "\e227"; +} +.glyphicon-xbt:before { + content: "\e227"; +} +.glyphicon-yen:before { + content: "\00a5"; +} +.glyphicon-jpy:before { + content: "\00a5"; +} +.glyphicon-ruble:before { + content: "\20bd"; +} +.glyphicon-rub:before { + content: "\20bd"; +} +.glyphicon-scale:before { + content: "\e230"; +} +.glyphicon-ice-lolly:before { + content: "\e231"; +} +.glyphicon-ice-lolly-tasted:before { + content: "\e232"; +} +.glyphicon-education:before { + content: "\e233"; +} +.glyphicon-option-horizontal:before { + content: "\e234"; +} +.glyphicon-option-vertical:before { + content: "\e235"; +} +.glyphicon-menu-hamburger:before { + content: "\e236"; +} +.glyphicon-modal-window:before { + content: "\e237"; +} +.glyphicon-oil:before { + content: "\e238"; +} +.glyphicon-grain:before { + content: "\e239"; +} +.glyphicon-sunglasses:before { + content: "\e240"; +} +.glyphicon-text-size:before { + content: "\e241"; +} +.glyphicon-text-color:before { + content: "\e242"; +} +.glyphicon-text-background:before { + content: "\e243"; +} +.glyphicon-object-align-top:before { + content: "\e244"; +} +.glyphicon-object-align-bottom:before { + content: "\e245"; +} +.glyphicon-object-align-horizontal:before { + content: "\e246"; +} +.glyphicon-object-align-left:before { + content: "\e247"; +} +.glyphicon-object-align-vertical:before { + content: "\e248"; +} +.glyphicon-object-align-right:before { + content: "\e249"; +} +.glyphicon-triangle-right:before { + content: "\e250"; +} +.glyphicon-triangle-left:before { + content: "\e251"; +} +.glyphicon-triangle-bottom:before { + content: "\e252"; +} +.glyphicon-triangle-top:before { + content: "\e253"; +} +.glyphicon-console:before { + content: "\e254"; +} +.glyphicon-superscript:before { + content: "\e255"; +} +.glyphicon-subscript:before { + content: "\e256"; +} +.glyphicon-menu-left:before { + content: "\e257"; +} +.glyphicon-menu-right:before { + content: "\e258"; +} +.glyphicon-menu-down:before { + content: "\e259"; +} +.glyphicon-menu-up:before { + content: "\e260"; +} +* { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +*:before, +*:after { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +html { + font-size: 10px; + + -webkit-tap-highlight-color: rgba(0, 0, 0, 0); +} +body { + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + line-height: 1.42857143; + color: #333; + background-color: #fff; +} +input, +button, +select, +textarea { + font-family: inherit; + font-size: inherit; + line-height: inherit; +} +a { + color: #337ab7; + text-decoration: none; +} +a:hover, +a:focus { + color: #23527c; + text-decoration: underline; +} +a:focus { + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +figure { + margin: 0; +} +img { + vertical-align: middle; +} +.img-responsive, +.thumbnail > img, +.thumbnail a > img, +.carousel-inner > .item > img, +.carousel-inner > .item > a > img { + display: block; + max-width: 100%; + height: auto; +} +.img-rounded { + border-radius: 6px; +} +.img-thumbnail { + display: inline-block; + max-width: 100%; + height: auto; + padding: 4px; + line-height: 1.42857143; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + -webkit-transition: all .2s ease-in-out; + -o-transition: all .2s ease-in-out; + transition: all .2s ease-in-out; +} +.img-circle { + border-radius: 50%; +} +hr { + margin-top: 20px; + margin-bottom: 20px; + border: 0; + border-top: 1px solid #eee; +} +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} +.sr-only-focusable:active, +.sr-only-focusable:focus { + position: static; + width: auto; + height: auto; + margin: 0; + overflow: visible; + clip: auto; +} +[role="button"] { + cursor: pointer; +} +h1, +h2, +h3, +h4, +h5, +h6, +.h1, +.h2, +.h3, +.h4, +.h5, +.h6 { + font-family: inherit; + font-weight: 500; + line-height: 1.1; + color: inherit; +} +h1 small, +h2 small, +h3 small, +h4 small, +h5 small, +h6 small, +.h1 small, +.h2 small, +.h3 small, +.h4 small, +.h5 small, +.h6 small, +h1 .small, +h2 .small, +h3 .small, +h4 .small, +h5 .small, +h6 .small, +.h1 .small, +.h2 .small, +.h3 .small, +.h4 .small, +.h5 .small, +.h6 .small { + font-weight: normal; + line-height: 1; + color: #777; +} +h1, +.h1, +h2, +.h2, +h3, +.h3 { + margin-top: 20px; + margin-bottom: 10px; +} +h1 small, +.h1 small, +h2 small, +.h2 small, +h3 small, +.h3 small, +h1 .small, +.h1 .small, +h2 .small, +.h2 .small, +h3 .small, +.h3 .small { + font-size: 65%; +} +h4, +.h4, +h5, +.h5, +h6, +.h6 { + margin-top: 10px; + margin-bottom: 10px; +} +h4 small, +.h4 small, +h5 small, +.h5 small, +h6 small, +.h6 small, +h4 .small, +.h4 .small, +h5 .small, +.h5 .small, +h6 .small, +.h6 .small { + font-size: 75%; +} +h1, +.h1 { + font-size: 36px; +} +h2, +.h2 { + font-size: 30px; +} +h3, +.h3 { + font-size: 24px; +} +h4, +.h4 { + font-size: 18px; +} +h5, +.h5 { + font-size: 14px; +} +h6, +.h6 { + font-size: 12px; +} +p { + margin: 0 0 10px; +} +.lead { + margin-bottom: 20px; + font-size: 16px; + font-weight: 300; + line-height: 1.4; +} +@media (min-width: 768px) { + .lead { + font-size: 21px; + } +} +small, +.small { + font-size: 85%; +} +mark, +.mark { + padding: .2em; + background-color: #fcf8e3; +} +.text-left { + text-align: left; +} +.text-right { + text-align: right; +} +.text-center { + text-align: center; +} +.text-justify { + text-align: justify; +} +.text-nowrap { + white-space: nowrap; +} +.text-lowercase { + text-transform: lowercase; +} +.text-uppercase { + text-transform: uppercase; +} +.text-capitalize { + text-transform: capitalize; +} +.text-muted { + color: #777; +} +.text-primary { + color: #337ab7; +} +a.text-primary:hover, +a.text-primary:focus { + color: #286090; +} +.text-success { + color: #3c763d; +} +a.text-success:hover, +a.text-success:focus { + color: #2b542c; +} +.text-info { + color: #31708f; +} +a.text-info:hover, +a.text-info:focus { + color: #245269; +} +.text-warning { + color: #8a6d3b; +} +a.text-warning:hover, +a.text-warning:focus { + color: #66512c; +} +.text-danger { + color: #a94442; +} +a.text-danger:hover, +a.text-danger:focus { + color: #843534; +} +.bg-primary { + color: #fff; + background-color: #337ab7; +} +a.bg-primary:hover, +a.bg-primary:focus { + background-color: #286090; +} +.bg-success { + background-color: #dff0d8; +} +a.bg-success:hover, +a.bg-success:focus { + background-color: #c1e2b3; +} +.bg-info { + background-color: #d9edf7; +} +a.bg-info:hover, +a.bg-info:focus { + background-color: #afd9ee; +} +.bg-warning { + background-color: #fcf8e3; +} +a.bg-warning:hover, +a.bg-warning:focus { + background-color: #f7ecb5; +} +.bg-danger { + background-color: #f2dede; +} +a.bg-danger:hover, +a.bg-danger:focus { + background-color: #e4b9b9; +} +.page-header { + padding-bottom: 9px; + margin: 40px 0 20px; + border-bottom: 1px solid #eee; +} +ul, +ol { + margin-top: 0; + margin-bottom: 10px; +} +ul ul, +ol ul, +ul ol, +ol ol { + margin-bottom: 0; +} +.list-unstyled { + padding-left: 0; + list-style: none; +} +.list-inline { + padding-left: 0; + margin-left: -5px; + list-style: none; +} +.list-inline > li { + display: inline-block; + padding-right: 5px; + padding-left: 5px; +} +dl { + margin-top: 0; + margin-bottom: 20px; +} +dt, +dd { + line-height: 1.42857143; +} +dt { + font-weight: bold; +} +dd { + margin-left: 0; +} +@media (min-width: 768px) { + .dl-horizontal dt { + float: left; + width: 160px; + overflow: hidden; + clear: left; + text-align: right; + text-overflow: ellipsis; + white-space: nowrap; + } + .dl-horizontal dd { + margin-left: 180px; + } +} +abbr[title], +abbr[data-original-title] { + cursor: help; + border-bottom: 1px dotted #777; +} +.initialism { + font-size: 90%; + text-transform: uppercase; +} +blockquote { + padding: 10px 20px; + margin: 0 0 20px; + font-size: 17.5px; + border-left: 5px solid #eee; +} +blockquote p:last-child, +blockquote ul:last-child, +blockquote ol:last-child { + margin-bottom: 0; +} +blockquote footer, +blockquote small, +blockquote .small { + display: block; + font-size: 80%; + line-height: 1.42857143; + color: #777; +} +blockquote footer:before, +blockquote small:before, +blockquote .small:before { + content: '\2014 \00A0'; +} +.blockquote-reverse, +blockquote.pull-right { + padding-right: 15px; + padding-left: 0; + text-align: right; + border-right: 5px solid #eee; + border-left: 0; +} +.blockquote-reverse footer:before, +blockquote.pull-right footer:before, +.blockquote-reverse small:before, +blockquote.pull-right small:before, +.blockquote-reverse .small:before, +blockquote.pull-right .small:before { + content: ''; +} +.blockquote-reverse footer:after, +blockquote.pull-right footer:after, +.blockquote-reverse small:after, +blockquote.pull-right small:after, +.blockquote-reverse .small:after, +blockquote.pull-right .small:after { + content: '\00A0 \2014'; +} +address { + margin-bottom: 20px; + font-style: normal; + line-height: 1.42857143; +} +code, +kbd, +pre, +samp { + font-family: Menlo, Monaco, Consolas, "Courier New", monospace; +} +code { + padding: 2px 4px; + font-size: 90%; + color: #c7254e; + background-color: #f9f2f4; + border-radius: 4px; +} +kbd { + padding: 2px 4px; + font-size: 90%; + color: #fff; + background-color: #333; + border-radius: 3px; + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .25); +} +kbd kbd { + padding: 0; + font-size: 100%; + font-weight: bold; + -webkit-box-shadow: none; + box-shadow: none; +} +pre { + display: block; + padding: 9.5px; + margin: 0 0 10px; + font-size: 13px; + line-height: 1.42857143; + color: #333; + word-break: break-all; + word-wrap: break-word; + background-color: #f5f5f5; + border: 1px solid #ccc; + border-radius: 4px; +} +pre code { + padding: 0; + font-size: inherit; + color: inherit; + white-space: pre-wrap; + background-color: transparent; + border-radius: 0; +} +.pre-scrollable { + max-height: 340px; + overflow-y: scroll; +} +.container { + padding-right: 15px; + padding-left: 15px; + margin-right: auto; + margin-left: auto; +} +@media (min-width: 768px) { + .container { + width: 750px; + } +} +@media (min-width: 992px) { + .container { + width: 970px; + } +} +@media (min-width: 1200px) { + .container { + width: 1170px; + } +} +.container-fluid { + padding-right: 15px; + padding-left: 15px; + margin-right: auto; + margin-left: auto; +} +.row { + margin-right: -15px; + margin-left: -15px; +} +.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 { + position: relative; + min-height: 1px; + padding-right: 15px; + padding-left: 15px; +} +.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 { + float: left; +} +.col-xs-12 { + width: 100%; +} +.col-xs-11 { + width: 91.66666667%; +} +.col-xs-10 { + width: 83.33333333%; +} +.col-xs-9 { + width: 75%; +} +.col-xs-8 { + width: 66.66666667%; +} +.col-xs-7 { + width: 58.33333333%; +} +.col-xs-6 { + width: 50%; +} +.col-xs-5 { + width: 41.66666667%; +} +.col-xs-4 { + width: 33.33333333%; +} +.col-xs-3 { + width: 25%; +} +.col-xs-2 { + width: 16.66666667%; +} +.col-xs-1 { + width: 8.33333333%; +} +.col-xs-pull-12 { + right: 100%; +} +.col-xs-pull-11 { + right: 91.66666667%; +} +.col-xs-pull-10 { + right: 83.33333333%; +} +.col-xs-pull-9 { + right: 75%; +} +.col-xs-pull-8 { + right: 66.66666667%; +} +.col-xs-pull-7 { + right: 58.33333333%; +} +.col-xs-pull-6 { + right: 50%; +} +.col-xs-pull-5 { + right: 41.66666667%; +} +.col-xs-pull-4 { + right: 33.33333333%; +} +.col-xs-pull-3 { + right: 25%; +} +.col-xs-pull-2 { + right: 16.66666667%; +} +.col-xs-pull-1 { + right: 8.33333333%; +} +.col-xs-pull-0 { + right: auto; +} +.col-xs-push-12 { + left: 100%; +} +.col-xs-push-11 { + left: 91.66666667%; +} +.col-xs-push-10 { + left: 83.33333333%; +} +.col-xs-push-9 { + left: 75%; +} +.col-xs-push-8 { + left: 66.66666667%; +} +.col-xs-push-7 { + left: 58.33333333%; +} +.col-xs-push-6 { + left: 50%; +} +.col-xs-push-5 { + left: 41.66666667%; +} +.col-xs-push-4 { + left: 33.33333333%; +} +.col-xs-push-3 { + left: 25%; +} +.col-xs-push-2 { + left: 16.66666667%; +} +.col-xs-push-1 { + left: 8.33333333%; +} +.col-xs-push-0 { + left: auto; +} +.col-xs-offset-12 { + margin-left: 100%; +} +.col-xs-offset-11 { + margin-left: 91.66666667%; +} +.col-xs-offset-10 { + margin-left: 83.33333333%; +} +.col-xs-offset-9 { + margin-left: 75%; +} +.col-xs-offset-8 { + margin-left: 66.66666667%; +} +.col-xs-offset-7 { + margin-left: 58.33333333%; +} +.col-xs-offset-6 { + margin-left: 50%; +} +.col-xs-offset-5 { + margin-left: 41.66666667%; +} +.col-xs-offset-4 { + margin-left: 33.33333333%; +} +.col-xs-offset-3 { + margin-left: 25%; +} +.col-xs-offset-2 { + margin-left: 16.66666667%; +} +.col-xs-offset-1 { + margin-left: 8.33333333%; +} +.col-xs-offset-0 { + margin-left: 0; +} +@media (min-width: 768px) { + .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 { + float: left; + } + .col-sm-12 { + width: 100%; + } + .col-sm-11 { + width: 91.66666667%; + } + .col-sm-10 { + width: 83.33333333%; + } + .col-sm-9 { + width: 75%; + } + .col-sm-8 { + width: 66.66666667%; + } + .col-sm-7 { + width: 58.33333333%; + } + .col-sm-6 { + width: 50%; + } + .col-sm-5 { + width: 41.66666667%; + } + .col-sm-4 { + width: 33.33333333%; + } + .col-sm-3 { + width: 25%; + } + .col-sm-2 { + width: 16.66666667%; + } + .col-sm-1 { + width: 8.33333333%; + } + .col-sm-pull-12 { + right: 100%; + } + .col-sm-pull-11 { + right: 91.66666667%; + } + .col-sm-pull-10 { + right: 83.33333333%; + } + .col-sm-pull-9 { + right: 75%; + } + .col-sm-pull-8 { + right: 66.66666667%; + } + .col-sm-pull-7 { + right: 58.33333333%; + } + .col-sm-pull-6 { + right: 50%; + } + .col-sm-pull-5 { + right: 41.66666667%; + } + .col-sm-pull-4 { + right: 33.33333333%; + } + .col-sm-pull-3 { + right: 25%; + } + .col-sm-pull-2 { + right: 16.66666667%; + } + .col-sm-pull-1 { + right: 8.33333333%; + } + .col-sm-pull-0 { + right: auto; + } + .col-sm-push-12 { + left: 100%; + } + .col-sm-push-11 { + left: 91.66666667%; + } + .col-sm-push-10 { + left: 83.33333333%; + } + .col-sm-push-9 { + left: 75%; + } + .col-sm-push-8 { + left: 66.66666667%; + } + .col-sm-push-7 { + left: 58.33333333%; + } + .col-sm-push-6 { + left: 50%; + } + .col-sm-push-5 { + left: 41.66666667%; + } + .col-sm-push-4 { + left: 33.33333333%; + } + .col-sm-push-3 { + left: 25%; + } + .col-sm-push-2 { + left: 16.66666667%; + } + .col-sm-push-1 { + left: 8.33333333%; + } + .col-sm-push-0 { + left: auto; + } + .col-sm-offset-12 { + margin-left: 100%; + } + .col-sm-offset-11 { + margin-left: 91.66666667%; + } + .col-sm-offset-10 { + margin-left: 83.33333333%; + } + .col-sm-offset-9 { + margin-left: 75%; + } + .col-sm-offset-8 { + margin-left: 66.66666667%; + } + .col-sm-offset-7 { + margin-left: 58.33333333%; + } + .col-sm-offset-6 { + margin-left: 50%; + } + .col-sm-offset-5 { + margin-left: 41.66666667%; + } + .col-sm-offset-4 { + margin-left: 33.33333333%; + } + .col-sm-offset-3 { + margin-left: 25%; + } + .col-sm-offset-2 { + margin-left: 16.66666667%; + } + .col-sm-offset-1 { + margin-left: 8.33333333%; + } + .col-sm-offset-0 { + margin-left: 0; + } +} +@media (min-width: 992px) { + .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 { + float: left; + } + .col-md-12 { + width: 100%; + } + .col-md-11 { + width: 91.66666667%; + } + .col-md-10 { + width: 83.33333333%; + } + .col-md-9 { + width: 75%; + } + .col-md-8 { + width: 66.66666667%; + } + .col-md-7 { + width: 58.33333333%; + } + .col-md-6 { + width: 50%; + } + .col-md-5 { + width: 41.66666667%; + } + .col-md-4 { + width: 33.33333333%; + } + .col-md-3 { + width: 25%; + } + .col-md-2 { + width: 16.66666667%; + } + .col-md-1 { + width: 8.33333333%; + } + .col-md-pull-12 { + right: 100%; + } + .col-md-pull-11 { + right: 91.66666667%; + } + .col-md-pull-10 { + right: 83.33333333%; + } + .col-md-pull-9 { + right: 75%; + } + .col-md-pull-8 { + right: 66.66666667%; + } + .col-md-pull-7 { + right: 58.33333333%; + } + .col-md-pull-6 { + right: 50%; + } + .col-md-pull-5 { + right: 41.66666667%; + } + .col-md-pull-4 { + right: 33.33333333%; + } + .col-md-pull-3 { + right: 25%; + } + .col-md-pull-2 { + right: 16.66666667%; + } + .col-md-pull-1 { + right: 8.33333333%; + } + .col-md-pull-0 { + right: auto; + } + .col-md-push-12 { + left: 100%; + } + .col-md-push-11 { + left: 91.66666667%; + } + .col-md-push-10 { + left: 83.33333333%; + } + .col-md-push-9 { + left: 75%; + } + .col-md-push-8 { + left: 66.66666667%; + } + .col-md-push-7 { + left: 58.33333333%; + } + .col-md-push-6 { + left: 50%; + } + .col-md-push-5 { + left: 41.66666667%; + } + .col-md-push-4 { + left: 33.33333333%; + } + .col-md-push-3 { + left: 25%; + } + .col-md-push-2 { + left: 16.66666667%; + } + .col-md-push-1 { + left: 8.33333333%; + } + .col-md-push-0 { + left: auto; + } + .col-md-offset-12 { + margin-left: 100%; + } + .col-md-offset-11 { + margin-left: 91.66666667%; + } + .col-md-offset-10 { + margin-left: 83.33333333%; + } + .col-md-offset-9 { + margin-left: 75%; + } + .col-md-offset-8 { + margin-left: 66.66666667%; + } + .col-md-offset-7 { + margin-left: 58.33333333%; + } + .col-md-offset-6 { + margin-left: 50%; + } + .col-md-offset-5 { + margin-left: 41.66666667%; + } + .col-md-offset-4 { + margin-left: 33.33333333%; + } + .col-md-offset-3 { + margin-left: 25%; + } + .col-md-offset-2 { + margin-left: 16.66666667%; + } + .col-md-offset-1 { + margin-left: 8.33333333%; + } + .col-md-offset-0 { + margin-left: 0; + } +} +@media (min-width: 1200px) { + .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 { + float: left; + } + .col-lg-12 { + width: 100%; + } + .col-lg-11 { + width: 91.66666667%; + } + .col-lg-10 { + width: 83.33333333%; + } + .col-lg-9 { + width: 75%; + } + .col-lg-8 { + width: 66.66666667%; + } + .col-lg-7 { + width: 58.33333333%; + } + .col-lg-6 { + width: 50%; + } + .col-lg-5 { + width: 41.66666667%; + } + .col-lg-4 { + width: 33.33333333%; + } + .col-lg-3 { + width: 25%; + } + .col-lg-2 { + width: 16.66666667%; + } + .col-lg-1 { + width: 8.33333333%; + } + .col-lg-pull-12 { + right: 100%; + } + .col-lg-pull-11 { + right: 91.66666667%; + } + .col-lg-pull-10 { + right: 83.33333333%; + } + .col-lg-pull-9 { + right: 75%; + } + .col-lg-pull-8 { + right: 66.66666667%; + } + .col-lg-pull-7 { + right: 58.33333333%; + } + .col-lg-pull-6 { + right: 50%; + } + .col-lg-pull-5 { + right: 41.66666667%; + } + .col-lg-pull-4 { + right: 33.33333333%; + } + .col-lg-pull-3 { + right: 25%; + } + .col-lg-pull-2 { + right: 16.66666667%; + } + .col-lg-pull-1 { + right: 8.33333333%; + } + .col-lg-pull-0 { + right: auto; + } + .col-lg-push-12 { + left: 100%; + } + .col-lg-push-11 { + left: 91.66666667%; + } + .col-lg-push-10 { + left: 83.33333333%; + } + .col-lg-push-9 { + left: 75%; + } + .col-lg-push-8 { + left: 66.66666667%; + } + .col-lg-push-7 { + left: 58.33333333%; + } + .col-lg-push-6 { + left: 50%; + } + .col-lg-push-5 { + left: 41.66666667%; + } + .col-lg-push-4 { + left: 33.33333333%; + } + .col-lg-push-3 { + left: 25%; + } + .col-lg-push-2 { + left: 16.66666667%; + } + .col-lg-push-1 { + left: 8.33333333%; + } + .col-lg-push-0 { + left: auto; + } + .col-lg-offset-12 { + margin-left: 100%; + } + .col-lg-offset-11 { + margin-left: 91.66666667%; + } + .col-lg-offset-10 { + margin-left: 83.33333333%; + } + .col-lg-offset-9 { + margin-left: 75%; + } + .col-lg-offset-8 { + margin-left: 66.66666667%; + } + .col-lg-offset-7 { + margin-left: 58.33333333%; + } + .col-lg-offset-6 { + margin-left: 50%; + } + .col-lg-offset-5 { + margin-left: 41.66666667%; + } + .col-lg-offset-4 { + margin-left: 33.33333333%; + } + .col-lg-offset-3 { + margin-left: 25%; + } + .col-lg-offset-2 { + margin-left: 16.66666667%; + } + .col-lg-offset-1 { + margin-left: 8.33333333%; + } + .col-lg-offset-0 { + margin-left: 0; + } +} +table { + background-color: transparent; +} +caption { + padding-top: 8px; + padding-bottom: 8px; + color: #777; + text-align: left; +} +th { + text-align: left; +} +.table { + width: 100%; + max-width: 100%; + margin-bottom: 20px; +} +.table > thead > tr > th, +.table > tbody > tr > th, +.table > tfoot > tr > th, +.table > thead > tr > td, +.table > tbody > tr > td, +.table > tfoot > tr > td { + padding: 8px; + line-height: 1.42857143; + vertical-align: top; + border-top: 1px solid #ddd; +} +.table > thead > tr > th { + vertical-align: bottom; + border-bottom: 2px solid #ddd; +} +.table > caption + thead > tr:first-child > th, +.table > colgroup + thead > tr:first-child > th, +.table > thead:first-child > tr:first-child > th, +.table > caption + thead > tr:first-child > td, +.table > colgroup + thead > tr:first-child > td, +.table > thead:first-child > tr:first-child > td { + border-top: 0; +} +.table > tbody + tbody { + border-top: 2px solid #ddd; +} +.table .table { + background-color: #fff; +} +.table-condensed > thead > tr > th, +.table-condensed > tbody > tr > th, +.table-condensed > tfoot > tr > th, +.table-condensed > thead > tr > td, +.table-condensed > tbody > tr > td, +.table-condensed > tfoot > tr > td { + padding: 5px; +} +.table-bordered { + border: 1px solid #ddd; +} +.table-bordered > thead > tr > th, +.table-bordered > tbody > tr > th, +.table-bordered > tfoot > tr > th, +.table-bordered > thead > tr > td, +.table-bordered > tbody > tr > td, +.table-bordered > tfoot > tr > td { + border: 1px solid #ddd; +} +.table-bordered > thead > tr > th, +.table-bordered > thead > tr > td { + border-bottom-width: 2px; +} +.table-striped > tbody > tr:nth-of-type(odd) { + background-color: #f9f9f9; +} +.table-hover > tbody > tr:hover { + background-color: #f5f5f5; +} +table col[class*="col-"] { + position: static; + display: table-column; + float: none; +} +table td[class*="col-"], +table th[class*="col-"] { + position: static; + display: table-cell; + float: none; +} +.table > thead > tr > td.active, +.table > tbody > tr > td.active, +.table > tfoot > tr > td.active, +.table > thead > tr > th.active, +.table > tbody > tr > th.active, +.table > tfoot > tr > th.active, +.table > thead > tr.active > td, +.table > tbody > tr.active > td, +.table > tfoot > tr.active > td, +.table > thead > tr.active > th, +.table > tbody > tr.active > th, +.table > tfoot > tr.active > th { + background-color: #f5f5f5; +} +.table-hover > tbody > tr > td.active:hover, +.table-hover > tbody > tr > th.active:hover, +.table-hover > tbody > tr.active:hover > td, +.table-hover > tbody > tr:hover > .active, +.table-hover > tbody > tr.active:hover > th { + background-color: #e8e8e8; +} +.table > thead > tr > td.success, +.table > tbody > tr > td.success, +.table > tfoot > tr > td.success, +.table > thead > tr > th.success, +.table > tbody > tr > th.success, +.table > tfoot > tr > th.success, +.table > thead > tr.success > td, +.table > tbody > tr.success > td, +.table > tfoot > tr.success > td, +.table > thead > tr.success > th, +.table > tbody > tr.success > th, +.table > tfoot > tr.success > th { + background-color: #dff0d8; +} +.table-hover > tbody > tr > td.success:hover, +.table-hover > tbody > tr > th.success:hover, +.table-hover > tbody > tr.success:hover > td, +.table-hover > tbody > tr:hover > .success, +.table-hover > tbody > tr.success:hover > th { + background-color: #d0e9c6; +} +.table > thead > tr > td.info, +.table > tbody > tr > td.info, +.table > tfoot > tr > td.info, +.table > thead > tr > th.info, +.table > tbody > tr > th.info, +.table > tfoot > tr > th.info, +.table > thead > tr.info > td, +.table > tbody > tr.info > td, +.table > tfoot > tr.info > td, +.table > thead > tr.info > th, +.table > tbody > tr.info > th, +.table > tfoot > tr.info > th { + background-color: #d9edf7; +} +.table-hover > tbody > tr > td.info:hover, +.table-hover > tbody > tr > th.info:hover, +.table-hover > tbody > tr.info:hover > td, +.table-hover > tbody > tr:hover > .info, +.table-hover > tbody > tr.info:hover > th { + background-color: #c4e3f3; +} +.table > thead > tr > td.warning, +.table > tbody > tr > td.warning, +.table > tfoot > tr > td.warning, +.table > thead > tr > th.warning, +.table > tbody > tr > th.warning, +.table > tfoot > tr > th.warning, +.table > thead > tr.warning > td, +.table > tbody > tr.warning > td, +.table > tfoot > tr.warning > td, +.table > thead > tr.warning > th, +.table > tbody > tr.warning > th, +.table > tfoot > tr.warning > th { + background-color: #fcf8e3; +} +.table-hover > tbody > tr > td.warning:hover, +.table-hover > tbody > tr > th.warning:hover, +.table-hover > tbody > tr.warning:hover > td, +.table-hover > tbody > tr:hover > .warning, +.table-hover > tbody > tr.warning:hover > th { + background-color: #faf2cc; +} +.table > thead > tr > td.danger, +.table > tbody > tr > td.danger, +.table > tfoot > tr > td.danger, +.table > thead > tr > th.danger, +.table > tbody > tr > th.danger, +.table > tfoot > tr > th.danger, +.table > thead > tr.danger > td, +.table > tbody > tr.danger > td, +.table > tfoot > tr.danger > td, +.table > thead > tr.danger > th, +.table > tbody > tr.danger > th, +.table > tfoot > tr.danger > th { + background-color: #f2dede; +} +.table-hover > tbody > tr > td.danger:hover, +.table-hover > tbody > tr > th.danger:hover, +.table-hover > tbody > tr.danger:hover > td, +.table-hover > tbody > tr:hover > .danger, +.table-hover > tbody > tr.danger:hover > th { + background-color: #ebcccc; +} +.table-responsive { + min-height: .01%; + overflow-x: auto; +} +@media screen and (max-width: 767px) { + .table-responsive { + width: 100%; + margin-bottom: 15px; + overflow-y: hidden; + -ms-overflow-style: -ms-autohiding-scrollbar; + border: 1px solid #ddd; + } + .table-responsive > .table { + margin-bottom: 0; + } + .table-responsive > .table > thead > tr > th, + .table-responsive > .table > tbody > tr > th, + .table-responsive > .table > tfoot > tr > th, + .table-responsive > .table > thead > tr > td, + .table-responsive > .table > tbody > tr > td, + .table-responsive > .table > tfoot > tr > td { + white-space: nowrap; + } + .table-responsive > .table-bordered { + border: 0; + } + .table-responsive > .table-bordered > thead > tr > th:first-child, + .table-responsive > .table-bordered > tbody > tr > th:first-child, + .table-responsive > .table-bordered > tfoot > tr > th:first-child, + .table-responsive > .table-bordered > thead > tr > td:first-child, + .table-responsive > .table-bordered > tbody > tr > td:first-child, + .table-responsive > .table-bordered > tfoot > tr > td:first-child { + border-left: 0; + } + .table-responsive > .table-bordered > thead > tr > th:last-child, + .table-responsive > .table-bordered > tbody > tr > th:last-child, + .table-responsive > .table-bordered > tfoot > tr > th:last-child, + .table-responsive > .table-bordered > thead > tr > td:last-child, + .table-responsive > .table-bordered > tbody > tr > td:last-child, + .table-responsive > .table-bordered > tfoot > tr > td:last-child { + border-right: 0; + } + .table-responsive > .table-bordered > tbody > tr:last-child > th, + .table-responsive > .table-bordered > tfoot > tr:last-child > th, + .table-responsive > .table-bordered > tbody > tr:last-child > td, + .table-responsive > .table-bordered > tfoot > tr:last-child > td { + border-bottom: 0; + } +} +fieldset { + min-width: 0; + padding: 0; + margin: 0; + border: 0; +} +legend { + display: block; + width: 100%; + padding: 0; + margin-bottom: 20px; + font-size: 21px; + line-height: inherit; + color: #333; + border: 0; + border-bottom: 1px solid #e5e5e5; +} +label { + display: inline-block; + max-width: 100%; + margin-bottom: 5px; + font-weight: bold; +} +input[type="search"] { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +input[type="radio"], +input[type="checkbox"] { + margin: 4px 0 0; + margin-top: 1px \9; + line-height: normal; +} +input[type="file"] { + display: block; +} +input[type="range"] { + display: block; + width: 100%; +} +select[multiple], +select[size] { + height: auto; +} +input[type="file"]:focus, +input[type="radio"]:focus, +input[type="checkbox"]:focus { + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +output { + display: block; + padding-top: 7px; + font-size: 14px; + line-height: 1.42857143; + color: #555; +} +.form-control { + display: block; + width: 100%; + height: 34px; + padding: 6px 12px; + font-size: 14px; + line-height: 1.42857143; + color: #555; + background-color: #fff; + background-image: none; + border: 1px solid #ccc; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s; + -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; + transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s; +} +.form-control:focus { + border-color: #66afe9; + outline: 0; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); + box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, .6); +} +.form-control::-moz-placeholder { + color: #999; + opacity: 1; +} +.form-control:-ms-input-placeholder { + color: #999; +} +.form-control::-webkit-input-placeholder { + color: #999; +} +.form-control::-ms-expand { + background-color: transparent; + border: 0; +} +.form-control[disabled], +.form-control[readonly], +fieldset[disabled] .form-control { + background-color: #eee; + opacity: 1; +} +.form-control[disabled], +fieldset[disabled] .form-control { + cursor: not-allowed; +} +textarea.form-control { + height: auto; +} +input[type="search"] { + -webkit-appearance: none; +} +@media screen and (-webkit-min-device-pixel-ratio: 0) { + input[type="date"].form-control, + input[type="time"].form-control, + input[type="datetime-local"].form-control, + input[type="month"].form-control { + line-height: 34px; + } + input[type="date"].input-sm, + input[type="time"].input-sm, + input[type="datetime-local"].input-sm, + input[type="month"].input-sm, + .input-group-sm input[type="date"], + .input-group-sm input[type="time"], + .input-group-sm input[type="datetime-local"], + .input-group-sm input[type="month"] { + line-height: 30px; + } + input[type="date"].input-lg, + input[type="time"].input-lg, + input[type="datetime-local"].input-lg, + input[type="month"].input-lg, + .input-group-lg input[type="date"], + .input-group-lg input[type="time"], + .input-group-lg input[type="datetime-local"], + .input-group-lg input[type="month"] { + line-height: 46px; + } +} +.form-group { + margin-bottom: 15px; +} +.radio, +.checkbox { + position: relative; + display: block; + margin-top: 10px; + margin-bottom: 10px; +} +.radio label, +.checkbox label { + min-height: 20px; + padding-left: 20px; + margin-bottom: 0; + font-weight: normal; + cursor: pointer; +} +.radio input[type="radio"], +.radio-inline input[type="radio"], +.checkbox input[type="checkbox"], +.checkbox-inline input[type="checkbox"] { + position: absolute; + margin-top: 4px \9; + margin-left: -20px; +} +.radio + .radio, +.checkbox + .checkbox { + margin-top: -5px; +} +.radio-inline, +.checkbox-inline { + position: relative; + display: inline-block; + padding-left: 20px; + margin-bottom: 0; + font-weight: normal; + vertical-align: middle; + cursor: pointer; +} +.radio-inline + .radio-inline, +.checkbox-inline + .checkbox-inline { + margin-top: 0; + margin-left: 10px; +} +input[type="radio"][disabled], +input[type="checkbox"][disabled], +input[type="radio"].disabled, +input[type="checkbox"].disabled, +fieldset[disabled] input[type="radio"], +fieldset[disabled] input[type="checkbox"] { + cursor: not-allowed; +} +.radio-inline.disabled, +.checkbox-inline.disabled, +fieldset[disabled] .radio-inline, +fieldset[disabled] .checkbox-inline { + cursor: not-allowed; +} +.radio.disabled label, +.checkbox.disabled label, +fieldset[disabled] .radio label, +fieldset[disabled] .checkbox label { + cursor: not-allowed; +} +.form-control-static { + min-height: 34px; + padding-top: 7px; + padding-bottom: 7px; + margin-bottom: 0; +} +.form-control-static.input-lg, +.form-control-static.input-sm { + padding-right: 0; + padding-left: 0; +} +.input-sm { + height: 30px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} +select.input-sm { + height: 30px; + line-height: 30px; +} +textarea.input-sm, +select[multiple].input-sm { + height: auto; +} +.form-group-sm .form-control { + height: 30px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} +.form-group-sm select.form-control { + height: 30px; + line-height: 30px; +} +.form-group-sm textarea.form-control, +.form-group-sm select[multiple].form-control { + height: auto; +} +.form-group-sm .form-control-static { + height: 30px; + min-height: 32px; + padding: 6px 10px; + font-size: 12px; + line-height: 1.5; +} +.input-lg { + height: 46px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.3333333; + border-radius: 6px; +} +select.input-lg { + height: 46px; + line-height: 46px; +} +textarea.input-lg, +select[multiple].input-lg { + height: auto; +} +.form-group-lg .form-control { + height: 46px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.3333333; + border-radius: 6px; +} +.form-group-lg select.form-control { + height: 46px; + line-height: 46px; +} +.form-group-lg textarea.form-control, +.form-group-lg select[multiple].form-control { + height: auto; +} +.form-group-lg .form-control-static { + height: 46px; + min-height: 38px; + padding: 11px 16px; + font-size: 18px; + line-height: 1.3333333; +} +.has-feedback { + position: relative; +} +.has-feedback .form-control { + padding-right: 42.5px; +} +.form-control-feedback { + position: absolute; + top: 0; + right: 0; + z-index: 2; + display: block; + width: 34px; + height: 34px; + line-height: 34px; + text-align: center; + pointer-events: none; +} +.input-lg + .form-control-feedback, +.input-group-lg + .form-control-feedback, +.form-group-lg .form-control + .form-control-feedback { + width: 46px; + height: 46px; + line-height: 46px; +} +.input-sm + .form-control-feedback, +.input-group-sm + .form-control-feedback, +.form-group-sm .form-control + .form-control-feedback { + width: 30px; + height: 30px; + line-height: 30px; +} +.has-success .help-block, +.has-success .control-label, +.has-success .radio, +.has-success .checkbox, +.has-success .radio-inline, +.has-success .checkbox-inline, +.has-success.radio label, +.has-success.checkbox label, +.has-success.radio-inline label, +.has-success.checkbox-inline label { + color: #3c763d; +} +.has-success .form-control { + border-color: #3c763d; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); +} +.has-success .form-control:focus { + border-color: #2b542c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #67b168; +} +.has-success .input-group-addon { + color: #3c763d; + background-color: #dff0d8; + border-color: #3c763d; +} +.has-success .form-control-feedback { + color: #3c763d; +} +.has-warning .help-block, +.has-warning .control-label, +.has-warning .radio, +.has-warning .checkbox, +.has-warning .radio-inline, +.has-warning .checkbox-inline, +.has-warning.radio label, +.has-warning.checkbox label, +.has-warning.radio-inline label, +.has-warning.checkbox-inline label { + color: #8a6d3b; +} +.has-warning .form-control { + border-color: #8a6d3b; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); +} +.has-warning .form-control:focus { + border-color: #66512c; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #c0a16b; +} +.has-warning .input-group-addon { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #8a6d3b; +} +.has-warning .form-control-feedback { + color: #8a6d3b; +} +.has-error .help-block, +.has-error .control-label, +.has-error .radio, +.has-error .checkbox, +.has-error .radio-inline, +.has-error .checkbox-inline, +.has-error.radio label, +.has-error.checkbox label, +.has-error.radio-inline label, +.has-error.checkbox-inline label { + color: #a94442; +} +.has-error .form-control { + border-color: #a94442; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075); +} +.has-error .form-control:focus { + border-color: #843534; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px #ce8483; +} +.has-error .input-group-addon { + color: #a94442; + background-color: #f2dede; + border-color: #a94442; +} +.has-error .form-control-feedback { + color: #a94442; +} +.has-feedback label ~ .form-control-feedback { + top: 25px; +} +.has-feedback label.sr-only ~ .form-control-feedback { + top: 0; +} +.help-block { + display: block; + margin-top: 5px; + margin-bottom: 10px; + color: #737373; +} +@media (min-width: 768px) { + .form-inline .form-group { + display: inline-block; + margin-bottom: 0; + vertical-align: middle; + } + .form-inline .form-control { + display: inline-block; + width: auto; + vertical-align: middle; + } + .form-inline .form-control-static { + display: inline-block; + } + .form-inline .input-group { + display: inline-table; + vertical-align: middle; + } + .form-inline .input-group .input-group-addon, + .form-inline .input-group .input-group-btn, + .form-inline .input-group .form-control { + width: auto; + } + .form-inline .input-group > .form-control { + width: 100%; + } + .form-inline .control-label { + margin-bottom: 0; + vertical-align: middle; + } + .form-inline .radio, + .form-inline .checkbox { + display: inline-block; + margin-top: 0; + margin-bottom: 0; + vertical-align: middle; + } + .form-inline .radio label, + .form-inline .checkbox label { + padding-left: 0; + } + .form-inline .radio input[type="radio"], + .form-inline .checkbox input[type="checkbox"] { + position: relative; + margin-left: 0; + } + .form-inline .has-feedback .form-control-feedback { + top: 0; + } +} +.form-horizontal .radio, +.form-horizontal .checkbox, +.form-horizontal .radio-inline, +.form-horizontal .checkbox-inline { + padding-top: 7px; + margin-top: 0; + margin-bottom: 0; +} +.form-horizontal .radio, +.form-horizontal .checkbox { + min-height: 27px; +} +.form-horizontal .form-group { + margin-right: -15px; + margin-left: -15px; +} +@media (min-width: 768px) { + .form-horizontal .control-label { + padding-top: 7px; + margin-bottom: 0; + text-align: right; + } +} +.form-horizontal .has-feedback .form-control-feedback { + right: 15px; +} +@media (min-width: 768px) { + .form-horizontal .form-group-lg .control-label { + padding-top: 11px; + font-size: 18px; + } +} +@media (min-width: 768px) { + .form-horizontal .form-group-sm .control-label { + padding-top: 6px; + font-size: 12px; + } +} +.btn { + display: inline-block; + padding: 6px 12px; + margin-bottom: 0; + font-size: 14px; + font-weight: normal; + line-height: 1.42857143; + text-align: center; + white-space: nowrap; + vertical-align: middle; + -ms-touch-action: manipulation; + touch-action: manipulation; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; +} +.btn:focus, +.btn:active:focus, +.btn.active:focus, +.btn.focus, +.btn:active.focus, +.btn.active.focus { + outline: thin dotted; + outline: 5px auto -webkit-focus-ring-color; + outline-offset: -2px; +} +.btn:hover, +.btn:focus, +.btn.focus { + color: #333; + text-decoration: none; +} +.btn:active, +.btn.active { + background-image: none; + outline: 0; + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); +} +.btn.disabled, +.btn[disabled], +fieldset[disabled] .btn { + cursor: not-allowed; + filter: alpha(opacity=65); + -webkit-box-shadow: none; + box-shadow: none; + opacity: .65; +} +a.btn.disabled, +fieldset[disabled] a.btn { + pointer-events: none; +} +.btn-default { + color: #333; + background-color: #fff; + border-color: #ccc; +} +.btn-default:focus, +.btn-default.focus { + color: #333; + background-color: #e6e6e6; + border-color: #8c8c8c; +} +.btn-default:hover { + color: #333; + background-color: #e6e6e6; + border-color: #adadad; +} +.btn-default:active, +.btn-default.active, +.open > .dropdown-toggle.btn-default { + color: #333; + background-color: #e6e6e6; + border-color: #adadad; +} +.btn-default:active:hover, +.btn-default.active:hover, +.open > .dropdown-toggle.btn-default:hover, +.btn-default:active:focus, +.btn-default.active:focus, +.open > .dropdown-toggle.btn-default:focus, +.btn-default:active.focus, +.btn-default.active.focus, +.open > .dropdown-toggle.btn-default.focus { + color: #333; + background-color: #d4d4d4; + border-color: #8c8c8c; +} +.btn-default:active, +.btn-default.active, +.open > .dropdown-toggle.btn-default { + background-image: none; +} +.btn-default.disabled:hover, +.btn-default[disabled]:hover, +fieldset[disabled] .btn-default:hover, +.btn-default.disabled:focus, +.btn-default[disabled]:focus, +fieldset[disabled] .btn-default:focus, +.btn-default.disabled.focus, +.btn-default[disabled].focus, +fieldset[disabled] .btn-default.focus { + background-color: #fff; + border-color: #ccc; +} +.btn-default .badge { + color: #fff; + background-color: #333; +} +.btn-primary { + color: #fff; + background-color: #337ab7; + border-color: #2e6da4; +} +.btn-primary:focus, +.btn-primary.focus { + color: #fff; + background-color: #286090; + border-color: #122b40; +} +.btn-primary:hover { + color: #fff; + background-color: #286090; + border-color: #204d74; +} +.btn-primary:active, +.btn-primary.active, +.open > .dropdown-toggle.btn-primary { + color: #fff; + background-color: #286090; + border-color: #204d74; +} +.btn-primary:active:hover, +.btn-primary.active:hover, +.open > .dropdown-toggle.btn-primary:hover, +.btn-primary:active:focus, +.btn-primary.active:focus, +.open > .dropdown-toggle.btn-primary:focus, +.btn-primary:active.focus, +.btn-primary.active.focus, +.open > .dropdown-toggle.btn-primary.focus { + color: #fff; + background-color: #204d74; + border-color: #122b40; +} +.btn-primary:active, +.btn-primary.active, +.open > .dropdown-toggle.btn-primary { + background-image: none; +} +.btn-primary.disabled:hover, +.btn-primary[disabled]:hover, +fieldset[disabled] .btn-primary:hover, +.btn-primary.disabled:focus, +.btn-primary[disabled]:focus, +fieldset[disabled] .btn-primary:focus, +.btn-primary.disabled.focus, +.btn-primary[disabled].focus, +fieldset[disabled] .btn-primary.focus { + background-color: #337ab7; + border-color: #2e6da4; +} +.btn-primary .badge { + color: #337ab7; + background-color: #fff; +} +.btn-success { + color: #fff; + background-color: #5cb85c; + border-color: #4cae4c; +} +.btn-success:focus, +.btn-success.focus { + color: #fff; + background-color: #449d44; + border-color: #255625; +} +.btn-success:hover { + color: #fff; + background-color: #449d44; + border-color: #398439; +} +.btn-success:active, +.btn-success.active, +.open > .dropdown-toggle.btn-success { + color: #fff; + background-color: #449d44; + border-color: #398439; +} +.btn-success:active:hover, +.btn-success.active:hover, +.open > .dropdown-toggle.btn-success:hover, +.btn-success:active:focus, +.btn-success.active:focus, +.open > .dropdown-toggle.btn-success:focus, +.btn-success:active.focus, +.btn-success.active.focus, +.open > .dropdown-toggle.btn-success.focus { + color: #fff; + background-color: #398439; + border-color: #255625; +} +.btn-success:active, +.btn-success.active, +.open > .dropdown-toggle.btn-success { + background-image: none; +} +.btn-success.disabled:hover, +.btn-success[disabled]:hover, +fieldset[disabled] .btn-success:hover, +.btn-success.disabled:focus, +.btn-success[disabled]:focus, +fieldset[disabled] .btn-success:focus, +.btn-success.disabled.focus, +.btn-success[disabled].focus, +fieldset[disabled] .btn-success.focus { + background-color: #5cb85c; + border-color: #4cae4c; +} +.btn-success .badge { + color: #5cb85c; + background-color: #fff; +} +.btn-info { + color: #fff; + background-color: #5bc0de; + border-color: #46b8da; +} +.btn-info:focus, +.btn-info.focus { + color: #fff; + background-color: #31b0d5; + border-color: #1b6d85; +} +.btn-info:hover { + color: #fff; + background-color: #31b0d5; + border-color: #269abc; +} +.btn-info:active, +.btn-info.active, +.open > .dropdown-toggle.btn-info { + color: #fff; + background-color: #31b0d5; + border-color: #269abc; +} +.btn-info:active:hover, +.btn-info.active:hover, +.open > .dropdown-toggle.btn-info:hover, +.btn-info:active:focus, +.btn-info.active:focus, +.open > .dropdown-toggle.btn-info:focus, +.btn-info:active.focus, +.btn-info.active.focus, +.open > .dropdown-toggle.btn-info.focus { + color: #fff; + background-color: #269abc; + border-color: #1b6d85; +} +.btn-info:active, +.btn-info.active, +.open > .dropdown-toggle.btn-info { + background-image: none; +} +.btn-info.disabled:hover, +.btn-info[disabled]:hover, +fieldset[disabled] .btn-info:hover, +.btn-info.disabled:focus, +.btn-info[disabled]:focus, +fieldset[disabled] .btn-info:focus, +.btn-info.disabled.focus, +.btn-info[disabled].focus, +fieldset[disabled] .btn-info.focus { + background-color: #5bc0de; + border-color: #46b8da; +} +.btn-info .badge { + color: #5bc0de; + background-color: #fff; +} +.btn-warning { + color: #fff; + background-color: #f0ad4e; + border-color: #eea236; +} +.btn-warning:focus, +.btn-warning.focus { + color: #fff; + background-color: #ec971f; + border-color: #985f0d; +} +.btn-warning:hover { + color: #fff; + background-color: #ec971f; + border-color: #d58512; +} +.btn-warning:active, +.btn-warning.active, +.open > .dropdown-toggle.btn-warning { + color: #fff; + background-color: #ec971f; + border-color: #d58512; +} +.btn-warning:active:hover, +.btn-warning.active:hover, +.open > .dropdown-toggle.btn-warning:hover, +.btn-warning:active:focus, +.btn-warning.active:focus, +.open > .dropdown-toggle.btn-warning:focus, +.btn-warning:active.focus, +.btn-warning.active.focus, +.open > .dropdown-toggle.btn-warning.focus { + color: #fff; + background-color: #d58512; + border-color: #985f0d; +} +.btn-warning:active, +.btn-warning.active, +.open > .dropdown-toggle.btn-warning { + background-image: none; +} +.btn-warning.disabled:hover, +.btn-warning[disabled]:hover, +fieldset[disabled] .btn-warning:hover, +.btn-warning.disabled:focus, +.btn-warning[disabled]:focus, +fieldset[disabled] .btn-warning:focus, +.btn-warning.disabled.focus, +.btn-warning[disabled].focus, +fieldset[disabled] .btn-warning.focus { + background-color: #f0ad4e; + border-color: #eea236; +} +.btn-warning .badge { + color: #f0ad4e; + background-color: #fff; +} +.btn-danger { + color: #fff; + background-color: #d9534f; + border-color: #d43f3a; +} +.btn-danger:focus, +.btn-danger.focus { + color: #fff; + background-color: #c9302c; + border-color: #761c19; +} +.btn-danger:hover { + color: #fff; + background-color: #c9302c; + border-color: #ac2925; +} +.btn-danger:active, +.btn-danger.active, +.open > .dropdown-toggle.btn-danger { + color: #fff; + background-color: #c9302c; + border-color: #ac2925; +} +.btn-danger:active:hover, +.btn-danger.active:hover, +.open > .dropdown-toggle.btn-danger:hover, +.btn-danger:active:focus, +.btn-danger.active:focus, +.open > .dropdown-toggle.btn-danger:focus, +.btn-danger:active.focus, +.btn-danger.active.focus, +.open > .dropdown-toggle.btn-danger.focus { + color: #fff; + background-color: #ac2925; + border-color: #761c19; +} +.btn-danger:active, +.btn-danger.active, +.open > .dropdown-toggle.btn-danger { + background-image: none; +} +.btn-danger.disabled:hover, +.btn-danger[disabled]:hover, +fieldset[disabled] .btn-danger:hover, +.btn-danger.disabled:focus, +.btn-danger[disabled]:focus, +fieldset[disabled] .btn-danger:focus, +.btn-danger.disabled.focus, +.btn-danger[disabled].focus, +fieldset[disabled] .btn-danger.focus { + background-color: #d9534f; + border-color: #d43f3a; +} +.btn-danger .badge { + color: #d9534f; + background-color: #fff; +} +.btn-link { + font-weight: normal; + color: #337ab7; + border-radius: 0; +} +.btn-link, +.btn-link:active, +.btn-link.active, +.btn-link[disabled], +fieldset[disabled] .btn-link { + background-color: transparent; + -webkit-box-shadow: none; + box-shadow: none; +} +.btn-link, +.btn-link:hover, +.btn-link:focus, +.btn-link:active { + border-color: transparent; +} +.btn-link:hover, +.btn-link:focus { + color: #23527c; + text-decoration: underline; + background-color: transparent; +} +.btn-link[disabled]:hover, +fieldset[disabled] .btn-link:hover, +.btn-link[disabled]:focus, +fieldset[disabled] .btn-link:focus { + color: #777; + text-decoration: none; +} +.btn-lg, +.btn-group-lg > .btn { + padding: 10px 16px; + font-size: 18px; + line-height: 1.3333333; + border-radius: 6px; +} +.btn-sm, +.btn-group-sm > .btn { + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} +.btn-xs, +.btn-group-xs > .btn { + padding: 1px 5px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} +.btn-block { + display: block; + width: 100%; +} +.btn-block + .btn-block { + margin-top: 5px; +} +input[type="submit"].btn-block, +input[type="reset"].btn-block, +input[type="button"].btn-block { + width: 100%; +} +.fade { + opacity: 0; + -webkit-transition: opacity .15s linear; + -o-transition: opacity .15s linear; + transition: opacity .15s linear; +} +.fade.in { + opacity: 1; +} +.collapse { + display: none; +} +.collapse.in { + display: block; +} +tr.collapse.in { + display: table-row; +} +tbody.collapse.in { + display: table-row-group; +} +.collapsing { + position: relative; + height: 0; + overflow: hidden; + -webkit-transition-timing-function: ease; + -o-transition-timing-function: ease; + transition-timing-function: ease; + -webkit-transition-duration: .35s; + -o-transition-duration: .35s; + transition-duration: .35s; + -webkit-transition-property: height, visibility; + -o-transition-property: height, visibility; + transition-property: height, visibility; +} +.caret { + display: inline-block; + width: 0; + height: 0; + margin-left: 2px; + vertical-align: middle; + border-top: 4px dashed; + border-top: 4px solid \9; + border-right: 4px solid transparent; + border-left: 4px solid transparent; +} +.dropup, +.dropdown { + position: relative; +} +.dropdown-toggle:focus { + outline: 0; +} +.dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + font-size: 14px; + text-align: left; + list-style: none; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, .15); + border-radius: 4px; + -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); + box-shadow: 0 6px 12px rgba(0, 0, 0, .175); +} +.dropdown-menu.pull-right { + right: 0; + left: auto; +} +.dropdown-menu .divider { + height: 1px; + margin: 9px 0; + overflow: hidden; + background-color: #e5e5e5; +} +.dropdown-menu > li > a { + display: block; + padding: 3px 20px; + clear: both; + font-weight: normal; + line-height: 1.42857143; + color: #333; + white-space: nowrap; +} +.dropdown-menu > li > a:hover, +.dropdown-menu > li > a:focus { + color: #262626; + text-decoration: none; + background-color: #f5f5f5; +} +.dropdown-menu > .active > a, +.dropdown-menu > .active > a:hover, +.dropdown-menu > .active > a:focus { + color: #fff; + text-decoration: none; + background-color: #337ab7; + outline: 0; +} +.dropdown-menu > .disabled > a, +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + color: #777; +} +.dropdown-menu > .disabled > a:hover, +.dropdown-menu > .disabled > a:focus { + text-decoration: none; + cursor: not-allowed; + background-color: transparent; + background-image: none; + filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); +} +.open > .dropdown-menu { + display: block; +} +.open > a { + outline: 0; +} +.dropdown-menu-right { + right: 0; + left: auto; +} +.dropdown-menu-left { + right: auto; + left: 0; +} +.dropdown-header { + display: block; + padding: 3px 20px; + font-size: 12px; + line-height: 1.42857143; + color: #777; + white-space: nowrap; +} +.dropdown-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 990; +} +.pull-right > .dropdown-menu { + right: 0; + left: auto; +} +.dropup .caret, +.navbar-fixed-bottom .dropdown .caret { + content: ""; + border-top: 0; + border-bottom: 4px dashed; + border-bottom: 4px solid \9; +} +.dropup .dropdown-menu, +.navbar-fixed-bottom .dropdown .dropdown-menu { + top: auto; + bottom: 100%; + margin-bottom: 2px; +} +@media (min-width: 768px) { + .navbar-right .dropdown-menu { + right: 0; + left: auto; + } + .navbar-right .dropdown-menu-left { + right: auto; + left: 0; + } +} +.btn-group, +.btn-group-vertical { + position: relative; + display: inline-block; + vertical-align: middle; +} +.btn-group > .btn, +.btn-group-vertical > .btn { + position: relative; + float: left; +} +.btn-group > .btn:hover, +.btn-group-vertical > .btn:hover, +.btn-group > .btn:focus, +.btn-group-vertical > .btn:focus, +.btn-group > .btn:active, +.btn-group-vertical > .btn:active, +.btn-group > .btn.active, +.btn-group-vertical > .btn.active { + z-index: 2; +} +.btn-group .btn + .btn, +.btn-group .btn + .btn-group, +.btn-group .btn-group + .btn, +.btn-group .btn-group + .btn-group { + margin-left: -1px; +} +.btn-toolbar { + margin-left: -5px; +} +.btn-toolbar .btn, +.btn-toolbar .btn-group, +.btn-toolbar .input-group { + float: left; +} +.btn-toolbar > .btn, +.btn-toolbar > .btn-group, +.btn-toolbar > .input-group { + margin-left: 5px; +} +.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) { + border-radius: 0; +} +.btn-group > .btn:first-child { + margin-left: 0; +} +.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} +.btn-group > .btn:last-child:not(:first-child), +.btn-group > .dropdown-toggle:not(:first-child) { + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} +.btn-group > .btn-group { + float: left; +} +.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn { + border-radius: 0; +} +.btn-group > .btn-group:first-child:not(:last-child) > .btn:last-child, +.btn-group > .btn-group:first-child:not(:last-child) > .dropdown-toggle { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} +.btn-group > .btn-group:last-child:not(:first-child) > .btn:first-child { + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} +.btn-group .dropdown-toggle:active, +.btn-group.open .dropdown-toggle { + outline: 0; +} +.btn-group > .btn + .dropdown-toggle { + padding-right: 8px; + padding-left: 8px; +} +.btn-group > .btn-lg + .dropdown-toggle { + padding-right: 12px; + padding-left: 12px; +} +.btn-group.open .dropdown-toggle { + -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); + box-shadow: inset 0 3px 5px rgba(0, 0, 0, .125); +} +.btn-group.open .dropdown-toggle.btn-link { + -webkit-box-shadow: none; + box-shadow: none; +} +.btn .caret { + margin-left: 0; +} +.btn-lg .caret { + border-width: 5px 5px 0; + border-bottom-width: 0; +} +.dropup .btn-lg .caret { + border-width: 0 5px 5px; +} +.btn-group-vertical > .btn, +.btn-group-vertical > .btn-group, +.btn-group-vertical > .btn-group > .btn { + display: block; + float: none; + width: 100%; + max-width: 100%; +} +.btn-group-vertical > .btn-group > .btn { + float: none; +} +.btn-group-vertical > .btn + .btn, +.btn-group-vertical > .btn + .btn-group, +.btn-group-vertical > .btn-group + .btn, +.btn-group-vertical > .btn-group + .btn-group { + margin-top: -1px; + margin-left: 0; +} +.btn-group-vertical > .btn:not(:first-child):not(:last-child) { + border-radius: 0; +} +.btn-group-vertical > .btn:first-child:not(:last-child) { + border-top-left-radius: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; +} +.btn-group-vertical > .btn:last-child:not(:first-child) { + border-top-left-radius: 0; + border-top-right-radius: 0; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; +} +.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn { + border-radius: 0; +} +.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child, +.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle { + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; +} +.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child { + border-top-left-radius: 0; + border-top-right-radius: 0; +} +.btn-group-justified { + display: table; + width: 100%; + table-layout: fixed; + border-collapse: separate; +} +.btn-group-justified > .btn, +.btn-group-justified > .btn-group { + display: table-cell; + float: none; + width: 1%; +} +.btn-group-justified > .btn-group .btn { + width: 100%; +} +.btn-group-justified > .btn-group .dropdown-menu { + left: auto; +} +[data-toggle="buttons"] > .btn input[type="radio"], +[data-toggle="buttons"] > .btn-group > .btn input[type="radio"], +[data-toggle="buttons"] > .btn input[type="checkbox"], +[data-toggle="buttons"] > .btn-group > .btn input[type="checkbox"] { + position: absolute; + clip: rect(0, 0, 0, 0); + pointer-events: none; +} +.input-group { + position: relative; + display: table; + border-collapse: separate; +} +.input-group[class*="col-"] { + float: none; + padding-right: 0; + padding-left: 0; +} +.input-group .form-control { + position: relative; + z-index: 2; + float: left; + width: 100%; + margin-bottom: 0; +} +.input-group .form-control:focus { + z-index: 3; +} +.input-group-lg > .form-control, +.input-group-lg > .input-group-addon, +.input-group-lg > .input-group-btn > .btn { + height: 46px; + padding: 10px 16px; + font-size: 18px; + line-height: 1.3333333; + border-radius: 6px; +} +select.input-group-lg > .form-control, +select.input-group-lg > .input-group-addon, +select.input-group-lg > .input-group-btn > .btn { + height: 46px; + line-height: 46px; +} +textarea.input-group-lg > .form-control, +textarea.input-group-lg > .input-group-addon, +textarea.input-group-lg > .input-group-btn > .btn, +select[multiple].input-group-lg > .form-control, +select[multiple].input-group-lg > .input-group-addon, +select[multiple].input-group-lg > .input-group-btn > .btn { + height: auto; +} +.input-group-sm > .form-control, +.input-group-sm > .input-group-addon, +.input-group-sm > .input-group-btn > .btn { + height: 30px; + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; + border-radius: 3px; +} +select.input-group-sm > .form-control, +select.input-group-sm > .input-group-addon, +select.input-group-sm > .input-group-btn > .btn { + height: 30px; + line-height: 30px; +} +textarea.input-group-sm > .form-control, +textarea.input-group-sm > .input-group-addon, +textarea.input-group-sm > .input-group-btn > .btn, +select[multiple].input-group-sm > .form-control, +select[multiple].input-group-sm > .input-group-addon, +select[multiple].input-group-sm > .input-group-btn > .btn { + height: auto; +} +.input-group-addon, +.input-group-btn, +.input-group .form-control { + display: table-cell; +} +.input-group-addon:not(:first-child):not(:last-child), +.input-group-btn:not(:first-child):not(:last-child), +.input-group .form-control:not(:first-child):not(:last-child) { + border-radius: 0; +} +.input-group-addon, +.input-group-btn { + width: 1%; + white-space: nowrap; + vertical-align: middle; +} +.input-group-addon { + padding: 6px 12px; + font-size: 14px; + font-weight: normal; + line-height: 1; + color: #555; + text-align: center; + background-color: #eee; + border: 1px solid #ccc; + border-radius: 4px; +} +.input-group-addon.input-sm { + padding: 5px 10px; + font-size: 12px; + border-radius: 3px; +} +.input-group-addon.input-lg { + padding: 10px 16px; + font-size: 18px; + border-radius: 6px; +} +.input-group-addon input[type="radio"], +.input-group-addon input[type="checkbox"] { + margin-top: 0; +} +.input-group .form-control:first-child, +.input-group-addon:first-child, +.input-group-btn:first-child > .btn, +.input-group-btn:first-child > .btn-group > .btn, +.input-group-btn:first-child > .dropdown-toggle, +.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle), +.input-group-btn:last-child > .btn-group:not(:last-child) > .btn { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} +.input-group-addon:first-child { + border-right: 0; +} +.input-group .form-control:last-child, +.input-group-addon:last-child, +.input-group-btn:last-child > .btn, +.input-group-btn:last-child > .btn-group > .btn, +.input-group-btn:last-child > .dropdown-toggle, +.input-group-btn:first-child > .btn:not(:first-child), +.input-group-btn:first-child > .btn-group:not(:first-child) > .btn { + border-top-left-radius: 0; + border-bottom-left-radius: 0; +} +.input-group-addon:last-child { + border-left: 0; +} +.input-group-btn { + position: relative; + font-size: 0; + white-space: nowrap; +} +.input-group-btn > .btn { + position: relative; +} +.input-group-btn > .btn + .btn { + margin-left: -1px; +} +.input-group-btn > .btn:hover, +.input-group-btn > .btn:focus, +.input-group-btn > .btn:active { + z-index: 2; +} +.input-group-btn:first-child > .btn, +.input-group-btn:first-child > .btn-group { + margin-right: -1px; +} +.input-group-btn:last-child > .btn, +.input-group-btn:last-child > .btn-group { + z-index: 2; + margin-left: -1px; +} +.nav { + padding-left: 0; + margin-bottom: 0; + list-style: none; +} +.nav > li { + position: relative; + display: block; +} +.nav > li > a { + position: relative; + display: block; + padding: 10px 15px; +} +.nav > li > a:hover, +.nav > li > a:focus { + text-decoration: none; + background-color: #eee; +} +.nav > li.disabled > a { + color: #777; +} +.nav > li.disabled > a:hover, +.nav > li.disabled > a:focus { + color: #777; + text-decoration: none; + cursor: not-allowed; + background-color: transparent; +} +.nav .open > a, +.nav .open > a:hover, +.nav .open > a:focus { + background-color: #eee; + border-color: #337ab7; +} +.nav .nav-divider { + height: 1px; + margin: 9px 0; + overflow: hidden; + background-color: #e5e5e5; +} +.nav > li > a > img { + max-width: none; +} +.nav-tabs { + border-bottom: 1px solid #ddd; +} +.nav-tabs > li { + float: left; + margin-bottom: -1px; +} +.nav-tabs > li > a { + margin-right: 2px; + line-height: 1.42857143; + border: 1px solid transparent; + border-radius: 4px 4px 0 0; +} +.nav-tabs > li > a:hover { + border-color: #eee #eee #ddd; +} +.nav-tabs > li.active > a, +.nav-tabs > li.active > a:hover, +.nav-tabs > li.active > a:focus { + color: #555; + cursor: default; + background-color: #fff; + border: 1px solid #ddd; + border-bottom-color: transparent; +} +.nav-tabs.nav-justified { + width: 100%; + border-bottom: 0; +} +.nav-tabs.nav-justified > li { + float: none; +} +.nav-tabs.nav-justified > li > a { + margin-bottom: 5px; + text-align: center; +} +.nav-tabs.nav-justified > .dropdown .dropdown-menu { + top: auto; + left: auto; +} +@media (min-width: 768px) { + .nav-tabs.nav-justified > li { + display: table-cell; + width: 1%; + } + .nav-tabs.nav-justified > li > a { + margin-bottom: 0; + } +} +.nav-tabs.nav-justified > li > a { + margin-right: 0; + border-radius: 4px; +} +.nav-tabs.nav-justified > .active > a, +.nav-tabs.nav-justified > .active > a:hover, +.nav-tabs.nav-justified > .active > a:focus { + border: 1px solid #ddd; +} +@media (min-width: 768px) { + .nav-tabs.nav-justified > li > a { + border-bottom: 1px solid #ddd; + border-radius: 4px 4px 0 0; + } + .nav-tabs.nav-justified > .active > a, + .nav-tabs.nav-justified > .active > a:hover, + .nav-tabs.nav-justified > .active > a:focus { + border-bottom-color: #fff; + } +} +.nav-pills > li { + float: left; +} +.nav-pills > li > a { + border-radius: 4px; +} +.nav-pills > li + li { + margin-left: 2px; +} +.nav-pills > li.active > a, +.nav-pills > li.active > a:hover, +.nav-pills > li.active > a:focus { + color: #fff; + background-color: #337ab7; +} +.nav-stacked > li { + float: none; +} +.nav-stacked > li + li { + margin-top: 2px; + margin-left: 0; +} +.nav-justified { + width: 100%; +} +.nav-justified > li { + float: none; +} +.nav-justified > li > a { + margin-bottom: 5px; + text-align: center; +} +.nav-justified > .dropdown .dropdown-menu { + top: auto; + left: auto; +} +@media (min-width: 768px) { + .nav-justified > li { + display: table-cell; + width: 1%; + } + .nav-justified > li > a { + margin-bottom: 0; + } +} +.nav-tabs-justified { + border-bottom: 0; +} +.nav-tabs-justified > li > a { + margin-right: 0; + border-radius: 4px; +} +.nav-tabs-justified > .active > a, +.nav-tabs-justified > .active > a:hover, +.nav-tabs-justified > .active > a:focus { + border: 1px solid #ddd; +} +@media (min-width: 768px) { + .nav-tabs-justified > li > a { + border-bottom: 1px solid #ddd; + border-radius: 4px 4px 0 0; + } + .nav-tabs-justified > .active > a, + .nav-tabs-justified > .active > a:hover, + .nav-tabs-justified > .active > a:focus { + border-bottom-color: #fff; + } +} +.tab-content > .tab-pane { + display: none; +} +.tab-content > .active { + display: block; +} +.nav-tabs .dropdown-menu { + margin-top: -1px; + border-top-left-radius: 0; + border-top-right-radius: 0; +} +.navbar { + position: relative; + min-height: 50px; + margin-bottom: 20px; + border: 1px solid transparent; +} +@media (min-width: 768px) { + .navbar { + border-radius: 4px; + } +} +@media (min-width: 768px) { + .navbar-header { + float: left; + } +} +.navbar-collapse { + padding-right: 15px; + padding-left: 15px; + overflow-x: visible; + -webkit-overflow-scrolling: touch; + border-top: 1px solid transparent; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1); +} +.navbar-collapse.in { + overflow-y: auto; +} +@media (min-width: 768px) { + .navbar-collapse { + width: auto; + border-top: 0; + -webkit-box-shadow: none; + box-shadow: none; + } + .navbar-collapse.collapse { + display: block !important; + height: auto !important; + padding-bottom: 0; + overflow: visible !important; + } + .navbar-collapse.in { + overflow-y: visible; + } + .navbar-fixed-top .navbar-collapse, + .navbar-static-top .navbar-collapse, + .navbar-fixed-bottom .navbar-collapse { + padding-right: 0; + padding-left: 0; + } +} +.navbar-fixed-top .navbar-collapse, +.navbar-fixed-bottom .navbar-collapse { + max-height: 340px; +} +@media (max-device-width: 480px) and (orientation: landscape) { + .navbar-fixed-top .navbar-collapse, + .navbar-fixed-bottom .navbar-collapse { + max-height: 200px; + } +} +.container > .navbar-header, +.container-fluid > .navbar-header, +.container > .navbar-collapse, +.container-fluid > .navbar-collapse { + margin-right: -15px; + margin-left: -15px; +} +@media (min-width: 768px) { + .container > .navbar-header, + .container-fluid > .navbar-header, + .container > .navbar-collapse, + .container-fluid > .navbar-collapse { + margin-right: 0; + margin-left: 0; + } +} +.navbar-static-top { + z-index: 1000; + border-width: 0 0 1px; +} +@media (min-width: 768px) { + .navbar-static-top { + border-radius: 0; + } +} +.navbar-fixed-top, +.navbar-fixed-bottom { + position: fixed; + right: 0; + left: 0; + z-index: 1030; +} +@media (min-width: 768px) { + .navbar-fixed-top, + .navbar-fixed-bottom { + border-radius: 0; + } +} +.navbar-fixed-top { + top: 0; + border-width: 0 0 1px; +} +.navbar-fixed-bottom { + bottom: 0; + margin-bottom: 0; + border-width: 1px 0 0; +} +.navbar-brand { + float: left; + height: 50px; + padding: 15px 15px; + font-size: 18px; + line-height: 20px; +} +.navbar-brand:hover, +.navbar-brand:focus { + text-decoration: none; +} +.navbar-brand > img { + display: block; +} +@media (min-width: 768px) { + .navbar > .container .navbar-brand, + .navbar > .container-fluid .navbar-brand { + margin-left: -15px; + } +} +.navbar-toggle { + position: relative; + float: right; + padding: 9px 10px; + margin-top: 8px; + margin-right: 15px; + margin-bottom: 8px; + background-color: transparent; + background-image: none; + border: 1px solid transparent; + border-radius: 4px; +} +.navbar-toggle:focus { + outline: 0; +} +.navbar-toggle .icon-bar { + display: block; + width: 22px; + height: 2px; + border-radius: 1px; +} +.navbar-toggle .icon-bar + .icon-bar { + margin-top: 4px; +} +@media (min-width: 768px) { + .navbar-toggle { + display: none; + } +} +.navbar-nav { + margin: 7.5px -15px; +} +.navbar-nav > li > a { + padding-top: 10px; + padding-bottom: 10px; + line-height: 20px; +} +@media (max-width: 767px) { + .navbar-nav .open .dropdown-menu { + position: static; + float: none; + width: auto; + margin-top: 0; + background-color: transparent; + border: 0; + -webkit-box-shadow: none; + box-shadow: none; + } + .navbar-nav .open .dropdown-menu > li > a, + .navbar-nav .open .dropdown-menu .dropdown-header { + padding: 5px 15px 5px 25px; + } + .navbar-nav .open .dropdown-menu > li > a { + line-height: 20px; + } + .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-nav .open .dropdown-menu > li > a:focus { + background-image: none; + } +} +@media (min-width: 768px) { + .navbar-nav { + float: left; + margin: 0; + } + .navbar-nav > li { + float: left; + } + .navbar-nav > li > a { + padding-top: 15px; + padding-bottom: 15px; + } +} +.navbar-form { + padding: 10px 15px; + margin-top: 8px; + margin-right: -15px; + margin-bottom: 8px; + margin-left: -15px; + border-top: 1px solid transparent; + border-bottom: 1px solid transparent; + -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, .1), 0 1px 0 rgba(255, 255, 255, .1); +} +@media (min-width: 768px) { + .navbar-form .form-group { + display: inline-block; + margin-bottom: 0; + vertical-align: middle; + } + .navbar-form .form-control { + display: inline-block; + width: auto; + vertical-align: middle; + } + .navbar-form .form-control-static { + display: inline-block; + } + .navbar-form .input-group { + display: inline-table; + vertical-align: middle; + } + .navbar-form .input-group .input-group-addon, + .navbar-form .input-group .input-group-btn, + .navbar-form .input-group .form-control { + width: auto; + } + .navbar-form .input-group > .form-control { + width: 100%; + } + .navbar-form .control-label { + margin-bottom: 0; + vertical-align: middle; + } + .navbar-form .radio, + .navbar-form .checkbox { + display: inline-block; + margin-top: 0; + margin-bottom: 0; + vertical-align: middle; + } + .navbar-form .radio label, + .navbar-form .checkbox label { + padding-left: 0; + } + .navbar-form .radio input[type="radio"], + .navbar-form .checkbox input[type="checkbox"] { + position: relative; + margin-left: 0; + } + .navbar-form .has-feedback .form-control-feedback { + top: 0; + } +} +@media (max-width: 767px) { + .navbar-form .form-group { + margin-bottom: 5px; + } + .navbar-form .form-group:last-child { + margin-bottom: 0; + } +} +@media (min-width: 768px) { + .navbar-form { + width: auto; + padding-top: 0; + padding-bottom: 0; + margin-right: 0; + margin-left: 0; + border: 0; + -webkit-box-shadow: none; + box-shadow: none; + } +} +.navbar-nav > li > .dropdown-menu { + margin-top: 0; + border-top-left-radius: 0; + border-top-right-radius: 0; +} +.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu { + margin-bottom: 0; + border-top-left-radius: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 0; + border-bottom-left-radius: 0; +} +.navbar-btn { + margin-top: 8px; + margin-bottom: 8px; +} +.navbar-btn.btn-sm { + margin-top: 10px; + margin-bottom: 10px; +} +.navbar-btn.btn-xs { + margin-top: 14px; + margin-bottom: 14px; +} +.navbar-text { + margin-top: 15px; + margin-bottom: 15px; +} +@media (min-width: 768px) { + .navbar-text { + float: left; + margin-right: 15px; + margin-left: 15px; + } +} +@media (min-width: 768px) { + .navbar-left { + float: left !important; + } + .navbar-right { + float: right !important; + margin-right: -15px; + } + .navbar-right ~ .navbar-right { + margin-right: 0; + } +} +.navbar-default { + background-color: #f8f8f8; + border-color: #e7e7e7; +} +.navbar-default .navbar-brand { + color: #777; +} +.navbar-default .navbar-brand:hover, +.navbar-default .navbar-brand:focus { + color: #5e5e5e; + background-color: transparent; +} +.navbar-default .navbar-text { + color: #777; +} +.navbar-default .navbar-nav > li > a { + color: #777; +} +.navbar-default .navbar-nav > li > a:hover, +.navbar-default .navbar-nav > li > a:focus { + color: #333; + background-color: transparent; +} +.navbar-default .navbar-nav > .active > a, +.navbar-default .navbar-nav > .active > a:hover, +.navbar-default .navbar-nav > .active > a:focus { + color: #555; + background-color: #e7e7e7; +} +.navbar-default .navbar-nav > .disabled > a, +.navbar-default .navbar-nav > .disabled > a:hover, +.navbar-default .navbar-nav > .disabled > a:focus { + color: #ccc; + background-color: transparent; +} +.navbar-default .navbar-toggle { + border-color: #ddd; +} +.navbar-default .navbar-toggle:hover, +.navbar-default .navbar-toggle:focus { + background-color: #ddd; +} +.navbar-default .navbar-toggle .icon-bar { + background-color: #888; +} +.navbar-default .navbar-collapse, +.navbar-default .navbar-form { + border-color: #e7e7e7; +} +.navbar-default .navbar-nav > .open > a, +.navbar-default .navbar-nav > .open > a:hover, +.navbar-default .navbar-nav > .open > a:focus { + color: #555; + background-color: #e7e7e7; +} +@media (max-width: 767px) { + .navbar-default .navbar-nav .open .dropdown-menu > li > a { + color: #777; + } + .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus { + color: #333; + background-color: transparent; + } + .navbar-default .navbar-nav .open .dropdown-menu > .active > a, + .navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus { + color: #555; + background-color: #e7e7e7; + } + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a, + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover, + .navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus { + color: #ccc; + background-color: transparent; + } +} +.navbar-default .navbar-link { + color: #777; +} +.navbar-default .navbar-link:hover { + color: #333; +} +.navbar-default .btn-link { + color: #777; +} +.navbar-default .btn-link:hover, +.navbar-default .btn-link:focus { + color: #333; +} +.navbar-default .btn-link[disabled]:hover, +fieldset[disabled] .navbar-default .btn-link:hover, +.navbar-default .btn-link[disabled]:focus, +fieldset[disabled] .navbar-default .btn-link:focus { + color: #ccc; +} +.navbar-inverse { + background-color: #222; + border-color: #080808; +} +.navbar-inverse .navbar-brand { + color: #9d9d9d; +} +.navbar-inverse .navbar-brand:hover, +.navbar-inverse .navbar-brand:focus { + color: #fff; + background-color: transparent; +} +.navbar-inverse .navbar-text { + color: #9d9d9d; +} +.navbar-inverse .navbar-nav > li > a { + color: #9d9d9d; +} +.navbar-inverse .navbar-nav > li > a:hover, +.navbar-inverse .navbar-nav > li > a:focus { + color: #fff; + background-color: transparent; +} +.navbar-inverse .navbar-nav > .active > a, +.navbar-inverse .navbar-nav > .active > a:hover, +.navbar-inverse .navbar-nav > .active > a:focus { + color: #fff; + background-color: #080808; +} +.navbar-inverse .navbar-nav > .disabled > a, +.navbar-inverse .navbar-nav > .disabled > a:hover, +.navbar-inverse .navbar-nav > .disabled > a:focus { + color: #444; + background-color: transparent; +} +.navbar-inverse .navbar-toggle { + border-color: #333; +} +.navbar-inverse .navbar-toggle:hover, +.navbar-inverse .navbar-toggle:focus { + background-color: #333; +} +.navbar-inverse .navbar-toggle .icon-bar { + background-color: #fff; +} +.navbar-inverse .navbar-collapse, +.navbar-inverse .navbar-form { + border-color: #101010; +} +.navbar-inverse .navbar-nav > .open > a, +.navbar-inverse .navbar-nav > .open > a:hover, +.navbar-inverse .navbar-nav > .open > a:focus { + color: #fff; + background-color: #080808; +} +@media (max-width: 767px) { + .navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header { + border-color: #080808; + } + .navbar-inverse .navbar-nav .open .dropdown-menu .divider { + background-color: #080808; + } + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a { + color: #9d9d9d; + } + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus { + color: #fff; + background-color: transparent; + } + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a, + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus { + color: #fff; + background-color: #080808; + } + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a, + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover, + .navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus { + color: #444; + background-color: transparent; + } +} +.navbar-inverse .navbar-link { + color: #9d9d9d; +} +.navbar-inverse .navbar-link:hover { + color: #fff; +} +.navbar-inverse .btn-link { + color: #9d9d9d; +} +.navbar-inverse .btn-link:hover, +.navbar-inverse .btn-link:focus { + color: #fff; +} +.navbar-inverse .btn-link[disabled]:hover, +fieldset[disabled] .navbar-inverse .btn-link:hover, +.navbar-inverse .btn-link[disabled]:focus, +fieldset[disabled] .navbar-inverse .btn-link:focus { + color: #444; +} +.breadcrumb { + padding: 8px 15px; + margin-bottom: 20px; + list-style: none; + background-color: #f5f5f5; + border-radius: 4px; +} +.breadcrumb > li { + display: inline-block; +} +.breadcrumb > li + li:before { + padding: 0 5px; + color: #ccc; + content: "/\00a0"; +} +.breadcrumb > .active { + color: #777; +} +.pagination { + display: inline-block; + padding-left: 0; + margin: 20px 0; + border-radius: 4px; +} +.pagination > li { + display: inline; +} +.pagination > li > a, +.pagination > li > span { + position: relative; + float: left; + padding: 6px 12px; + margin-left: -1px; + line-height: 1.42857143; + color: #337ab7; + text-decoration: none; + background-color: #fff; + border: 1px solid #ddd; +} +.pagination > li:first-child > a, +.pagination > li:first-child > span { + margin-left: 0; + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; +} +.pagination > li:last-child > a, +.pagination > li:last-child > span { + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; +} +.pagination > li > a:hover, +.pagination > li > span:hover, +.pagination > li > a:focus, +.pagination > li > span:focus { + z-index: 2; + color: #23527c; + background-color: #eee; + border-color: #ddd; +} +.pagination > .active > a, +.pagination > .active > span, +.pagination > .active > a:hover, +.pagination > .active > span:hover, +.pagination > .active > a:focus, +.pagination > .active > span:focus { + z-index: 3; + color: #fff; + cursor: default; + background-color: #337ab7; + border-color: #337ab7; +} +.pagination > .disabled > span, +.pagination > .disabled > span:hover, +.pagination > .disabled > span:focus, +.pagination > .disabled > a, +.pagination > .disabled > a:hover, +.pagination > .disabled > a:focus { + color: #777; + cursor: not-allowed; + background-color: #fff; + border-color: #ddd; +} +.pagination-lg > li > a, +.pagination-lg > li > span { + padding: 10px 16px; + font-size: 18px; + line-height: 1.3333333; +} +.pagination-lg > li:first-child > a, +.pagination-lg > li:first-child > span { + border-top-left-radius: 6px; + border-bottom-left-radius: 6px; +} +.pagination-lg > li:last-child > a, +.pagination-lg > li:last-child > span { + border-top-right-radius: 6px; + border-bottom-right-radius: 6px; +} +.pagination-sm > li > a, +.pagination-sm > li > span { + padding: 5px 10px; + font-size: 12px; + line-height: 1.5; +} +.pagination-sm > li:first-child > a, +.pagination-sm > li:first-child > span { + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; +} +.pagination-sm > li:last-child > a, +.pagination-sm > li:last-child > span { + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; +} +.pager { + padding-left: 0; + margin: 20px 0; + text-align: center; + list-style: none; +} +.pager li { + display: inline; +} +.pager li > a, +.pager li > span { + display: inline-block; + padding: 5px 14px; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 15px; +} +.pager li > a:hover, +.pager li > a:focus { + text-decoration: none; + background-color: #eee; +} +.pager .next > a, +.pager .next > span { + float: right; +} +.pager .previous > a, +.pager .previous > span { + float: left; +} +.pager .disabled > a, +.pager .disabled > a:hover, +.pager .disabled > a:focus, +.pager .disabled > span { + color: #777; + cursor: not-allowed; + background-color: #fff; +} +.label { + display: inline; + padding: .2em .6em .3em; + font-size: 75%; + font-weight: bold; + line-height: 1; + color: #fff; + text-align: center; + white-space: nowrap; + vertical-align: baseline; + border-radius: .25em; +} +a.label:hover, +a.label:focus { + color: #fff; + text-decoration: none; + cursor: pointer; +} +.label:empty { + display: none; +} +.btn .label { + position: relative; + top: -1px; +} +.label-default { + background-color: #777; +} +.label-default[href]:hover, +.label-default[href]:focus { + background-color: #5e5e5e; +} +.label-primary { + background-color: #337ab7; +} +.label-primary[href]:hover, +.label-primary[href]:focus { + background-color: #286090; +} +.label-success { + background-color: #5cb85c; +} +.label-success[href]:hover, +.label-success[href]:focus { + background-color: #449d44; +} +.label-info { + background-color: #5bc0de; +} +.label-info[href]:hover, +.label-info[href]:focus { + background-color: #31b0d5; +} +.label-warning { + background-color: #f0ad4e; +} +.label-warning[href]:hover, +.label-warning[href]:focus { + background-color: #ec971f; +} +.label-danger { + background-color: #d9534f; +} +.label-danger[href]:hover, +.label-danger[href]:focus { + background-color: #c9302c; +} +.badge { + display: inline-block; + min-width: 10px; + padding: 3px 7px; + font-size: 12px; + font-weight: bold; + line-height: 1; + color: #fff; + text-align: center; + white-space: nowrap; + vertical-align: middle; + background-color: #777; + border-radius: 10px; +} +.badge:empty { + display: none; +} +.btn .badge { + position: relative; + top: -1px; +} +.btn-xs .badge, +.btn-group-xs > .btn .badge { + top: 0; + padding: 1px 5px; +} +a.badge:hover, +a.badge:focus { + color: #fff; + text-decoration: none; + cursor: pointer; +} +.list-group-item.active > .badge, +.nav-pills > .active > a > .badge { + color: #337ab7; + background-color: #fff; +} +.list-group-item > .badge { + float: right; +} +.list-group-item > .badge + .badge { + margin-right: 5px; +} +.nav-pills > li > a > .badge { + margin-left: 3px; +} +.jumbotron { + padding-top: 30px; + padding-bottom: 30px; + margin-bottom: 30px; + color: inherit; + background-color: #eee; +} +.jumbotron h1, +.jumbotron .h1 { + color: inherit; +} +.jumbotron p { + margin-bottom: 15px; + font-size: 21px; + font-weight: 200; +} +.jumbotron > hr { + border-top-color: #d5d5d5; +} +.container .jumbotron, +.container-fluid .jumbotron { + padding-right: 15px; + padding-left: 15px; + border-radius: 6px; +} +.jumbotron .container { + max-width: 100%; +} +@media screen and (min-width: 768px) { + .jumbotron { + padding-top: 48px; + padding-bottom: 48px; + } + .container .jumbotron, + .container-fluid .jumbotron { + padding-right: 60px; + padding-left: 60px; + } + .jumbotron h1, + .jumbotron .h1 { + font-size: 63px; + } +} +.thumbnail { + display: block; + padding: 4px; + margin-bottom: 20px; + line-height: 1.42857143; + background-color: #fff; + border: 1px solid #ddd; + border-radius: 4px; + -webkit-transition: border .2s ease-in-out; + -o-transition: border .2s ease-in-out; + transition: border .2s ease-in-out; +} +.thumbnail > img, +.thumbnail a > img { + margin-right: auto; + margin-left: auto; +} +a.thumbnail:hover, +a.thumbnail:focus, +a.thumbnail.active { + border-color: #337ab7; +} +.thumbnail .caption { + padding: 9px; + color: #333; +} +.alert { + padding: 15px; + margin-bottom: 20px; + border: 1px solid transparent; + border-radius: 4px; +} +.alert h4 { + margin-top: 0; + color: inherit; +} +.alert .alert-link { + font-weight: bold; +} +.alert > p, +.alert > ul { + margin-bottom: 0; +} +.alert > p + p { + margin-top: 5px; +} +.alert-dismissable, +.alert-dismissible { + padding-right: 35px; +} +.alert-dismissable .close, +.alert-dismissible .close { + position: relative; + top: -2px; + right: -21px; + color: inherit; +} +.alert-success { + color: #3c763d; + background-color: #dff0d8; + border-color: #d6e9c6; +} +.alert-success hr { + border-top-color: #c9e2b3; +} +.alert-success .alert-link { + color: #2b542c; +} +.alert-info { + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; +} +.alert-info hr { + border-top-color: #a6e1ec; +} +.alert-info .alert-link { + color: #245269; +} +.alert-warning { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; +} +.alert-warning hr { + border-top-color: #f7e1b5; +} +.alert-warning .alert-link { + color: #66512c; +} +.alert-danger { + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; +} +.alert-danger hr { + border-top-color: #e4b9c0; +} +.alert-danger .alert-link { + color: #843534; +} +@-webkit-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +@-o-keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +@keyframes progress-bar-stripes { + from { + background-position: 40px 0; + } + to { + background-position: 0 0; + } +} +.progress { + height: 20px; + margin-bottom: 20px; + overflow: hidden; + background-color: #f5f5f5; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, .1); +} +.progress-bar { + float: left; + width: 0; + height: 100%; + font-size: 12px; + line-height: 20px; + color: #fff; + text-align: center; + background-color: #337ab7; + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .15); + -webkit-transition: width .6s ease; + -o-transition: width .6s ease; + transition: width .6s ease; +} +.progress-striped .progress-bar, +.progress-bar-striped { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + -webkit-background-size: 40px 40px; + background-size: 40px 40px; +} +.progress.active .progress-bar, +.progress-bar.active { + -webkit-animation: progress-bar-stripes 2s linear infinite; + -o-animation: progress-bar-stripes 2s linear infinite; + animation: progress-bar-stripes 2s linear infinite; +} +.progress-bar-success { + background-color: #5cb85c; +} +.progress-striped .progress-bar-success { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); +} +.progress-bar-info { + background-color: #5bc0de; +} +.progress-striped .progress-bar-info { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); +} +.progress-bar-warning { + background-color: #f0ad4e; +} +.progress-striped .progress-bar-warning { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); +} +.progress-bar-danger { + background-color: #d9534f; +} +.progress-striped .progress-bar-danger { + background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); + background-image: linear-gradient(45deg, rgba(255, 255, 255, .15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, .15) 50%, rgba(255, 255, 255, .15) 75%, transparent 75%, transparent); +} +.media { + margin-top: 15px; +} +.media:first-child { + margin-top: 0; +} +.media, +.media-body { + overflow: hidden; + zoom: 1; +} +.media-body { + width: 10000px; +} +.media-object { + display: block; +} +.media-object.img-thumbnail { + max-width: none; +} +.media-right, +.media > .pull-right { + padding-left: 10px; +} +.media-left, +.media > .pull-left { + padding-right: 10px; +} +.media-left, +.media-right, +.media-body { + display: table-cell; + vertical-align: top; +} +.media-middle { + vertical-align: middle; +} +.media-bottom { + vertical-align: bottom; +} +.media-heading { + margin-top: 0; + margin-bottom: 5px; +} +.media-list { + padding-left: 0; + list-style: none; +} +.list-group { + padding-left: 0; + margin-bottom: 20px; +} +.list-group-item { + position: relative; + display: block; + padding: 10px 15px; + margin-bottom: -1px; + background-color: #fff; + border: 1px solid #ddd; +} +.list-group-item:first-child { + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} +.list-group-item:last-child { + margin-bottom: 0; + border-bottom-right-radius: 4px; + border-bottom-left-radius: 4px; +} +a.list-group-item, +button.list-group-item { + color: #555; +} +a.list-group-item .list-group-item-heading, +button.list-group-item .list-group-item-heading { + color: #333; +} +a.list-group-item:hover, +button.list-group-item:hover, +a.list-group-item:focus, +button.list-group-item:focus { + color: #555; + text-decoration: none; + background-color: #f5f5f5; +} +button.list-group-item { + width: 100%; + text-align: left; +} +.list-group-item.disabled, +.list-group-item.disabled:hover, +.list-group-item.disabled:focus { + color: #777; + cursor: not-allowed; + background-color: #eee; +} +.list-group-item.disabled .list-group-item-heading, +.list-group-item.disabled:hover .list-group-item-heading, +.list-group-item.disabled:focus .list-group-item-heading { + color: inherit; +} +.list-group-item.disabled .list-group-item-text, +.list-group-item.disabled:hover .list-group-item-text, +.list-group-item.disabled:focus .list-group-item-text { + color: #777; +} +.list-group-item.active, +.list-group-item.active:hover, +.list-group-item.active:focus { + z-index: 2; + color: #fff; + background-color: #337ab7; + border-color: #337ab7; +} +.list-group-item.active .list-group-item-heading, +.list-group-item.active:hover .list-group-item-heading, +.list-group-item.active:focus .list-group-item-heading, +.list-group-item.active .list-group-item-heading > small, +.list-group-item.active:hover .list-group-item-heading > small, +.list-group-item.active:focus .list-group-item-heading > small, +.list-group-item.active .list-group-item-heading > .small, +.list-group-item.active:hover .list-group-item-heading > .small, +.list-group-item.active:focus .list-group-item-heading > .small { + color: inherit; +} +.list-group-item.active .list-group-item-text, +.list-group-item.active:hover .list-group-item-text, +.list-group-item.active:focus .list-group-item-text { + color: #c7ddef; +} +.list-group-item-success { + color: #3c763d; + background-color: #dff0d8; +} +a.list-group-item-success, +button.list-group-item-success { + color: #3c763d; +} +a.list-group-item-success .list-group-item-heading, +button.list-group-item-success .list-group-item-heading { + color: inherit; +} +a.list-group-item-success:hover, +button.list-group-item-success:hover, +a.list-group-item-success:focus, +button.list-group-item-success:focus { + color: #3c763d; + background-color: #d0e9c6; +} +a.list-group-item-success.active, +button.list-group-item-success.active, +a.list-group-item-success.active:hover, +button.list-group-item-success.active:hover, +a.list-group-item-success.active:focus, +button.list-group-item-success.active:focus { + color: #fff; + background-color: #3c763d; + border-color: #3c763d; +} +.list-group-item-info { + color: #31708f; + background-color: #d9edf7; +} +a.list-group-item-info, +button.list-group-item-info { + color: #31708f; +} +a.list-group-item-info .list-group-item-heading, +button.list-group-item-info .list-group-item-heading { + color: inherit; +} +a.list-group-item-info:hover, +button.list-group-item-info:hover, +a.list-group-item-info:focus, +button.list-group-item-info:focus { + color: #31708f; + background-color: #c4e3f3; +} +a.list-group-item-info.active, +button.list-group-item-info.active, +a.list-group-item-info.active:hover, +button.list-group-item-info.active:hover, +a.list-group-item-info.active:focus, +button.list-group-item-info.active:focus { + color: #fff; + background-color: #31708f; + border-color: #31708f; +} +.list-group-item-warning { + color: #8a6d3b; + background-color: #fcf8e3; +} +a.list-group-item-warning, +button.list-group-item-warning { + color: #8a6d3b; +} +a.list-group-item-warning .list-group-item-heading, +button.list-group-item-warning .list-group-item-heading { + color: inherit; +} +a.list-group-item-warning:hover, +button.list-group-item-warning:hover, +a.list-group-item-warning:focus, +button.list-group-item-warning:focus { + color: #8a6d3b; + background-color: #faf2cc; +} +a.list-group-item-warning.active, +button.list-group-item-warning.active, +a.list-group-item-warning.active:hover, +button.list-group-item-warning.active:hover, +a.list-group-item-warning.active:focus, +button.list-group-item-warning.active:focus { + color: #fff; + background-color: #8a6d3b; + border-color: #8a6d3b; +} +.list-group-item-danger { + color: #a94442; + background-color: #f2dede; +} +a.list-group-item-danger, +button.list-group-item-danger { + color: #a94442; +} +a.list-group-item-danger .list-group-item-heading, +button.list-group-item-danger .list-group-item-heading { + color: inherit; +} +a.list-group-item-danger:hover, +button.list-group-item-danger:hover, +a.list-group-item-danger:focus, +button.list-group-item-danger:focus { + color: #a94442; + background-color: #ebcccc; +} +a.list-group-item-danger.active, +button.list-group-item-danger.active, +a.list-group-item-danger.active:hover, +button.list-group-item-danger.active:hover, +a.list-group-item-danger.active:focus, +button.list-group-item-danger.active:focus { + color: #fff; + background-color: #a94442; + border-color: #a94442; +} +.list-group-item-heading { + margin-top: 0; + margin-bottom: 5px; +} +.list-group-item-text { + margin-bottom: 0; + line-height: 1.3; +} +.panel { + margin-bottom: 20px; + background-color: #fff; + border: 1px solid transparent; + border-radius: 4px; + -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .05); + box-shadow: 0 1px 1px rgba(0, 0, 0, .05); +} +.panel-body { + padding: 15px; +} +.panel-heading { + padding: 10px 15px; + border-bottom: 1px solid transparent; + border-top-left-radius: 3px; + border-top-right-radius: 3px; +} +.panel-heading > .dropdown .dropdown-toggle { + color: inherit; +} +.panel-title { + margin-top: 0; + margin-bottom: 0; + font-size: 16px; + color: inherit; +} +.panel-title > a, +.panel-title > small, +.panel-title > .small, +.panel-title > small > a, +.panel-title > .small > a { + color: inherit; +} +.panel-footer { + padding: 10px 15px; + background-color: #f5f5f5; + border-top: 1px solid #ddd; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; +} +.panel > .list-group, +.panel > .panel-collapse > .list-group { + margin-bottom: 0; +} +.panel > .list-group .list-group-item, +.panel > .panel-collapse > .list-group .list-group-item { + border-width: 1px 0; + border-radius: 0; +} +.panel > .list-group:first-child .list-group-item:first-child, +.panel > .panel-collapse > .list-group:first-child .list-group-item:first-child { + border-top: 0; + border-top-left-radius: 3px; + border-top-right-radius: 3px; +} +.panel > .list-group:last-child .list-group-item:last-child, +.panel > .panel-collapse > .list-group:last-child .list-group-item:last-child { + border-bottom: 0; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; +} +.panel > .panel-heading + .panel-collapse > .list-group .list-group-item:first-child { + border-top-left-radius: 0; + border-top-right-radius: 0; +} +.panel-heading + .list-group .list-group-item:first-child { + border-top-width: 0; +} +.list-group + .panel-footer { + border-top-width: 0; +} +.panel > .table, +.panel > .table-responsive > .table, +.panel > .panel-collapse > .table { + margin-bottom: 0; +} +.panel > .table caption, +.panel > .table-responsive > .table caption, +.panel > .panel-collapse > .table caption { + padding-right: 15px; + padding-left: 15px; +} +.panel > .table:first-child, +.panel > .table-responsive:first-child > .table:first-child { + border-top-left-radius: 3px; + border-top-right-radius: 3px; +} +.panel > .table:first-child > thead:first-child > tr:first-child, +.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child, +.panel > .table:first-child > tbody:first-child > tr:first-child, +.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child { + border-top-left-radius: 3px; + border-top-right-radius: 3px; +} +.panel > .table:first-child > thead:first-child > tr:first-child td:first-child, +.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child, +.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child, +.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child, +.panel > .table:first-child > thead:first-child > tr:first-child th:first-child, +.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child, +.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child, +.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child { + border-top-left-radius: 3px; +} +.panel > .table:first-child > thead:first-child > tr:first-child td:last-child, +.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child, +.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child, +.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child, +.panel > .table:first-child > thead:first-child > tr:first-child th:last-child, +.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child, +.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child, +.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child { + border-top-right-radius: 3px; +} +.panel > .table:last-child, +.panel > .table-responsive:last-child > .table:last-child { + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; +} +.panel > .table:last-child > tbody:last-child > tr:last-child, +.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child, +.panel > .table:last-child > tfoot:last-child > tr:last-child, +.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child { + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; +} +.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child, +.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child, +.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child, +.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child, +.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child, +.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child, +.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child, +.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child { + border-bottom-left-radius: 3px; +} +.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child, +.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child, +.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child, +.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child, +.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child, +.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child, +.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child, +.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child { + border-bottom-right-radius: 3px; +} +.panel > .panel-body + .table, +.panel > .panel-body + .table-responsive, +.panel > .table + .panel-body, +.panel > .table-responsive + .panel-body { + border-top: 1px solid #ddd; +} +.panel > .table > tbody:first-child > tr:first-child th, +.panel > .table > tbody:first-child > tr:first-child td { + border-top: 0; +} +.panel > .table-bordered, +.panel > .table-responsive > .table-bordered { + border: 0; +} +.panel > .table-bordered > thead > tr > th:first-child, +.panel > .table-responsive > .table-bordered > thead > tr > th:first-child, +.panel > .table-bordered > tbody > tr > th:first-child, +.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child, +.panel > .table-bordered > tfoot > tr > th:first-child, +.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child, +.panel > .table-bordered > thead > tr > td:first-child, +.panel > .table-responsive > .table-bordered > thead > tr > td:first-child, +.panel > .table-bordered > tbody > tr > td:first-child, +.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child, +.panel > .table-bordered > tfoot > tr > td:first-child, +.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child { + border-left: 0; +} +.panel > .table-bordered > thead > tr > th:last-child, +.panel > .table-responsive > .table-bordered > thead > tr > th:last-child, +.panel > .table-bordered > tbody > tr > th:last-child, +.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child, +.panel > .table-bordered > tfoot > tr > th:last-child, +.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child, +.panel > .table-bordered > thead > tr > td:last-child, +.panel > .table-responsive > .table-bordered > thead > tr > td:last-child, +.panel > .table-bordered > tbody > tr > td:last-child, +.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child, +.panel > .table-bordered > tfoot > tr > td:last-child, +.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child { + border-right: 0; +} +.panel > .table-bordered > thead > tr:first-child > td, +.panel > .table-responsive > .table-bordered > thead > tr:first-child > td, +.panel > .table-bordered > tbody > tr:first-child > td, +.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td, +.panel > .table-bordered > thead > tr:first-child > th, +.panel > .table-responsive > .table-bordered > thead > tr:first-child > th, +.panel > .table-bordered > tbody > tr:first-child > th, +.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th { + border-bottom: 0; +} +.panel > .table-bordered > tbody > tr:last-child > td, +.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td, +.panel > .table-bordered > tfoot > tr:last-child > td, +.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td, +.panel > .table-bordered > tbody > tr:last-child > th, +.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th, +.panel > .table-bordered > tfoot > tr:last-child > th, +.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th { + border-bottom: 0; +} +.panel > .table-responsive { + margin-bottom: 0; + border: 0; +} +.panel-group { + margin-bottom: 20px; +} +.panel-group .panel { + margin-bottom: 0; + border-radius: 4px; +} +.panel-group .panel + .panel { + margin-top: 5px; +} +.panel-group .panel-heading { + border-bottom: 0; +} +.panel-group .panel-heading + .panel-collapse > .panel-body, +.panel-group .panel-heading + .panel-collapse > .list-group { + border-top: 1px solid #ddd; +} +.panel-group .panel-footer { + border-top: 0; +} +.panel-group .panel-footer + .panel-collapse .panel-body { + border-bottom: 1px solid #ddd; +} +.panel-default { + border-color: #ddd; +} +.panel-default > .panel-heading { + color: #333; + background-color: #f5f5f5; + border-color: #ddd; +} +.panel-default > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #ddd; +} +.panel-default > .panel-heading .badge { + color: #f5f5f5; + background-color: #333; +} +.panel-default > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #ddd; +} +.panel-primary { + border-color: #337ab7; +} +.panel-primary > .panel-heading { + color: #fff; + background-color: #337ab7; + border-color: #337ab7; +} +.panel-primary > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #337ab7; +} +.panel-primary > .panel-heading .badge { + color: #337ab7; + background-color: #fff; +} +.panel-primary > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #337ab7; +} +.panel-success { + border-color: #d6e9c6; +} +.panel-success > .panel-heading { + color: #3c763d; + background-color: #dff0d8; + border-color: #d6e9c6; +} +.panel-success > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #d6e9c6; +} +.panel-success > .panel-heading .badge { + color: #dff0d8; + background-color: #3c763d; +} +.panel-success > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #d6e9c6; +} +.panel-info { + border-color: #bce8f1; +} +.panel-info > .panel-heading { + color: #31708f; + background-color: #d9edf7; + border-color: #bce8f1; +} +.panel-info > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #bce8f1; +} +.panel-info > .panel-heading .badge { + color: #d9edf7; + background-color: #31708f; +} +.panel-info > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #bce8f1; +} +.panel-warning { + border-color: #faebcc; +} +.panel-warning > .panel-heading { + color: #8a6d3b; + background-color: #fcf8e3; + border-color: #faebcc; +} +.panel-warning > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #faebcc; +} +.panel-warning > .panel-heading .badge { + color: #fcf8e3; + background-color: #8a6d3b; +} +.panel-warning > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #faebcc; +} +.panel-danger { + border-color: #ebccd1; +} +.panel-danger > .panel-heading { + color: #a94442; + background-color: #f2dede; + border-color: #ebccd1; +} +.panel-danger > .panel-heading + .panel-collapse > .panel-body { + border-top-color: #ebccd1; +} +.panel-danger > .panel-heading .badge { + color: #f2dede; + background-color: #a94442; +} +.panel-danger > .panel-footer + .panel-collapse > .panel-body { + border-bottom-color: #ebccd1; +} +.embed-responsive { + position: relative; + display: block; + height: 0; + padding: 0; + overflow: hidden; +} +.embed-responsive .embed-responsive-item, +.embed-responsive iframe, +.embed-responsive embed, +.embed-responsive object, +.embed-responsive video { + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 100%; + height: 100%; + border: 0; +} +.embed-responsive-16by9 { + padding-bottom: 56.25%; +} +.embed-responsive-4by3 { + padding-bottom: 75%; +} +.well { + min-height: 20px; + padding: 19px; + margin-bottom: 20px; + background-color: #f5f5f5; + border: 1px solid #e3e3e3; + border-radius: 4px; + -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); + box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05); +} +.well blockquote { + border-color: #ddd; + border-color: rgba(0, 0, 0, .15); +} +.well-lg { + padding: 24px; + border-radius: 6px; +} +.well-sm { + padding: 9px; + border-radius: 3px; +} +.close { + float: right; + font-size: 21px; + font-weight: bold; + line-height: 1; + color: #000; + text-shadow: 0 1px 0 #fff; + filter: alpha(opacity=20); + opacity: .2; +} +.close:hover, +.close:focus { + color: #000; + text-decoration: none; + cursor: pointer; + filter: alpha(opacity=50); + opacity: .5; +} +button.close { + -webkit-appearance: none; + padding: 0; + cursor: pointer; + background: transparent; + border: 0; +} +.modal-open { + overflow: hidden; +} +.modal { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1050; + display: none; + overflow: hidden; + -webkit-overflow-scrolling: touch; + outline: 0; +} +.modal.fade .modal-dialog { + -webkit-transition: -webkit-transform .3s ease-out; + -o-transition: -o-transform .3s ease-out; + transition: transform .3s ease-out; + -webkit-transform: translate(0, -25%); + -ms-transform: translate(0, -25%); + -o-transform: translate(0, -25%); + transform: translate(0, -25%); +} +.modal.in .modal-dialog { + -webkit-transform: translate(0, 0); + -ms-transform: translate(0, 0); + -o-transform: translate(0, 0); + transform: translate(0, 0); +} +.modal-open .modal { + overflow-x: hidden; + overflow-y: auto; +} +.modal-dialog { + position: relative; + width: auto; + margin: 10px; +} +.modal-content { + position: relative; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #999; + border: 1px solid rgba(0, 0, 0, .2); + border-radius: 6px; + outline: 0; + -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, .5); + box-shadow: 0 3px 9px rgba(0, 0, 0, .5); +} +.modal-backdrop { + position: fixed; + top: 0; + right: 0; + bottom: 0; + left: 0; + z-index: 1040; + background-color: #000; +} +.modal-backdrop.fade { + filter: alpha(opacity=0); + opacity: 0; +} +.modal-backdrop.in { + filter: alpha(opacity=50); + opacity: .5; +} +.modal-header { + padding: 15px; + border-bottom: 1px solid #e5e5e5; +} +.modal-header .close { + margin-top: -2px; +} +.modal-title { + margin: 0; + line-height: 1.42857143; +} +.modal-body { + position: relative; + padding: 15px; +} +.modal-footer { + padding: 15px; + text-align: right; + border-top: 1px solid #e5e5e5; +} +.modal-footer .btn + .btn { + margin-bottom: 0; + margin-left: 5px; +} +.modal-footer .btn-group .btn + .btn { + margin-left: -1px; +} +.modal-footer .btn-block + .btn-block { + margin-left: 0; +} +.modal-scrollbar-measure { + position: absolute; + top: -9999px; + width: 50px; + height: 50px; + overflow: scroll; +} +@media (min-width: 768px) { + .modal-dialog { + width: 600px; + margin: 30px auto; + } + .modal-content { + -webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, .5); + box-shadow: 0 5px 15px rgba(0, 0, 0, .5); + } + .modal-sm { + width: 300px; + } +} +@media (min-width: 992px) { + .modal-lg { + width: 900px; + } +} +.tooltip { + position: absolute; + z-index: 1070; + display: block; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 12px; + font-style: normal; + font-weight: normal; + line-height: 1.42857143; + text-align: left; + text-align: start; + text-decoration: none; + text-shadow: none; + text-transform: none; + letter-spacing: normal; + word-break: normal; + word-spacing: normal; + word-wrap: normal; + white-space: normal; + filter: alpha(opacity=0); + opacity: 0; + + line-break: auto; +} +.tooltip.in { + filter: alpha(opacity=90); + opacity: .9; +} +.tooltip.top { + padding: 5px 0; + margin-top: -3px; +} +.tooltip.right { + padding: 0 5px; + margin-left: 3px; +} +.tooltip.bottom { + padding: 5px 0; + margin-top: 3px; +} +.tooltip.left { + padding: 0 5px; + margin-left: -3px; +} +.tooltip-inner { + max-width: 200px; + padding: 3px 8px; + color: #fff; + text-align: center; + background-color: #000; + border-radius: 4px; +} +.tooltip-arrow { + position: absolute; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.tooltip.top .tooltip-arrow { + bottom: 0; + left: 50%; + margin-left: -5px; + border-width: 5px 5px 0; + border-top-color: #000; +} +.tooltip.top-left .tooltip-arrow { + right: 5px; + bottom: 0; + margin-bottom: -5px; + border-width: 5px 5px 0; + border-top-color: #000; +} +.tooltip.top-right .tooltip-arrow { + bottom: 0; + left: 5px; + margin-bottom: -5px; + border-width: 5px 5px 0; + border-top-color: #000; +} +.tooltip.right .tooltip-arrow { + top: 50%; + left: 0; + margin-top: -5px; + border-width: 5px 5px 5px 0; + border-right-color: #000; +} +.tooltip.left .tooltip-arrow { + top: 50%; + right: 0; + margin-top: -5px; + border-width: 5px 0 5px 5px; + border-left-color: #000; +} +.tooltip.bottom .tooltip-arrow { + top: 0; + left: 50%; + margin-left: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; +} +.tooltip.bottom-left .tooltip-arrow { + top: 0; + right: 5px; + margin-top: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; +} +.tooltip.bottom-right .tooltip-arrow { + top: 0; + left: 5px; + margin-top: -5px; + border-width: 0 5px 5px; + border-bottom-color: #000; +} +.popover { + position: absolute; + top: 0; + left: 0; + z-index: 1060; + display: none; + max-width: 276px; + padding: 1px; + font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + font-style: normal; + font-weight: normal; + line-height: 1.42857143; + text-align: left; + text-align: start; + text-decoration: none; + text-shadow: none; + text-transform: none; + letter-spacing: normal; + word-break: normal; + word-spacing: normal; + word-wrap: normal; + white-space: normal; + background-color: #fff; + -webkit-background-clip: padding-box; + background-clip: padding-box; + border: 1px solid #ccc; + border: 1px solid rgba(0, 0, 0, .2); + border-radius: 6px; + -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, .2); + box-shadow: 0 5px 10px rgba(0, 0, 0, .2); + + line-break: auto; +} +.popover.top { + margin-top: -10px; +} +.popover.right { + margin-left: 10px; +} +.popover.bottom { + margin-top: 10px; +} +.popover.left { + margin-left: -10px; +} +.popover-title { + padding: 8px 14px; + margin: 0; + font-size: 14px; + background-color: #f7f7f7; + border-bottom: 1px solid #ebebeb; + border-radius: 5px 5px 0 0; +} +.popover-content { + padding: 9px 14px; +} +.popover > .arrow, +.popover > .arrow:after { + position: absolute; + display: block; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; +} +.popover > .arrow { + border-width: 11px; +} +.popover > .arrow:after { + content: ""; + border-width: 10px; +} +.popover.top > .arrow { + bottom: -11px; + left: 50%; + margin-left: -11px; + border-top-color: #999; + border-top-color: rgba(0, 0, 0, .25); + border-bottom-width: 0; +} +.popover.top > .arrow:after { + bottom: 1px; + margin-left: -10px; + content: " "; + border-top-color: #fff; + border-bottom-width: 0; +} +.popover.right > .arrow { + top: 50%; + left: -11px; + margin-top: -11px; + border-right-color: #999; + border-right-color: rgba(0, 0, 0, .25); + border-left-width: 0; +} +.popover.right > .arrow:after { + bottom: -10px; + left: 1px; + content: " "; + border-right-color: #fff; + border-left-width: 0; +} +.popover.bottom > .arrow { + top: -11px; + left: 50%; + margin-left: -11px; + border-top-width: 0; + border-bottom-color: #999; + border-bottom-color: rgba(0, 0, 0, .25); +} +.popover.bottom > .arrow:after { + top: 1px; + margin-left: -10px; + content: " "; + border-top-width: 0; + border-bottom-color: #fff; +} +.popover.left > .arrow { + top: 50%; + right: -11px; + margin-top: -11px; + border-right-width: 0; + border-left-color: #999; + border-left-color: rgba(0, 0, 0, .25); +} +.popover.left > .arrow:after { + right: 1px; + bottom: -10px; + content: " "; + border-right-width: 0; + border-left-color: #fff; +} +.carousel { + position: relative; +} +.carousel-inner { + position: relative; + width: 100%; + overflow: hidden; +} +.carousel-inner > .item { + position: relative; + display: none; + -webkit-transition: .6s ease-in-out left; + -o-transition: .6s ease-in-out left; + transition: .6s ease-in-out left; +} +.carousel-inner > .item > img, +.carousel-inner > .item > a > img { + line-height: 1; +} +@media all and (transform-3d), (-webkit-transform-3d) { + .carousel-inner > .item { + -webkit-transition: -webkit-transform .6s ease-in-out; + -o-transition: -o-transform .6s ease-in-out; + transition: transform .6s ease-in-out; + + -webkit-backface-visibility: hidden; + backface-visibility: hidden; + -webkit-perspective: 1000px; + perspective: 1000px; + } + .carousel-inner > .item.next, + .carousel-inner > .item.active.right { + left: 0; + -webkit-transform: translate3d(100%, 0, 0); + transform: translate3d(100%, 0, 0); + } + .carousel-inner > .item.prev, + .carousel-inner > .item.active.left { + left: 0; + -webkit-transform: translate3d(-100%, 0, 0); + transform: translate3d(-100%, 0, 0); + } + .carousel-inner > .item.next.left, + .carousel-inner > .item.prev.right, + .carousel-inner > .item.active { + left: 0; + -webkit-transform: translate3d(0, 0, 0); + transform: translate3d(0, 0, 0); + } +} +.carousel-inner > .active, +.carousel-inner > .next, +.carousel-inner > .prev { + display: block; +} +.carousel-inner > .active { + left: 0; +} +.carousel-inner > .next, +.carousel-inner > .prev { + position: absolute; + top: 0; + width: 100%; +} +.carousel-inner > .next { + left: 100%; +} +.carousel-inner > .prev { + left: -100%; +} +.carousel-inner > .next.left, +.carousel-inner > .prev.right { + left: 0; +} +.carousel-inner > .active.left { + left: -100%; +} +.carousel-inner > .active.right { + left: 100%; +} +.carousel-control { + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: 15%; + font-size: 20px; + color: #fff; + text-align: center; + text-shadow: 0 1px 2px rgba(0, 0, 0, .6); + background-color: rgba(0, 0, 0, 0); + filter: alpha(opacity=50); + opacity: .5; +} +.carousel-control.left { + background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001))); + background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1); + background-repeat: repeat-x; +} +.carousel-control.right { + right: 0; + left: auto; + background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5))); + background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%); + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1); + background-repeat: repeat-x; +} +.carousel-control:hover, +.carousel-control:focus { + color: #fff; + text-decoration: none; + filter: alpha(opacity=90); + outline: 0; + opacity: .9; +} +.carousel-control .icon-prev, +.carousel-control .icon-next, +.carousel-control .glyphicon-chevron-left, +.carousel-control .glyphicon-chevron-right { + position: absolute; + top: 50%; + z-index: 5; + display: inline-block; + margin-top: -10px; +} +.carousel-control .icon-prev, +.carousel-control .glyphicon-chevron-left { + left: 50%; + margin-left: -10px; +} +.carousel-control .icon-next, +.carousel-control .glyphicon-chevron-right { + right: 50%; + margin-right: -10px; +} +.carousel-control .icon-prev, +.carousel-control .icon-next { + width: 20px; + height: 20px; + font-family: serif; + line-height: 1; +} +.carousel-control .icon-prev:before { + content: '\2039'; +} +.carousel-control .icon-next:before { + content: '\203a'; +} +.carousel-indicators { + position: absolute; + bottom: 10px; + left: 50%; + z-index: 15; + width: 60%; + padding-left: 0; + margin-left: -30%; + text-align: center; + list-style: none; +} +.carousel-indicators li { + display: inline-block; + width: 10px; + height: 10px; + margin: 1px; + text-indent: -999px; + cursor: pointer; + background-color: #000 \9; + background-color: rgba(0, 0, 0, 0); + border: 1px solid #fff; + border-radius: 10px; +} +.carousel-indicators .active { + width: 12px; + height: 12px; + margin: 0; + background-color: #fff; +} +.carousel-caption { + position: absolute; + right: 15%; + bottom: 20px; + left: 15%; + z-index: 10; + padding-top: 20px; + padding-bottom: 20px; + color: #fff; + text-align: center; + text-shadow: 0 1px 2px rgba(0, 0, 0, .6); +} +.carousel-caption .btn { + text-shadow: none; +} +@media screen and (min-width: 768px) { + .carousel-control .glyphicon-chevron-left, + .carousel-control .glyphicon-chevron-right, + .carousel-control .icon-prev, + .carousel-control .icon-next { + width: 30px; + height: 30px; + margin-top: -10px; + font-size: 30px; + } + .carousel-control .glyphicon-chevron-left, + .carousel-control .icon-prev { + margin-left: -10px; + } + .carousel-control .glyphicon-chevron-right, + .carousel-control .icon-next { + margin-right: -10px; + } + .carousel-caption { + right: 20%; + left: 20%; + padding-bottom: 30px; + } + .carousel-indicators { + bottom: 20px; + } +} +.clearfix:before, +.clearfix:after, +.dl-horizontal dd:before, +.dl-horizontal dd:after, +.container:before, +.container:after, +.container-fluid:before, +.container-fluid:after, +.row:before, +.row:after, +.form-horizontal .form-group:before, +.form-horizontal .form-group:after, +.btn-toolbar:before, +.btn-toolbar:after, +.btn-group-vertical > .btn-group:before, +.btn-group-vertical > .btn-group:after, +.nav:before, +.nav:after, +.navbar:before, +.navbar:after, +.navbar-header:before, +.navbar-header:after, +.navbar-collapse:before, +.navbar-collapse:after, +.pager:before, +.pager:after, +.panel-body:before, +.panel-body:after, +.modal-header:before, +.modal-header:after, +.modal-footer:before, +.modal-footer:after { + display: table; + content: " "; +} +.clearfix:after, +.dl-horizontal dd:after, +.container:after, +.container-fluid:after, +.row:after, +.form-horizontal .form-group:after, +.btn-toolbar:after, +.btn-group-vertical > .btn-group:after, +.nav:after, +.navbar:after, +.navbar-header:after, +.navbar-collapse:after, +.pager:after, +.panel-body:after, +.modal-header:after, +.modal-footer:after { + clear: both; +} +.center-block { + display: block; + margin-right: auto; + margin-left: auto; +} +.pull-right { + float: right !important; +} +.pull-left { + float: left !important; +} +.hide { + display: none !important; +} +.show { + display: block !important; +} +.invisible { + visibility: hidden; +} +.text-hide { + font: 0/0 a; + color: transparent; + text-shadow: none; + background-color: transparent; + border: 0; +} +.hidden { + display: none !important; +} +.affix { + position: fixed; +} +@-ms-viewport { + width: device-width; +} +.visible-xs, +.visible-sm, +.visible-md, +.visible-lg { + display: none !important; +} +.visible-xs-block, +.visible-xs-inline, +.visible-xs-inline-block, +.visible-sm-block, +.visible-sm-inline, +.visible-sm-inline-block, +.visible-md-block, +.visible-md-inline, +.visible-md-inline-block, +.visible-lg-block, +.visible-lg-inline, +.visible-lg-inline-block { + display: none !important; +} +@media (max-width: 767px) { + .visible-xs { + display: block !important; + } + table.visible-xs { + display: table !important; + } + tr.visible-xs { + display: table-row !important; + } + th.visible-xs, + td.visible-xs { + display: table-cell !important; + } +} +@media (max-width: 767px) { + .visible-xs-block { + display: block !important; + } +} +@media (max-width: 767px) { + .visible-xs-inline { + display: inline !important; + } +} +@media (max-width: 767px) { + .visible-xs-inline-block { + display: inline-block !important; + } +} +@media (min-width: 768px) and (max-width: 991px) { + .visible-sm { + display: block !important; + } + table.visible-sm { + display: table !important; + } + tr.visible-sm { + display: table-row !important; + } + th.visible-sm, + td.visible-sm { + display: table-cell !important; + } +} +@media (min-width: 768px) and (max-width: 991px) { + .visible-sm-block { + display: block !important; + } +} +@media (min-width: 768px) and (max-width: 991px) { + .visible-sm-inline { + display: inline !important; + } +} +@media (min-width: 768px) and (max-width: 991px) { + .visible-sm-inline-block { + display: inline-block !important; + } +} +@media (min-width: 992px) and (max-width: 1199px) { + .visible-md { + display: block !important; + } + table.visible-md { + display: table !important; + } + tr.visible-md { + display: table-row !important; + } + th.visible-md, + td.visible-md { + display: table-cell !important; + } +} +@media (min-width: 992px) and (max-width: 1199px) { + .visible-md-block { + display: block !important; + } +} +@media (min-width: 992px) and (max-width: 1199px) { + .visible-md-inline { + display: inline !important; + } +} +@media (min-width: 992px) and (max-width: 1199px) { + .visible-md-inline-block { + display: inline-block !important; + } +} +@media (min-width: 1200px) { + .visible-lg { + display: block !important; + } + table.visible-lg { + display: table !important; + } + tr.visible-lg { + display: table-row !important; + } + th.visible-lg, + td.visible-lg { + display: table-cell !important; + } +} +@media (min-width: 1200px) { + .visible-lg-block { + display: block !important; + } +} +@media (min-width: 1200px) { + .visible-lg-inline { + display: inline !important; + } +} +@media (min-width: 1200px) { + .visible-lg-inline-block { + display: inline-block !important; + } +} +@media (max-width: 767px) { + .hidden-xs { + display: none !important; + } +} +@media (min-width: 768px) and (max-width: 991px) { + .hidden-sm { + display: none !important; + } +} +@media (min-width: 992px) and (max-width: 1199px) { + .hidden-md { + display: none !important; + } +} +@media (min-width: 1200px) { + .hidden-lg { + display: none !important; + } +} +.visible-print { + display: none !important; +} +@media print { + .visible-print { + display: block !important; + } + table.visible-print { + display: table !important; + } + tr.visible-print { + display: table-row !important; + } + th.visible-print, + td.visible-print { + display: table-cell !important; + } +} +.visible-print-block { + display: none !important; +} +@media print { + .visible-print-block { + display: block !important; + } +} +.visible-print-inline { + display: none !important; +} +@media print { + .visible-print-inline { + display: inline !important; + } +} +.visible-print-inline-block { + display: none !important; +} +@media print { + .visible-print-inline-block { + display: inline-block !important; + } +} +@media print { + .hidden-print { + display: none !important; + } +} +/*# sourceMappingURL=bootstrap.css.map */ diff --git a/test_app/app/css/main.css b/test_app/app/css/main.css new file mode 100644 index 00000000..abfcd67f --- /dev/null +++ b/test_app/app/css/main.css @@ -0,0 +1,26 @@ + +div { + margin: 15px; +} + +.logs { + background-color: black; + font-size: 14px; + color: white; + font-weight: bold; + padding: 10px; + border-radius: 8px; +} + +.tab-content { + border-left: 1px solid #ddd; + border-right: 1px solid #ddd; + border-bottom: 1px solid #ddd; + padding: 10px; + margin: 0px; +} + +.nav-tabs { + margin-bottom: 0; +} + diff --git a/test_app/app/images/.gitkeep b/test_app/app/images/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/test_app/app/index.html b/test_app/app/index.html new file mode 100644 index 00000000..417f6096 --- /dev/null +++ b/test_app/app/index.html @@ -0,0 +1,105 @@ + + + Embark - SimpleStorage Demo + + + + +

Embark - Usage Example

+ + + +
+
+

1. Set the value in the blockchain

+
+ + +

Once you set the value, the transaction will need to be mined and then the value will be updated on the blockchain.

+
+ +

2. Get the current value

+
+
+ current value is +
+ +

Click the button to get the current value. The initial value is 100.

+
+ +

3. Contract Calls

+

Javascript calls being made:

+
+
+
+
+ note: You need to have an IPFS node running + +

Save text to IPFS

+
+ + +

generated Hash:

+
+ +

Load text from IPFS given an hash

+
+ + +

result:

+
+ +

upload file to ipfs

+
+ + +

generated hash:

+
+ +

Get file or image from ipfs

+
+ + +

file available at:

+

+
+ +

Javascript calls being made:

+
+
EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'}) +
+ +
+
+ The node you are using does not support whisper + +

Listen To channel

+
+ + +
+

messages received:

+

+
+ +

Send Message

+
+ + + +
+ +

Javascript calls being made:

+
+
EmbarkJS.Messages.setProvider('whisper') +
+ +
+
+ + + diff --git a/test_app/app/js/.gitkeep b/test_app/app/js/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/test_app/app/js/_vendor/async.min.js b/test_app/app/js/_vendor/async.min.js new file mode 100644 index 00000000..f0697dea --- /dev/null +++ b/test_app/app/js/_vendor/async.min.js @@ -0,0 +1,2 @@ +!function(n,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(n.async=n.async||{})}(this,function(n){"use strict";function t(n,t,e){switch(e.length){case 0:return n.call(t);case 1:return n.call(t,e[0]);case 2:return n.call(t,e[0],e[1]);case 3:return n.call(t,e[0],e[1],e[2])}return n.apply(t,e)}function e(n,e,r){return e=rt(void 0===e?n.length-1:e,0),function(){for(var u=arguments,o=-1,i=rt(u.length-e,0),c=Array(i);++o-1&&n%1==0&&n<=kt}function p(n){return null!=n&&s(n.length)&&!l(n)}function h(){}function y(n){return function(){if(null!==n){var t=n;n=null,t.apply(this,arguments)}}}function v(n,t){for(var e=-1,r=Array(n);++e-1&&n%1==0&&nu?0:u+t),e=e>u?u:e,e<0&&(e+=u),u=t>e?0:e-t>>>0,t>>>=0;for(var o=Array(u);++r=r?n:K(n,t,e)}function Y(n,t){for(var e=n.length;e--&&Q(t,n[e],0)>-1;);return e}function Z(n,t){for(var e=-1,r=n.length;++e-1;);return e}function nn(n){return n.split("")}function tn(n){return We.test(n)}function en(n){return n.match(fr)||[]}function rn(n){return tn(n)?en(n):nn(n)}function un(n){return null==n?"":J(n)}function on(n,t,e){if(n=un(n),n&&(e||void 0===t))return n.replace(ar,"");if(!n||!(t=J(t)))return n;var r=rn(n),u=rn(t),o=Z(r,u),i=Y(r,u)+1;return X(r,o,i).join("")}function cn(n){return n=n.toString().replace(hr,""),n=n.match(lr)[2].replace(" ",""),n=n?n.split(sr):[],n=n.map(function(n){return on(n.replace(pr,""))})}function fn(n,t){var e={};C(n,function(n,t){function r(t,e){var r=G(u,function(n){return t[n]});r.push(e),n.apply(null,r)}var u;if(Ft(n))u=n.slice(0,-1),n=n[n.length-1],e[t]=u.concat(u.length>0?r:n);else if(1===n.length)e[t]=n;else{if(u=cn(n),0===n.length&&0===u.length)throw new Error("autoInject task functions require explicit parameters.");u.pop(),e[t]=u.concat(r)}}),Me(e,t)}function an(n){setTimeout(n,0)}function ln(n){return u(function(t,e){n(function(){t.apply(null,e)})})}function sn(){this.head=this.tail=null,this.length=0}function pn(n,t){n.length=1,n.head=n.tail=t}function hn(n,t,e){function r(n,t,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");if(f.started=!0,Ft(n)||(n=[n]),0===n.length&&f.idle())return dr(function(){f.drain()});for(var r=0,u=n.length;r=0&&c.splice(o),u.callback.apply(u,t),null!=t[0]&&f.error(t[0],u.data)}i<=f.concurrency-f.buffer&&f.unsaturated(),f.idle()&&f.drain(),f.process()})}if(null==t)t=1;else if(0===t)throw new Error("Concurrency must not be zero");var i=0,c=[],f={_tasks:new sn,concurrency:t,payload:e,saturated:h,unsaturated:h,buffer:t/4,empty:h,drain:h,error:h,started:!1,paused:!1,push:function(n,t){r(n,!1,t)},kill:function(){f.drain=h,f._tasks.empty()},unshift:function(n,t){r(n,!0,t)},process:function(){for(;!f.paused&&i3?(i=i||h,n(r,u,f,c)):(i=o,i=i||h,o=u,n(r,f,c))}}function bn(n,t){return t}function jn(n){return u(function(t,e){t.apply(null,e.concat([u(function(t,e){"object"==typeof console&&(t?console.error&&console.error(t):console[n]&&D(e,function(t){console[n](t)}))})]))})}function Sn(n,t,e){function r(t,r){return t?e(t):r?void n(o):e(null)}e=I(e||h);var o=u(function(n,u){return n?e(n):(u.push(r),void t.apply(this,u))});r(null,!0)}function kn(n,t,e){e=I(e||h);var r=u(function(u,o){return u?e(u):t.apply(this,o)?n(r):void e.apply(null,[null].concat(o))});n(r)}function wn(n,t,e){kn(n,function(){return!t.apply(this,arguments)},e)}function xn(n,t,e){function r(t){return t?e(t):void n(u)}function u(n,u){return n?e(n):u?void t(r):e(null)}e=I(e||h),n(u)}function On(n){return function(t,e,r){return n(t,r)}}function En(n,t,e){Ee(n,On(t),e)}function Ln(n,t,e,r){_(t)(n,On(e),r)}function An(n){return ut(function(t,e){var r=!0;t.push(function(){var n=arguments;r?dr(function(){e.apply(null,n)}):e.apply(null,n)}),n.apply(this,t),r=!1})}function Tn(n){return!n}function Fn(n){return function(t){return null==t?void 0:t[n]}}function In(n,t,e,r){var u=new Array(t.length);n(t,function(n,t,r){e(n,function(n,e){u[t]=!!e,r(n)})},function(n){if(n)return r(n);for(var e=[],o=0;o1&&(r=t),e(null,{value:r})}})),n.apply(this,t)})}function Wn(n,t,e,r){Bn(n,t,function(n,t){e(n,function(n,e){t(n,!e)})},r)}function Nn(n){var t;return Ft(n)?t=G(n,$n):(t={},C(n,function(n,e){t[e]=$n.call(this,n)})),t}function Qn(n){return function(){return n}}function Gn(n,t,e){function r(n,t){if("object"==typeof t)n.times=+t.times||o,n.intervalFunc="function"==typeof t.interval?t.interval:Qn(+t.interval||i),n.errorFilter=t.errorFilter;else{if("number"!=typeof t&&"string"!=typeof t)throw new Error("Invalid arguments for async.retry");n.times=+t||o}}function u(){t(function(n){n&&f++r?1:0}Le(n,function(n,e){t(n,function(t,r){return t?e(t):void e(null,{value:n,criteria:r})})},function(n,t){return n?e(n):void e(null,G(t.sort(r),Fn("value")))})}function Kn(n,t,e){function r(){c||(o.apply(null,arguments),clearTimeout(i))}function u(){var t=n.name||"anonymous",r=new Error('Callback function "'+t+'" timed out.');r.code="ETIMEDOUT",e&&(r.info=e),c=!0,o(r)}var o,i,c=!1;return ut(function(e,c){o=c,i=setTimeout(u,t),n.apply(null,e.concat(r))})}function Xn(n,t,e,r){for(var u=-1,o=Kr(Jr((t-n)/(e||1)),0),i=Array(o);o--;)i[r?o:++u]=n,n+=e;return i}function Yn(n,t,e,r){Te(Xn(0,n,1),t,e,r)}function Zn(n,t,e,r){3===arguments.length&&(r=e,e=t,t=Ft(n)?[]:{}),r=y(r||h),Ee(n,function(n,r,u){e(t,n,r,u)},function(n){r(n,t)})}function nt(n){return function(){return(n.unmemoized||n).apply(null,arguments)}}function tt(n,t,e){if(e=I(e||h),!n())return e(null);var r=u(function(u,o){return u?e(u):n()?t(r):void e.apply(null,[null].concat(o))});t(r)}function et(n,t,e){tt(function(){return!n.apply(this,arguments)},t,e)}var rt=Math.max,ut=function(n){return u(function(t){var e=t.pop();n.call(this,t,e)})},ot="object"==typeof global&&global&&global.Object===Object&&global,it="object"==typeof self&&self&&self.Object===Object&&self,ct=ot||it||Function("return this")(),ft=ct.Symbol,at=Object.prototype,lt=at.hasOwnProperty,st=at.toString,pt=ft?ft.toStringTag:void 0,ht=Object.prototype,yt=ht.toString,vt="[object Null]",dt="[object Undefined]",mt=ft?ft.toStringTag:void 0,gt="[object AsyncFunction]",bt="[object Function]",jt="[object GeneratorFunction]",St="[object Proxy]",kt=9007199254740991,wt="function"==typeof Symbol&&Symbol.iterator,xt=function(n){return wt&&n[wt]&&n[wt]()},Ot="[object Arguments]",Et=Object.prototype,Lt=Et.hasOwnProperty,At=Et.propertyIsEnumerable,Tt=m(function(){return arguments}())?m:function(n){return d(n)&&Lt.call(n,"callee")&&!At.call(n,"callee")},Ft=Array.isArray,It="object"==typeof n&&n&&!n.nodeType&&n,_t=It&&"object"==typeof module&&module&&!module.nodeType&&module,Bt=_t&&_t.exports===It,Mt=Bt?ct.Buffer:void 0,Ut=Mt?Mt.isBuffer:void 0,zt=Ut||g,Vt=9007199254740991,Pt=/^(?:0|[1-9]\d*)$/,qt="[object Arguments]",Dt="[object Array]",Rt="[object Boolean]",Ct="[object Date]",$t="[object Error]",Wt="[object Function]",Nt="[object Map]",Qt="[object Number]",Gt="[object Object]",Ht="[object RegExp]",Jt="[object Set]",Kt="[object String]",Xt="[object WeakMap]",Yt="[object ArrayBuffer]",Zt="[object DataView]",ne="[object Float32Array]",te="[object Float64Array]",ee="[object Int8Array]",re="[object Int16Array]",ue="[object Int32Array]",oe="[object Uint8Array]",ie="[object Uint8ClampedArray]",ce="[object Uint16Array]",fe="[object Uint32Array]",ae={};ae[ne]=ae[te]=ae[ee]=ae[re]=ae[ue]=ae[oe]=ae[ie]=ae[ce]=ae[fe]=!0,ae[qt]=ae[Dt]=ae[Yt]=ae[Rt]=ae[Zt]=ae[Ct]=ae[$t]=ae[Wt]=ae[Nt]=ae[Qt]=ae[Gt]=ae[Ht]=ae[Jt]=ae[Kt]=ae[Xt]=!1;var le,se="object"==typeof n&&n&&!n.nodeType&&n,pe=se&&"object"==typeof module&&module&&!module.nodeType&&module,he=pe&&pe.exports===se,ye=he&&ot.process,ve=function(){try{return ye&&ye.binding("util")}catch(n){}}(),de=ve&&ve.isTypedArray,me=de?S(de):j,ge=Object.prototype,be=ge.hasOwnProperty,je=Object.prototype,Se=x(Object.keys,Object),ke=Object.prototype,we=ke.hasOwnProperty,xe={},Oe=M(B,1/0),Ee=function(n,t,e){var r=p(n)?U:Oe;r(n,t,e)},Le=z(V),Ae=o(Le),Te=P(V),Fe=M(Te,1),Ie=o(Fe),_e=u(function(n,t){return u(function(e){return n.apply(null,t.concat(e))})}),Be=R(),Me=function(n,t,e){function r(n,t){b.push(function(){f(n,t)})}function o(){if(0===b.length&&0===d)return e(null,v);for(;b.length&&d1?o(v,r):o(r)}}function a(){for(var n,t=0;j.length;)n=j.pop(),t++,D(l(n),function(n){0===--S[n]&&j.push(n)});if(t!==p)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function l(t){var e=[];return C(n,function(n,r){Ft(n)&&Q(n,t,0)>=0&&e.push(r)}),e}"function"==typeof t&&(e=t,t=null),e=y(e||h);var s=E(n),p=s.length;if(!p)return e(null);t||(t=p);var v={},d=0,m=!1,g={},b=[],j=[],S={};C(n,function(t,e){if(!Ft(t))return r(e,[t]),void j.push(e);var u=t.slice(0,t.length-1),o=u.length;return 0===o?(r(e,t),void j.push(e)):(S[e]=o,void D(u,function(c){if(!n[c])throw new Error("async.auto task `"+e+"` has a non-existent dependency in "+u.join(", "));i(c,function(){o--,0===o&&r(e,t)})}))}),a(),o()},Ue="[object Symbol]",ze=1/0,Ve=ft?ft.prototype:void 0,Pe=Ve?Ve.toString:void 0,qe="\\ud800-\\udfff",De="\\u0300-\\u036f\\ufe20-\\ufe23",Re="\\u20d0-\\u20f0",Ce="\\ufe0e\\ufe0f",$e="\\u200d",We=RegExp("["+$e+qe+De+Re+Ce+"]"),Ne="\\ud800-\\udfff",Qe="\\u0300-\\u036f\\ufe20-\\ufe23",Ge="\\u20d0-\\u20f0",He="\\ufe0e\\ufe0f",Je="["+Ne+"]",Ke="["+Qe+Ge+"]",Xe="\\ud83c[\\udffb-\\udfff]",Ye="(?:"+Ke+"|"+Xe+")",Ze="[^"+Ne+"]",nr="(?:\\ud83c[\\udde6-\\uddff]){2}",tr="[\\ud800-\\udbff][\\udc00-\\udfff]",er="\\u200d",rr=Ye+"?",ur="["+He+"]?",or="(?:"+er+"(?:"+[Ze,nr,tr].join("|")+")"+ur+rr+")*",ir=ur+rr+or,cr="(?:"+[Ze+Ke+"?",Ke,nr,tr,Je].join("|")+")",fr=RegExp(Xe+"(?="+Xe+")|"+cr+ir,"g"),ar=/^\s+|\s+$/g,lr=/^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,sr=/,/,pr=/(=.+)?(\s*)$/,hr=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,yr="function"==typeof setImmediate&&setImmediate,vr="object"==typeof process&&"function"==typeof process.nextTick;le=yr?setImmediate:vr?process.nextTick:an;var dr=ln(le);sn.prototype.removeLink=function(n){return n.prev?n.prev.next=n.next:this.head=n.next,n.next?n.next.prev=n.prev:this.tail=n.prev,n.prev=n.next=null,this.length-=1,n},sn.prototype.empty=sn,sn.prototype.insertAfter=function(n,t){t.prev=n,t.next=n.next,n.next?n.next.prev=t:this.tail=t,n.next=t,this.length+=1},sn.prototype.insertBefore=function(n,t){t.prev=n.prev,t.next=n,n.prev?n.prev.next=t:this.head=t,n.prev=t,this.length+=1},sn.prototype.unshift=function(n){this.head?this.insertBefore(this.head,n):pn(this,n)},sn.prototype.push=function(n){this.tail?this.insertAfter(this.tail,n):pn(this,n)},sn.prototype.shift=function(){return this.head&&this.removeLink(this.head)},sn.prototype.pop=function(){return this.tail&&this.removeLink(this.tail)};var mr,gr=M(B,1),br=u(function(n){return u(function(t){var e=this,r=t[t.length-1];"function"==typeof r?t.pop():r=h,vn(n,t,function(n,t,r){t.apply(e,n.concat([u(function(n,t){r(n,t)})]))},function(n,t){r.apply(e,[n].concat(t))})})}),jr=u(function(n){return br.apply(null,n.reverse())}),Sr=z(dn),kr=mn(dn),wr=u(function(n){var t=[null].concat(n);return ut(function(n,e){return e.apply(this,t)})}),xr=gn(Ee,r,bn),Or=gn(B,r,bn),Er=gn(gr,r,bn),Lr=jn("dir"),Ar=M(Ln,1),Tr=gn(Ee,Tn,Tn),Fr=gn(B,Tn,Tn),Ir=M(Fr,1),_r=z(Bn),Br=P(Bn),Mr=M(Br,1),Ur=jn("log"),zr=M(Un,1/0),Vr=M(Un,1);mr=vr?process.nextTick:yr?setImmediate:an;var Pr=ln(mr),qr=function(n,t){return hn(function(t,e){n(t[0],e)},t,1)},Dr=function(n,t){var e=qr(n,t);return e.push=function(n,t,r){if(null==r&&(r=h),"function"!=typeof r)throw new Error("task callback must be a function");if(e.started=!0,Ft(n)||(n=[n]),0===n.length)return dr(function(){e.drain()});t=t||0;for(var u=e._tasks.head;u&&t>=u.priority;)u=u.next;for(var o=0,i=n.length;o2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file diff --git a/test_app/app/js/_vendor/jquery.min.js b/test_app/app/js/_vendor/jquery.min.js new file mode 100644 index 00000000..0f60b7bd --- /dev/null +++ b/test_app/app/js/_vendor/jquery.min.js @@ -0,0 +1,5 @@ +/*! jQuery v1.11.3 | (c) 2005, 2015 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.3",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b="length"in a&&a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(f=_.exec(a)))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ca,da).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sa(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function ta(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ca,da),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1; + +return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function aa(){return!0}function ba(){return!1}function ca(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),ha=/^\s+/,ia=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ja=/<([\w:]+)/,ka=/\s*$/g,ra={option:[1,""],legend:[1,"
","
"],area:[1,"",""],param:[1,"",""],thead:[1,"","
"],tr:[2,"","
"],col:[2,"","
"],td:[3,"","
"],_default:k.htmlSerialize?[0,"",""]:[1,"X
","
"]},sa=da(y),ta=sa.appendChild(y.createElement("div"));ra.optgroup=ra.option,ra.tbody=ra.tfoot=ra.colgroup=ra.caption=ra.thead,ra.th=ra.td;function ua(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ua(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function va(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wa(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xa(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function ya(a){var b=pa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function za(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Aa(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Ba(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xa(b).text=a.text,ya(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!ga.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ta.innerHTML=a.outerHTML,ta.removeChild(f=ta.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ua(f),h=ua(a),g=0;null!=(e=h[g]);++g)d[g]&&Ba(e,d[g]);if(b)if(c)for(h=h||ua(a),d=d||ua(f),g=0;null!=(e=h[g]);g++)Aa(e,d[g]);else Aa(a,f);return d=ua(f,"script"),d.length>0&&za(d,!i&&ua(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=da(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(la.test(f)){h=h||o.appendChild(b.createElement("div")),i=(ja.exec(f)||["",""])[1].toLowerCase(),l=ra[i]||ra._default,h.innerHTML=l[1]+f.replace(ia,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&ha.test(f)&&p.push(b.createTextNode(ha.exec(f)[0])),!k.tbody){f="table"!==i||ka.test(f)?""!==l[1]||ka.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ua(p,"input"),va),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ua(o.appendChild(f),"script"),g&&za(h),c)){e=0;while(f=h[e++])oa.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wa(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ua(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&za(ua(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ua(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fa,""):void 0;if(!("string"!=typeof a||ma.test(a)||!k.htmlSerialize&&ga.test(a)||!k.leadingWhitespace&&ha.test(a)||ra[(ja.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ia,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ua(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ua(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&na.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ua(i,"script"),xa),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ua(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,ya),j=0;f>j;j++)d=g[j],oa.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qa,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Ca,Da={};function Ea(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fa(a){var b=y,c=Da[a];return c||(c=Ea(a,b),"none"!==c&&c||(Ca=(Ca||m("