From ee73a4656b533b7b3f2d3a3273037312b0c3ef1f Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 05:54:10 -0500 Subject: [PATCH 01/98] Add install.sh --- build.xml | 4 +- jmeter-rabbitmq-setup.sh | 111 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 2 deletions(-) create mode 100755 jmeter-rabbitmq-setup.sh diff --git a/build.xml b/build.xml index b61b1f1..ab5a0b9 100644 --- a/build.xml +++ b/build.xml @@ -25,8 +25,8 @@ - - + + diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh new file mode 100755 index 0000000..2291a4e --- /dev/null +++ b/jmeter-rabbitmq-setup.sh @@ -0,0 +1,111 @@ +#!/bin/sh + +# jmeter-rabbitmq-setup.sh From https://github.com/wilsonmar/JMeter-Rabbit-AMQP +# This script bootstraps a OSX laptop for development +# to a point where we can run Ansible on localhost. It: +# 1. Installs: +# - xcode +# - homebrew, then via brew: +# - java JDK +# +# It begins by asking for your sudo password: + +fancy_echo() { + local fmt="$1"; shift + # shellcheck disable=SC2059 + printf "\n>>> $fmt\n" "$@" +} + +fancy_echo "Boostrapping ..." + +trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +set -e + +# Here we go.. ask for the administrator password upfront and run a +# keep-alive to update existing `sudo` time stamp until script has finished +# sudo -v +# while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & + +# Ensure Apple's command line tools are installed +if ! command -v cc >/dev/null; then + fancy_echo "Installing xcode. It's needed by Homebrew ..." + xcode-select --install +else + fancy_echo "Xcode already installed. Skipping." +fi + +if ! command -v brew >/dev/null; then + fancy_echo "Installing Homebrew for brew commands ..." + ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" /dev/null; then + fancy_echo "Installing JDK ..." + brew cask info java + brew install java + javac -version +else + fancy_echo "JDK already installed. Skipping." +fi + +if ! command -v jmeter >/dev/null; then + fancy_echo "Installing jmeter ..." + brew install jmeter + export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" + echo $JMETER_HOME + ls $JMETER_HOME + + git clone https://github.com/jlavallee/JMeter-Rabbit-AMQP --depth=1 + cd JMeter-Rabbit-AMQPelse + fancy_echo "jmeter already installed. Skipping." +fi + + +if ! command -v tree >/dev/null; then + fancy_echo "Installing tree utlity ..." + brew install tree +else + fancy_echo "tree already installed. Skipping." +fi + pwd + tree -L 1 + +# cd ~/gits + +if ! command -v ant >/dev/null; then + fancy_echo "Installing ant utlity ..." + brew install ant +else + fancy_echo "ant already installed. Skipping." +fi + fancy_echo "ant running..." + ant + +# If file exists: +FILE="target/dist/JMeterAMQP.jar" +if [ -f $FILE ]; then + echo $FILE + cp $FILE $JMETER_HOME/libexec/lib/ext + ls $JMETER_HOME/libexec/lib/ext -al +else + echo "File '$FILE' not found." +fi + + fancy_echo "ivy running..." + java -jar ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ + -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" + +if ! command -v rabbitmq-server >/dev/null; then + fancy_echo "Installing rabbitmq-server locally as server under test ..." + brew install rabbitmq +else + fancy_echo "rabbitmq-server already installed. Skipping." +fi + +#fancy_echo "Starting JMeter..." +# jmeter ??? + + +fancy_echo "Done." From cafab26714ef74009fb8bc0d40b4819f0d5d2845 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 18:12:18 -0500 Subject: [PATCH 02/98] Java8 --- Dockerfile | 22 ++++++++++++++++++++++ jmeter-rabbitmq-setup.sh | 15 +++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9b79587 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +Dockerfile + +FROM ubuntu + +MAINTAINER Wilson Mar + +RUN apt-get update && apt-get install -y nano && apt-get clean + +EXPOSE 8484 + +ENTRYPOINT "put your code here" && /bin/bash +#exemple ENTRYPOINT service nginx start && service ssh start && /bin/bash "use && to separate your code" + +WORKDIR TS3MusicBot +CMD "./TS3MusicBot_runscript.sh -account ... -port 8484 -webif-bind-ip 0.0.0.0" + +after save your code on /root, create a new image docker using + +docker build -t lucassimao/teste:0.1 /root/ +start new container + +docker run -it lucassimao/teste:0.1 /bin/bash \ No newline at end of file diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 2291a4e..3654e52 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -43,10 +43,11 @@ fi if ! command -v java >/dev/null; then fancy_echo "Installing JDK ..." - brew cask info java - brew install java + brew cask info java8 + brew cask install java8 javac -version else + javac -version fancy_echo "JDK already installed. Skipping." fi @@ -104,8 +105,18 @@ else fancy_echo "rabbitmq-server already installed. Skipping." fi +if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then + fancy_echo "rabbitmq in path already. Skipping." +else + fancy_echo "Add path of rabbitmq ..." + export PATH=$PATH:/usr/local/sbin +fi +fancy_echo "Starting Rabbitmq server ..." + rabbitmq-server + #fancy_echo "Starting JMeter..." # jmeter ??? +# watch run at http://localhost:15672 fancy_echo "Done." From 8cece339f146531583e929abd7ce66137cf37ab9 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 18:19:37 -0500 Subject: [PATCH 03/98] tree --- jmeter-rabbitmq-setup.sh | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 3654e52..5fd51ed 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -47,8 +47,8 @@ if ! command -v java >/dev/null; then brew cask install java8 javac -version else - javac -version fancy_echo "JDK already installed. Skipping." + javac -version fi if ! command -v jmeter >/dev/null; then @@ -57,12 +57,18 @@ if ! command -v jmeter >/dev/null; then export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" echo $JMETER_HOME ls $JMETER_HOME - - git clone https://github.com/jlavallee/JMeter-Rabbit-AMQP --depth=1 - cd JMeter-Rabbit-AMQPelse fancy_echo "jmeter already installed. Skipping." fi +// FILE="target/dist/JMeterAMQP.jar" +if [ -f $FILE ]; then + fancy_echo "Cloning JMeter-Rabbit-AMQP repo ..." + echo $FILE + git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 + cd JMeter-Rabbit-AMQPelse +else + fancy_echo "JMeter-Rabbit-AMQP repo already exists ..." +fi if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." @@ -70,6 +76,7 @@ if ! command -v tree >/dev/null; then else fancy_echo "tree already installed. Skipping." fi + fancy_echo "Tree ...." pwd tree -L 1 From a4b45b91b40fc4379c6050829fc7dee2c04b4b89 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 18:23:58 -0500 Subject: [PATCH 04/98] ant --- jmeter-rabbitmq-setup.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 5fd51ed..68ff135 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -18,8 +18,8 @@ fancy_echo() { fancy_echo "Boostrapping ..." -trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -set -e +#trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +#et -e # Here we go.. ask for the administrator password upfront and run a # keep-alive to update existing `sudo` time stamp until script has finished @@ -60,7 +60,7 @@ if ! command -v jmeter >/dev/null; then fancy_echo "jmeter already installed. Skipping." fi -// FILE="target/dist/JMeterAMQP.jar" +# FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then fancy_echo "Cloning JMeter-Rabbit-AMQP repo ..." echo $FILE @@ -94,11 +94,13 @@ fi # If file exists: FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then + fancy_echo "Installing JMeterAMPQ.jar ..." echo $FILE cp $FILE $JMETER_HOME/libexec/lib/ext ls $JMETER_HOME/libexec/lib/ext -al else - echo "File '$FILE' not found." + echo "File '$FILE' not found. Aborting..." + exit fi fancy_echo "ivy running..." From c2673d10e5504f3e98b42282d6109eef096f57b4 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 18:43:49 -0500 Subject: [PATCH 05/98] cloning --- jmeter-rabbitmq-setup.sh | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 68ff135..f10660e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -60,16 +60,17 @@ if ! command -v jmeter >/dev/null; then fancy_echo "jmeter already installed. Skipping." fi -# FILE="target/dist/JMeterAMQP.jar" +FILE="JMeter-Rabbit-AMQP" if [ -f $FILE ]; then - fancy_echo "Cloning JMeter-Rabbit-AMQP repo ..." - echo $FILE + fancy_echo "JMeter-Rabbit-AMQP folder exists, so deleting..." + rm -rf $FILE +fi + fancy_echo "JMeter-Rabbit-AMQP repo being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd JMeter-Rabbit-AMQPelse -else - fancy_echo "JMeter-Rabbit-AMQP repo already exists ..." -fi + tree + if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." brew install tree From 1b11bd4ca8d0e08888cd99562543eb918b69bbb4 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:01:54 -0500 Subject: [PATCH 06/98] cloning --- jmeter-rabbitmq-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index f10660e..ef6c26a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -39,6 +39,7 @@ if ! command -v brew >/dev/null; then ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" /dev/null; then @@ -70,7 +71,7 @@ fi cd JMeter-Rabbit-AMQPelse tree - + if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." brew install tree From ce6c76851b4468ea364fe8b4f2cb307363338df1 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:07:35 -0500 Subject: [PATCH 07/98] cloning --- jmeter-rabbitmq-setup.sh | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index ef6c26a..4846fe2 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -33,6 +33,8 @@ if ! command -v cc >/dev/null; then else fancy_echo "Xcode already installed. Skipping." fi +sw_vers + if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew for brew commands ..." @@ -42,6 +44,7 @@ else brew --version # Homebrew 1.4.2 fi + if ! command -v java >/dev/null; then fancy_echo "Installing JDK ..." brew cask info java8 @@ -52,6 +55,7 @@ else javac -version fi + if ! command -v jmeter >/dev/null; then fancy_echo "Installing jmeter ..." brew install jmeter @@ -61,6 +65,7 @@ if ! command -v jmeter >/dev/null; then fancy_echo "jmeter already installed. Skipping." fi + FILE="JMeter-Rabbit-AMQP" if [ -f $FILE ]; then fancy_echo "JMeter-Rabbit-AMQP folder exists, so deleting..." @@ -79,9 +84,11 @@ else fancy_echo "tree already installed. Skipping." fi fancy_echo "Tree ...." + cd $FILE pwd tree -L 1 + # cd ~/gits if ! command -v ant >/dev/null; then @@ -93,6 +100,7 @@ fi fancy_echo "ant running..." ant + # If file exists: FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then @@ -105,6 +113,7 @@ else exit fi + fancy_echo "ivy running..." java -jar ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" @@ -116,6 +125,7 @@ else fancy_echo "rabbitmq-server already installed. Skipping." fi + if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then fancy_echo "rabbitmq in path already. Skipping." else @@ -125,6 +135,7 @@ fi fancy_echo "Starting Rabbitmq server ..." rabbitmq-server + #fancy_echo "Starting JMeter..." # jmeter ??? From a7031f5dbe79eebeca81948013aa13f239553cf1 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:20:12 -0500 Subject: [PATCH 08/98] cloning --- jmeter-rabbitmq-setup.sh | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 4846fe2..fbf6d6a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -16,7 +16,7 @@ fancy_echo() { printf "\n>>> $fmt\n" "$@" } -fancy_echo "Boostrapping ..." +fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." #trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT #et -e @@ -31,7 +31,7 @@ if ! command -v cc >/dev/null; then fancy_echo "Installing xcode. It's needed by Homebrew ..." xcode-select --install else - fancy_echo "Xcode already installed. Skipping." + fancy_echo "Xcode already installed. Skipping install." fi sw_vers @@ -40,7 +40,7 @@ if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew for brew commands ..." ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" /dev/null; then brew cask install java8 javac -version else - fancy_echo "JDK already installed. Skipping." + fancy_echo "JDK already installed. Skipping install." javac -version fi @@ -62,7 +62,7 @@ if ! command -v jmeter >/dev/null; then export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" echo $JMETER_HOME ls $JMETER_HOME - fancy_echo "jmeter already installed. Skipping." + fancy_echo "jmeter already installed. Skipping install." fi @@ -81,7 +81,7 @@ if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." brew install tree else - fancy_echo "tree already installed. Skipping." + fancy_echo "tree already installed. Skipping install." fi fancy_echo "Tree ...." cd $FILE @@ -95,7 +95,7 @@ if ! command -v ant >/dev/null; then fancy_echo "Installing ant utlity ..." brew install ant else - fancy_echo "ant already installed. Skipping." + fancy_echo "ant already installed. Skipping install." fi fancy_echo "ant running..." ant @@ -122,23 +122,24 @@ if ! command -v rabbitmq-server >/dev/null; then fancy_echo "Installing rabbitmq-server locally as server under test ..." brew install rabbitmq else - fancy_echo "rabbitmq-server already installed. Skipping." + fancy_echo "rabbitmq-server already installed. Skipping install." fi if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then - fancy_echo "rabbitmq in path already. Skipping." + fancy_echo "rabbitmq in path already. Skipping install." else fancy_echo "Add path of rabbitmq ..." export PATH=$PATH:/usr/local/sbin fi -fancy_echo "Starting Rabbitmq server ..." - rabbitmq-server +fancy_echo "Starting Rabbitmq server in background using nohup ..." + nohup rabbitmq-server &>/dev/null & + jobs + open http://localhost:15672 #fancy_echo "Starting JMeter..." # jmeter ??? -# watch run at http://localhost:15672 fancy_echo "Done." From 8db2fd989fa487ba27c0c4463c8b695604abef15 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:28:04 -0500 Subject: [PATCH 09/98] jmeter --- jmeter-rabbitmq-setup.sh | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index fbf6d6a..002f386 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -16,10 +16,12 @@ fancy_echo() { printf "\n>>> $fmt\n" "$@" } +trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +set -e + fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." +clear -#trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -#et -e # Here we go.. ask for the administrator password upfront and run a # keep-alive to update existing `sudo` time stamp until script has finished @@ -70,6 +72,8 @@ FILE="JMeter-Rabbit-AMQP" if [ -f $FILE ]; then fancy_echo "JMeter-Rabbit-AMQP folder exists, so deleting..." rm -rf $FILE +else + fancy_echo "JMeter-Rabbit-AMQP folder does not exist ..." fi fancy_echo "JMeter-Rabbit-AMQP repo being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 @@ -135,11 +139,12 @@ fi fancy_echo "Starting Rabbitmq server in background using nohup ..." nohup rabbitmq-server &>/dev/null & jobs + ps open http://localhost:15672 -#fancy_echo "Starting JMeter..." -# jmeter ??? +fancy_echo "Starting JMeter in background to run test..." + jmeter -v fancy_echo "Done." From 7a7860397186adebd68bee249b5dda9af5777acf Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:35:52 -0500 Subject: [PATCH 10/98] jmeter --- jmeter-rabbitmq-setup.sh | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 002f386..b182c44 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -2,8 +2,7 @@ # jmeter-rabbitmq-setup.sh From https://github.com/wilsonmar/JMeter-Rabbit-AMQP # This script bootstraps a OSX laptop for development -# to a point where we can run Ansible on localhost. It: -# 1. Installs: +# See https://wilsonmar.github.io/ # - xcode # - homebrew, then via brew: # - java JDK @@ -20,7 +19,8 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." -clear + clear + sw_vers # Here we go.. ask for the administrator password upfront and run a @@ -35,7 +35,7 @@ if ! command -v cc >/dev/null; then else fancy_echo "Xcode already installed. Skipping install." fi -sw_vers + xcodebuild -version if ! command -v brew >/dev/null; then @@ -69,6 +69,7 @@ fi FILE="JMeter-Rabbit-AMQP" +echo $FILE if [ -f $FILE ]; then fancy_echo "JMeter-Rabbit-AMQP folder exists, so deleting..." rm -rf $FILE @@ -79,7 +80,7 @@ fi git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd JMeter-Rabbit-AMQPelse tree - +exit if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." @@ -98,10 +99,12 @@ fi if ! command -v ant >/dev/null; then fancy_echo "Installing ant utlity ..." brew install ant + ant -v else fancy_echo "ant already installed. Skipping install." + ant -v fi - fancy_echo "ant running..." + fancy_echo "ant running to process ant.xml ..." ant @@ -133,7 +136,7 @@ fi if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then fancy_echo "rabbitmq in path already. Skipping install." else - fancy_echo "Add path of rabbitmq ..." + fancy_echo "Add path of rabbitmq /usr/local/sbin ..." export PATH=$PATH:/usr/local/sbin fi fancy_echo "Starting Rabbitmq server in background using nohup ..." From 51b7341e2b34c09bc8d390afa86abb964d36d338 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:39:11 -0500 Subject: [PATCH 11/98] jmeter --- jmeter-rabbitmq-setup.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b182c44..2aea41a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -19,7 +19,7 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." - clear +# clear sw_vers @@ -68,17 +68,17 @@ if ! command -v jmeter >/dev/null; then fi -FILE="JMeter-Rabbit-AMQP" -echo $FILE -if [ -f $FILE ]; then - fancy_echo "JMeter-Rabbit-AMQP folder exists, so deleting..." - rm -rf $FILE +REPO1="JMeter-Rabbit-AMQP" +echo $REPO1 +if [ -d $REPO1 ]; then + fancy_echo "$REPO1 folder exists, so deleting..." + rm -rf $REPO1 else - fancy_echo "JMeter-Rabbit-AMQP folder does not exist ..." + fancy_echo "$REPO1 folder does not exist ..." fi - fancy_echo "JMeter-Rabbit-AMQP repo being cloned ..." + fancy_echo "$REPO1 repo being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 - cd JMeter-Rabbit-AMQPelse + cd $REPO1 tree exit From a42059fd84cb92c270dfa781cdd57abd17c7c430 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:48:52 -0500 Subject: [PATCH 12/98] jmeter --- jmeter-rabbitmq-setup.sh | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 2aea41a..0fa0556 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -48,12 +48,12 @@ fi if ! command -v java >/dev/null; then - fancy_echo "Installing JDK ..." + fancy_echo "Installing Java JDK ..." brew cask info java8 brew cask install java8 javac -version else - fancy_echo "JDK already installed. Skipping install." + fancy_echo "Java JDK already installed. Skipping install." javac -version fi @@ -64,8 +64,10 @@ if ! command -v jmeter >/dev/null; then export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" echo $JMETER_HOME ls $JMETER_HOME +else fancy_echo "jmeter already installed. Skipping install." fi + jmeter -v REPO1="JMeter-Rabbit-AMQP" @@ -76,7 +78,7 @@ if [ -d $REPO1 ]; then else fancy_echo "$REPO1 folder does not exist ..." fi - fancy_echo "$REPO1 repo being cloned ..." + echo "$REPO1 repo being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd $REPO1 tree @@ -139,15 +141,15 @@ else fancy_echo "Add path of rabbitmq /usr/local/sbin ..." export PATH=$PATH:/usr/local/sbin fi -fancy_echo "Starting Rabbitmq server in background using nohup ..." + fancy_echo "Starting Rabbitmq server in background using nohup ..." nohup rabbitmq-server &>/dev/null & jobs ps - open http://localhost:15672 + open http://localhost:15672 # default port. -fancy_echo "Starting JMeter in background to run test..." - jmeter -v + fancy_echo "Starting JMeter in background to run test ..." +# nohup "./jmeter.sh -n -t $REPO1/bin/GamesSubscriber.jmx -l result.jtl" > /dev/null 2>&1 & fancy_echo "Done." From 0bdc34d9fc6338740a5bc2b11ab329629cc65814 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:54:48 -0500 Subject: [PATCH 13/98] jmeter --- jmeter-rabbitmq-setup.sh | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 0fa0556..e79a32b 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -58,25 +58,25 @@ else fi +export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" +if [ -d $JMETER_HOME ]; then if ! command -v jmeter >/dev/null; then - fancy_echo "Installing jmeter ..." + fancy_echo "Installing jmeter to $JMETER_HOME ..." brew install jmeter - export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" - echo $JMETER_HOME - ls $JMETER_HOME else - fancy_echo "jmeter already installed. Skipping install." + fancy_echo "$JMETER_HOME already installed. Skipping install." fi - jmeter -v + ls $JMETER_HOME + # jmeter -v # with that big ASCII art banner. REPO1="JMeter-Rabbit-AMQP" echo $REPO1 if [ -d $REPO1 ]; then - fancy_echo "$REPO1 folder exists, so deleting..." + fancy_echo "$REPO1 repo folder exists, so deleting..." rm -rf $REPO1 else - fancy_echo "$REPO1 folder does not exist ..." + fancy_echo "$REPO1 repo folder does not exist ..." fi echo "$REPO1 repo being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 From b33d0f2e60394c6e580f8213e46836e2278badb0 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:57:05 -0500 Subject: [PATCH 14/98] jmeter --- jmeter-rabbitmq-setup.sh | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index e79a32b..8335287 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -60,11 +60,10 @@ fi export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" if [ -d $JMETER_HOME ]; then -if ! command -v jmeter >/dev/null; then + fancy_echo "$JMETER_HOME already installed. Skipping install." +else fancy_echo "Installing jmeter to $JMETER_HOME ..." brew install jmeter -else - fancy_echo "$JMETER_HOME already installed. Skipping install." fi ls $JMETER_HOME # jmeter -v # with that big ASCII art banner. From 35de76768c63dee8eee8d73de08a03fcd001f414 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:58:03 -0500 Subject: [PATCH 15/98] jmeter --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 8335287..fc4ee1f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -67,7 +67,7 @@ else fi ls $JMETER_HOME # jmeter -v # with that big ASCII art banner. - +exit REPO1="JMeter-Rabbit-AMQP" echo $REPO1 From fb6cdc8e142283ba58ccf5c27b48462475d4a95f Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:58:27 -0500 Subject: [PATCH 16/98] jmeter --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index fc4ee1f..077b3d9 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -36,7 +36,7 @@ else fancy_echo "Xcode already installed. Skipping install." fi xcodebuild -version - +exit if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew for brew commands ..." From faf05f96779cae97c8a024af80417d299b5ed211 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Sun, 7 Jan 2018 23:59:08 -0500 Subject: [PATCH 17/98] jmeter --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 077b3d9..d43a79e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -15,8 +15,8 @@ fancy_echo() { printf "\n>>> $fmt\n" "$@" } -trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -set -e +#trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +#set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." # clear @@ -36,7 +36,7 @@ else fancy_echo "Xcode already installed. Skipping install." fi xcodebuild -version -exit + if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew for brew commands ..." From 1edaf62fb4529fb0375057975564298671b33ac2 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:00:07 -0500 Subject: [PATCH 18/98] jmeter --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index d43a79e..ff478d6 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -67,7 +67,7 @@ else fi ls $JMETER_HOME # jmeter -v # with that big ASCII art banner. -exit + REPO1="JMeter-Rabbit-AMQP" echo $REPO1 From 66fb4705ae77c0226b6b102e25f1d598e7cf06d5 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:02:22 -0500 Subject: [PATCH 19/98] jmeter --- jmeter-rabbitmq-setup.sh | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index ff478d6..7889b03 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -70,18 +70,17 @@ fi REPO1="JMeter-Rabbit-AMQP" -echo $REPO1 if [ -d $REPO1 ]; then - fancy_echo "$REPO1 repo folder exists, so deleting..." + fancy_echo "Repo $REPO1 folder exists, so deleting..." rm -rf $REPO1 else - fancy_echo "$REPO1 repo folder does not exist ..." + fancy_echo "Repo $REPO1 folder does not exist ..." fi - echo "$REPO1 repo being cloned ..." + echo "Repo $REPO1 being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd $REPO1 tree -exit + if ! command -v tree >/dev/null; then fancy_echo "Installing tree utlity ..." From e3165fb1f135ad165b3d7a57c6636e0d71bdeba7 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:04:06 -0500 Subject: [PATCH 20/98] jmeter --- jmeter-rabbitmq-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 7889b03..242816f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -79,7 +79,8 @@ fi echo "Repo $REPO1 being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd $REPO1 - tree + pwd + #tree if ! command -v tree >/dev/null; then From a91704ac07ca50256432ba540c6aa40e32302e60 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:07:16 -0500 Subject: [PATCH 21/98] set e --- jmeter-rabbitmq-setup.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 242816f..9f14a6d 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -15,8 +15,8 @@ fancy_echo() { printf "\n>>> $fmt\n" "$@" } -#trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -#set -e +trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." # clear @@ -76,7 +76,7 @@ if [ -d $REPO1 ]; then else fancy_echo "Repo $REPO1 folder does not exist ..." fi - echo "Repo $REPO1 being cloned ..." + fancy_echo "Repo $REPO1 being cloned ..." git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 cd $REPO1 pwd @@ -117,7 +117,7 @@ if [ -f $FILE ]; then cp $FILE $JMETER_HOME/libexec/lib/ext ls $JMETER_HOME/libexec/lib/ext -al else - echo "File '$FILE' not found. Aborting..." + fancy_echo "File '$FILE' not found. Aborting..." exit fi From 29d79a6b34379419b60c5454356240be873397d1 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:09:17 -0500 Subject: [PATCH 22/98] tree --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9f14a6d..c34c6eb 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -89,8 +89,8 @@ if ! command -v tree >/dev/null; then else fancy_echo "tree already installed. Skipping install." fi - fancy_echo "Tree ...." - cd $FILE + fancy_echo "Tree of $REPO1 ...." + cd $REPO1 pwd tree -L 1 From c743ec1c06ac6a44542001c7d12805a41b852da0 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:11:17 -0500 Subject: [PATCH 23/98] tree --- jmeter-rabbitmq-setup.sh | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index c34c6eb..de202b6 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -84,13 +84,11 @@ fi if ! command -v tree >/dev/null; then - fancy_echo "Installing tree utlity ..." + fancy_echo "Installing tree utility missing in MacOS ..." brew install tree else fancy_echo "tree already installed. Skipping install." fi - fancy_echo "Tree of $REPO1 ...." - cd $REPO1 pwd tree -L 1 From 1420bc221ca690028d7df86a787945d41d87dfff Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:35:40 -0500 Subject: [PATCH 24/98] JMeterAMQP.jar --- jmeter-rabbitmq-setup.sh | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index de202b6..b7d2a9a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -89,7 +89,6 @@ if ! command -v tree >/dev/null; then else fancy_echo "tree already installed. Skipping install." fi - pwd tree -L 1 @@ -107,11 +106,11 @@ fi ant -# If file exists: FILE="target/dist/JMeterAMQP.jar" -if [ -f $FILE ]; then - fancy_echo "Installing JMeterAMPQ.jar ..." - echo $FILE +if [ -f $FILE ]; then # file exists within folder $REPO1 + fancy_echo "Deleting previous and copying from $FILE ..." + ls -al $JMETER_HOME/libexec/lib/ext | grep JMeterAMQP.jar + rm $JMETER_HOME/libexec/lib/ext/JMeterAMQP.jar cp $FILE $JMETER_HOME/libexec/lib/ext ls $JMETER_HOME/libexec/lib/ext -al else @@ -142,7 +141,7 @@ fi nohup rabbitmq-server &>/dev/null & jobs ps - open http://localhost:15672 # default port. + open http://localhost:15672 # default port (open is Mac only command) fancy_echo "Starting JMeter in background to run test ..." From 18bf321cb63fd52217c533649481d63ff3e09d47 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:39:56 -0500 Subject: [PATCH 25/98] JMeterAMQP.jar --- jmeter-rabbitmq-setup.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b7d2a9a..bab97c8 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -108,9 +108,12 @@ fi FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then # file exists within folder $REPO1 - fancy_echo "Deleting previous and copying from $FILE ..." + fancy_echo "$FILE was created ..." + ls -al $FILE | grep JMeterAMQP.jar + fancy_echo "Removing previous within JMETER_HOME ..." ls -al $JMETER_HOME/libexec/lib/ext | grep JMeterAMQP.jar rm $JMETER_HOME/libexec/lib/ext/JMeterAMQP.jar + fancy_echo "Copying in from $FILE ..." cp $FILE $JMETER_HOME/libexec/lib/ext ls $JMETER_HOME/libexec/lib/ext -al else From 0e1631d0eeb9bb41d9b6892c86a89440ca5620dc Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:41:38 -0500 Subject: [PATCH 26/98] JMeterAMQP.jar --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index bab97c8..61fb438 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -115,7 +115,7 @@ if [ -f $FILE ]; then # file exists within folder $REPO1 rm $JMETER_HOME/libexec/lib/ext/JMeterAMQP.jar fancy_echo "Copying in from $FILE ..." cp $FILE $JMETER_HOME/libexec/lib/ext - ls $JMETER_HOME/libexec/lib/ext -al + ls -al $JMETER_HOME/libexec/lib/ext | grep JMeterAMQP.jar else fancy_echo "File '$FILE' not found. Aborting..." exit From 559c96f94949c6ebfea2d9f28bd2ca2a8b424068 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 00:45:16 -0500 Subject: [PATCH 27/98] JMeterAMQP.jar --- jmeter-rabbitmq-setup.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 61fb438..af8abd4 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -120,6 +120,7 @@ else fancy_echo "File '$FILE' not found. Aborting..." exit fi +pwd fancy_echo "ivy running..." From 168409f22d3b756ff89118d269432c3772752ca4 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:10:25 -0500 Subject: [PATCH 28/98] from temp --- jmeter-rabbitmq-setup.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index af8abd4..5dcaa99 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -120,11 +120,13 @@ else fancy_echo "File '$FILE' not found. Aborting..." exit fi + + pwd fancy_echo "ivy running..." - java -jar ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ + java -jar ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" if ! command -v rabbitmq-server >/dev/null; then From 342fde0829043ee975e8d7c676998e3f8e368a05 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:11:43 -0500 Subject: [PATCH 29/98] ivy --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 5dcaa99..86d8eb5 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -125,8 +125,8 @@ fi pwd - fancy_echo "ivy running..." - java -jar ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ + fancy_echo "ivy running in ivy folder ..." + java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" if ! command -v rabbitmq-server >/dev/null; then From f5e8715554fd4368fdb8e07d8e763e49fa973bda Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:14:46 -0500 Subject: [PATCH 30/98] ivy --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 86d8eb5..4b7a5b7 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -122,13 +122,13 @@ else fi -pwd - fancy_echo "ivy running in ivy folder ..." + pwd java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" + if ! command -v rabbitmq-server >/dev/null; then fancy_echo "Installing rabbitmq-server locally as server under test ..." brew install rabbitmq From 44feebf94a301c4d5b0fb73b2fc0d7b10c98a037 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:36:43 -0500 Subject: [PATCH 31/98] pause --- jmeter-rabbitmq-setup.sh | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 4b7a5b7..b748797 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -14,6 +14,10 @@ fancy_echo() { # shellcheck disable=SC2059 printf "\n>>> $fmt\n" "$@" } +function pause(){ + read -p "$*" +} + trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e @@ -143,12 +147,15 @@ else fancy_echo "Add path of rabbitmq /usr/local/sbin ..." export PATH=$PATH:/usr/local/sbin fi + + fancy_echo "Starting Rabbitmq server in background using nohup ..." nohup rabbitmq-server &>/dev/null & jobs - ps - open http://localhost:15672 # default port (open is Mac only command) + ps + open http://localhost:15672 # default port (open is Mac only command) +pause 'Press [Enter] key to continue...' fancy_echo "Starting JMeter in background to run test ..." # nohup "./jmeter.sh -n -t $REPO1/bin/GamesSubscriber.jmx -l result.jtl" > /dev/null 2>&1 & From 1af4f9d0064888897d460739315491ccb96f7585 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:44:22 -0500 Subject: [PATCH 32/98] pause --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b748797..6343bc6 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -2,7 +2,7 @@ # jmeter-rabbitmq-setup.sh From https://github.com/wilsonmar/JMeter-Rabbit-AMQP # This script bootstraps a OSX laptop for development -# See https://wilsonmar.github.io/ +# Steps here are explained in https://wilsonmar.github.io/jmeter-install/ # - xcode # - homebrew, then via brew: # - java JDK @@ -154,8 +154,8 @@ fi jobs ps - open http://localhost:15672 # default port (open is Mac only command) -pause 'Press [Enter] key to continue...' + #open http://localhost:15672 # default port (open is Mac only command) + # pause 'Press [Enter] key to continue...' fancy_echo "Starting JMeter in background to run test ..." # nohup "./jmeter.sh -n -t $REPO1/bin/GamesSubscriber.jmx -l result.jtl" > /dev/null 2>&1 & From b0c473083566b8a55cf5c2143fd30fd0d20ca890 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 01:53:06 -0500 Subject: [PATCH 33/98] pause --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 6343bc6..9df0613 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -155,7 +155,7 @@ fi ps #open http://localhost:15672 # default port (open is Mac only command) - # pause 'Press [Enter] key to continue...' +pause 'Press [Enter] key to continue...' fancy_echo "Starting JMeter in background to run test ..." # nohup "./jmeter.sh -n -t $REPO1/bin/GamesSubscriber.jmx -l result.jtl" > /dev/null 2>&1 & From 679dc3bd4369443733b6c4af7d545130a55bcaff Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 02:53:10 -0500 Subject: [PATCH 34/98] update --- examples/rabbitmq_test.jmx | 215 +++++++++++++++++++++++++++++++++++++ jmeter-rabbitmq-setup.sh | 17 +-- 2 files changed, 224 insertions(+), 8 deletions(-) create mode 100644 examples/rabbitmq_test.jmx diff --git a/examples/rabbitmq_test.jmx b/examples/rabbitmq_test.jmx new file mode 100644 index 0000000..cdffc49 --- /dev/null +++ b/examples/rabbitmq_test.jmx @@ -0,0 +1,215 @@ + + + + + + false + false + + + + + + + + stoptest + + false + 125 + + 8 + 15 + 1361373100000 + 1361373100000 + false + + + + + + 999999999 + 1 + 000000000 + false + + replyToQueue + + + + uniqueId + 0000000 + 1 + 9999999 + 3499272 + false + + + + true + false + + + + my_rpc_exchange + false + false + RPCRequestQueue + RPCMessage.Request.v1_0 + / + + + direct + true + false + false + false + 1000 + 1 + localhost + 5672 + guest + guest + false + false + false + RPCMessage.Request.v1_0 + { + "RequestMessageText": '${uniqueId}' +} + RPCMessageRequest + jMeter_${__threadNum}_${replyToQueue} + ${uniqueId} + + + + + + + my_rpc_exchange + false + false + jMeter_${__threadNum}_${replyToQueue} + RPCMessage.Request.v1_0 + / + + + direct + false + true + true + false + 1000 + 1 + localhost + 5672 + guest + guest + false + false + 0 + 10000 + false + true + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + + + + + + + + + diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9df0613..0e85222 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -1,7 +1,8 @@ #!/bin/sh # jmeter-rabbitmq-setup.sh From https://github.com/wilsonmar/JMeter-Rabbit-AMQP -# This script bootstraps a OSX laptop for development +# This script bootstraps a OSX laptop for development. +# Resources are created new each run (after deleting leftovers from previous run) # Steps here are explained in https://wilsonmar.github.io/jmeter-install/ # - xcode # - homebrew, then via brew: @@ -96,8 +97,6 @@ fi tree -L 1 -# cd ~/gits - if ! command -v ant >/dev/null; then fancy_echo "Installing ant utlity ..." brew install ant @@ -106,8 +105,9 @@ else fancy_echo "ant already installed. Skipping install." ant -v fi - fancy_echo "ant running to process ant.xml ..." + fancy_echo "ant run to process ant.xml ..." ant + # Ant can pick up the Test.jmx file, execute it, and generate an easily-readable HTML report. FILE="target/dist/JMeterAMQP.jar" @@ -127,7 +127,7 @@ fi - fancy_echo "ivy running in ivy folder ..." + fancy_echo "ivy java program running in ivy folder ..." pwd java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" @@ -158,7 +158,8 @@ fi pause 'Press [Enter] key to continue...' fancy_echo "Starting JMeter in background to run test ..." -# nohup "./jmeter.sh -n -t $REPO1/bin/GamesSubscriber.jmx -l result.jtl" > /dev/null 2>&1 & - + # chmod +x jmeter.sh +# nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & +# -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] -fancy_echo "Done." +fancy_echo "Done." \ No newline at end of file From 741622904617c0aeee192ee767bcffe577ad99e2 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 08:30:05 -0500 Subject: [PATCH 35/98] plugins-manager --- jmeter-rabbitmq-setup.sh | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 0e85222..a968d0a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -74,6 +74,23 @@ fi # jmeter -v # with that big ASCII art banner. +FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed. +FOLDER="$JMETER_HOME/libexec/lib/ext" +if [ -f $FOLDER/$FILE ]; then # file exists within folder + fancy_echo "$FILE already installed in $FOLDER. Skipping install." +else + fancy_echo "Downloading and moving $FILE to $FOLDER ..." + # From https://jmeter-plugins.org/wiki/StandardSet/ + curl -O http://jmeter-plugins.org/downloads/file/jmeter-plugins-manager-0.18.jar + cp $FILE $FOLDER -i +fi +exit + +# TODO: Check if version has changed. +# fancy_echo "Installing plugin extras to $JMETER_HOME/libexec/lib/ext ..." +# curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip + + REPO1="JMeter-Rabbit-AMQP" if [ -d $REPO1 ]; then fancy_echo "Repo $REPO1 folder exists, so deleting..." @@ -154,12 +171,17 @@ fi jobs ps - #open http://localhost:15672 # default port (open is Mac only command) -pause 'Press [Enter] key to continue...' + #open http://localhost:15672 # 5672 default port (open is Mac only command) +#pause 'Press [Enter] key to continue...' - fancy_echo "Starting JMeter in background to run test ..." +export JMETER_FILE="rabbitmq_test_run" + fancy_echo "Starting JMeter in background for $JMETER_FILE ..." # chmod +x jmeter.sh + $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/$JMETER_FILE.jmx -l JMETER_FILE_log.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] + fancy_echo "Process $JMETER_FILE_log.jtl ..." + subl $JMETER_FILE_log.jtl + fancy_echo "Done." \ No newline at end of file From 7f792f50ae586e43552ff08518f886680e2ba6e1 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 08:34:03 -0500 Subject: [PATCH 36/98] plugins-manager --- jmeter-rabbitmq-setup.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index a968d0a..97e92f5 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -74,18 +74,22 @@ fi # jmeter -v # with that big ASCII art banner. -FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed. +FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" +echo $FOLDER/$FILE if [ -f $FOLDER/$FILE ]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." else fancy_echo "Downloading and moving $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ curl -O http://jmeter-plugins.org/downloads/file/jmeter-plugins-manager-0.18.jar + + fancy_echo "Moving $FILE to $FOLDER ..." cp $FILE $FOLDER -i fi exit + # TODO: Check if version has changed. # fancy_echo "Installing plugin extras to $JMETER_HOME/libexec/lib/ext ..." # curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip From 3198055ca0edac4ed7b5b9b59679ff5856bd68ba Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 08:37:31 -0500 Subject: [PATCH 37/98] plugins-manager --- jmeter-rabbitmq-setup.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 97e92f5..1511ae5 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -76,7 +76,6 @@ fi FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" -echo $FOLDER/$FILE if [ -f $FOLDER/$FILE ]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." else From a68bf6fc964f3de5bede4d2782d7e02229ebe49e Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 08:40:30 -0500 Subject: [PATCH 38/98] extras --- jmeter-rabbitmq-setup.sh | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 1511ae5..d614f04 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -79,19 +79,27 @@ FOLDER="$JMETER_HOME/libexec/lib/ext" if [ -f $FOLDER/$FILE ]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." else - fancy_echo "Downloading and moving $FILE to $FOLDER ..." + fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ curl -O http://jmeter-plugins.org/downloads/file/jmeter-plugins-manager-0.18.jar fancy_echo "Moving $FILE to $FOLDER ..." cp $FILE $FOLDER -i fi -exit -# TODO: Check if version has changed. -# fancy_echo "Installing plugin extras to $JMETER_HOME/libexec/lib/ext ..." -# curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip +FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. +FOLDER="$JMETER_HOME/libexec/lib/ext" +if [ -f $FOLDER/$FILE ]; then # file exists within folder + fancy_echo "$FILE already installed in $FOLDER. Skipping install." +else + fancy_echo "Downloading $FILE to $FOLDER ..." + # From https://jmeter-plugins.org/wiki/Extras + curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip + + fancy_echo "Moving $FILE to $FOLDER ..." + cp $FILE $FOLDER -i +fi REPO1="JMeter-Rabbit-AMQP" From 82da59181c841167156c7c5c2924bae21f40d4dd Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 09:02:48 -0500 Subject: [PATCH 39/98] extras --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index d614f04..6687e39 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -81,10 +81,10 @@ if [ -f $FOLDER/$FILE ]; then # file exists within folder else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ - curl -O http://jmeter-plugins.org/downloads/file/jmeter-plugins-manager-0.18.jar + curl -O http://jmeter-plugins.org/downloads/file/$FILE fancy_echo "Moving $FILE to $FOLDER ..." - cp $FILE $FOLDER -i + cp $FILE $FOLDER -i fi From 2f6ee8f3c4ef930d424d68b968d46f8f3db95a7b Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 09:03:26 -0500 Subject: [PATCH 40/98] extras --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 6687e39..cb06eee 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -20,8 +20,8 @@ function pause(){ } -trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -set -e +# trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +# set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." # clear From 1db4f5684b778f974898396e7439a4133e0f5661 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 09:13:07 -0500 Subject: [PATCH 41/98] extras out --- jmeter-rabbitmq-setup.sh | 37 +++++++------------------------------ 1 file changed, 7 insertions(+), 30 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index cb06eee..1d3007c 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -20,12 +20,15 @@ function pause(){ } -# trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT -# set -e +trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT +set -e fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." # clear sw_vers + # ProductName: Mac OS X + # ProductVersion: 10.11.6 + # BuildVersion: 15G18013 # Here we go.. ask for the administrator password upfront and run a @@ -41,7 +44,8 @@ else fancy_echo "Xcode already installed. Skipping install." fi xcodebuild -version - + # Xcode 7.3.1 + # Build version 7D1014 if ! command -v brew >/dev/null; then fancy_echo "Installing Homebrew for brew commands ..." @@ -88,33 +92,6 @@ else fi -FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. -FOLDER="$JMETER_HOME/libexec/lib/ext" -if [ -f $FOLDER/$FILE ]; then # file exists within folder - fancy_echo "$FILE already installed in $FOLDER. Skipping install." -else - fancy_echo "Downloading $FILE to $FOLDER ..." - # From https://jmeter-plugins.org/wiki/Extras - curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip - - fancy_echo "Moving $FILE to $FOLDER ..." - cp $FILE $FOLDER -i -fi - - -REPO1="JMeter-Rabbit-AMQP" -if [ -d $REPO1 ]; then - fancy_echo "Repo $REPO1 folder exists, so deleting..." - rm -rf $REPO1 -else - fancy_echo "Repo $REPO1 folder does not exist ..." -fi - fancy_echo "Repo $REPO1 being cloned ..." - git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 - cd $REPO1 - pwd - #tree - if ! command -v tree >/dev/null; then fancy_echo "Installing tree utility missing in MacOS ..." From d6f18df15a8d91ecd1d7244b07d95c7aed98d9be Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Mon, 8 Jan 2018 09:14:20 -0500 Subject: [PATCH 42/98] extras out --- jmeter-rabbitmq-setup.sh | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 1d3007c..aed2a7b 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -78,19 +78,18 @@ fi # jmeter -v # with that big ASCII art banner. -FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. -FOLDER="$JMETER_HOME/libexec/lib/ext" -if [ -f $FOLDER/$FILE ]; then # file exists within folder - fancy_echo "$FILE already installed in $FOLDER. Skipping install." +REPO1="JMeter-Rabbit-AMQP" +if [ -d $REPO1 ]; then + fancy_echo "Repo $REPO1 folder exists, so deleting..." + rm -rf $REPO1 else - fancy_echo "Downloading $FILE to $FOLDER ..." - # From https://jmeter-plugins.org/wiki/StandardSet/ - curl -O http://jmeter-plugins.org/downloads/file/$FILE - - fancy_echo "Moving $FILE to $FOLDER ..." - cp $FILE $FOLDER -i + fancy_echo "Repo $REPO1 folder does not exist ..." fi - + fancy_echo "Repo $REPO1 being cloned ..." + git clone https://github.com/wilsonmar/JMeter-Rabbit-AMQP --depth=1 + cd $REPO1 + pwd + #tree if ! command -v tree >/dev/null; then From 72893a970afd8d61fa11e9ac98d53b7166ac4594 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 01:57:04 -0500 Subject: [PATCH 43/98] extras in --- jmeter-rabbitmq-setup.sh | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index aed2a7b..ce15124 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -101,6 +101,35 @@ fi tree -L 1 +FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. +FOLDER="$JMETER_HOME/libexec/lib/ext" +if [ -f "$FOLDER/$FILE" ]; then # file exists within folder + fancy_echo "$FILE already installed in $FOLDER. Skipping install." +else + fancy_echo "Downloading $FILE to $FOLDER ..." + # From https://jmeter-plugins.org/wiki/StandardSet/ + curl -O http://jmeter-plugins.org/downloads/file/$FILE + + fancy_echo "Moving $FILE to $FOLDER ..." + cp $FILE $FOLDER -i +fi + + +FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. +FOLDER="$JMETER_HOME/libexec/lib/ext" +if [ -f "$FOLDER/$FILE" ]; then # file exists within folder + fancy_echo "$FILE already installed in $FOLDER. Skipping install." +else + fancy_echo "Downloading $FILE to $FOLDER ..." + # From https://jmeter-plugins.org/wiki/Extras + curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip + + fancy_echo "Moving $FILE to $FOLDER ..." + cp $FILE $FOLDER -i +fi + + + if ! command -v ant >/dev/null; then fancy_echo "Installing ant utlity ..." brew install ant From 5649f5b0f9bf45374336bc7eedbb6db4ef1b71f8 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:22:48 -0500 Subject: [PATCH 44/98] extras in --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index ce15124..a414ef7 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -65,7 +65,7 @@ else fancy_echo "Java JDK already installed. Skipping install." javac -version fi - + # javac 1.8.0_152 export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" if [ -d $JMETER_HOME ]; then @@ -74,7 +74,7 @@ else fancy_echo "Installing jmeter to $JMETER_HOME ..." brew install jmeter fi - ls $JMETER_HOME + ls $JMETER_HOME/libexec # jmeter -v # with that big ASCII art banner. @@ -103,7 +103,7 @@ fi FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" -if [ -f "$FOLDER/$FILE" ]; then # file exists within folder +if [[ -f "$FOLDER/$FILE" ]]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." else fancy_echo "Downloading $FILE to $FOLDER ..." From 5d75d9dc66698e62086993f49196481cfbf04989 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:23:48 -0500 Subject: [PATCH 45/98] extras in --- jmeter-rabbitmq-setup.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index a414ef7..215469e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -98,6 +98,7 @@ if ! command -v tree >/dev/null; then else fancy_echo "tree already installed. Skipping install." fi + pwd tree -L 1 From aeb79ce32b19c9d10b602f39f4a400cb86a66f96 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:26:54 -0500 Subject: [PATCH 46/98] time --- jmeter-rabbitmq-setup.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 215469e..9c3c91a 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -23,7 +23,8 @@ function pause(){ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e -fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." +BEGIN=`date +%s` +fancy_echo "Starting jmeter-rabbitmq-setup.sh at $BEGIN ................................." # clear sw_vers # ProductName: Mac OS X @@ -101,6 +102,9 @@ fi pwd tree -L 1 +END=`date +%s` +RUNTIME=$((END-BEGIN)) +echo $RUNTIME FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" From b79704818a6a369d26983937548ef1a229fc8cb5 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:29:01 -0500 Subject: [PATCH 47/98] end time --- jmeter-rabbitmq-setup.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9c3c91a..48f562d 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -24,7 +24,7 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e BEGIN=`date +%s` -fancy_echo "Starting jmeter-rabbitmq-setup.sh at $BEGIN ................................." +fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." # clear sw_vers # ProductName: Mac OS X @@ -102,9 +102,6 @@ fi pwd tree -L 1 -END=`date +%s` -RUNTIME=$((END-BEGIN)) -echo $RUNTIME FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" @@ -122,7 +119,7 @@ fi FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" -if [ -f "$FOLDER/$FILE" ]; then # file exists within folder +if [[ -f "$FOLDER/$FILE" ]]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." else fancy_echo "Downloading $FILE to $FOLDER ..." @@ -205,4 +202,7 @@ export JMETER_FILE="rabbitmq_test_run" fancy_echo "Process $JMETER_FILE_log.jtl ..." subl $JMETER_FILE_log.jtl -fancy_echo "Done." \ No newline at end of file + +END=`date +%s` +RUNTIME=$((END-BEGIN)) +fancy_echo "Done in $RUNTIME seconds." \ No newline at end of file From 5fd29a7564c2120fcaa0293519d8c2b5e1ac7f48 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:33:07 -0500 Subject: [PATCH 48/98] single resolve --- jmeter-rabbitmq-setup.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 48f562d..c6b6898 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -68,6 +68,7 @@ else fi # javac 1.8.0_152 + export JMETER_HOME="/usr/local/Cellar/jmeter/3.3" if [ -d $JMETER_HOME ]; then fancy_echo "$JMETER_HOME already installed. Skipping install." @@ -105,8 +106,9 @@ fi FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" -if [[ -f "$FOLDER/$FILE" ]]; then # file exists within folder +if [[ -f "$JMETER_HOME/libexec/lib/ext/$FILE" ]]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ From bdbe714f05cfbf8900247ce80440829cb3f79cb9 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:35:27 -0500 Subject: [PATCH 49/98] single resolve --- jmeter-rabbitmq-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index c6b6898..6d75be9 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -106,7 +106,7 @@ fi FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FOLDER="$JMETER_HOME/libexec/lib/ext" -if [[ -f "$JMETER_HOME/libexec/lib/ext/$FILE" ]]; then # file exists within folder +if [ -f "$JMETER_HOME/libexec/lib/ext/$FILE" ]; then # file exists within folder fancy_echo "$FILE already installed in $FOLDER. Skipping install." ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE else @@ -116,6 +116,7 @@ else fancy_echo "Moving $FILE to $FOLDER ..." cp $FILE $FOLDER -i + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi From 4e7f9a263e7b115bfc6d89281b06bd0fdaa777ab Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:41:50 -0500 Subject: [PATCH 50/98] FILE_PATH --- jmeter-rabbitmq-setup.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 6d75be9..b520212 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -104,18 +104,18 @@ fi tree -L 1 -FILE="meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. -FOLDER="$JMETER_HOME/libexec/lib/ext" -if [ -f "$JMETER_HOME/libexec/lib/ext/$FILE" ]; then # file exists within folder - fancy_echo "$FILE already installed in $FOLDER. Skipping install." +FILE_PATH="$JMETER_HOME/libexec/lib/ext/meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. +FILE="meter-plugins-manager-0.18.jar" +if [ -f $FILE_PATH ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ curl -O http://jmeter-plugins.org/downloads/file/$FILE - fancy_echo "Moving $FILE to $FOLDER ..." - cp $FILE $FOLDER -i + fancy_echo "Moving $FILE to $FILE_PATH ..." + cp $FILE $FILE_PATH -i ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi From be08505caa74bc24279712c15217617654262bd0 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:44:20 -0500 Subject: [PATCH 51/98] yes cp --- jmeter-rabbitmq-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b520212..75f8d55 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -103,6 +103,7 @@ fi pwd tree -L 1 +# DEBUGGING: FILE_PATH="$JMETER_HOME/libexec/lib/ext/meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FILE="meter-plugins-manager-0.18.jar" @@ -115,7 +116,7 @@ else curl -O http://jmeter-plugins.org/downloads/file/$FILE fancy_echo "Moving $FILE to $FILE_PATH ..." - cp $FILE $FILE_PATH -i + yes | cp -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi From 7ab881c9136c2379c4aa6da6fcf0a223f8f365a7 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 02:47:56 -0500 Subject: [PATCH 52/98] typo --- jmeter-rabbitmq-setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 75f8d55..e96c947 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -105,7 +105,8 @@ fi # DEBUGGING: -FILE_PATH="$JMETER_HOME/libexec/lib/ext/meter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. + +FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FILE="meter-plugins-manager-0.18.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." From 78328e9de52069a97a80673d1585266a06ebde22 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 03:41:42 -0500 Subject: [PATCH 53/98] typo --- jmeter-rabbitmq-setup.sh | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index e96c947..e99bb23 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -103,11 +103,10 @@ fi pwd tree -L 1 -# DEBUGGING: -FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-manager-0.18.jar" # TODO: Check if version has changed since Jan 4, 2018. FILE="meter-plugins-manager-0.18.jar" +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" # TODO: Check if version has changed since Jan 4, 2018. if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE @@ -115,24 +114,26 @@ else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ curl -O http://jmeter-plugins.org/downloads/file/$FILE - - fancy_echo "Moving $FILE to $FILE_PATH ..." + ls -al $FILE + fancy_echo "Overwriting $FILE_PATH ..." yes | cp -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. -FOLDER="$JMETER_HOME/libexec/lib/ext" -if [[ -f "$FOLDER/$FILE" ]]; then # file exists within folder - fancy_echo "$FILE already installed in $FOLDER. Skipping install." +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +if [ -f $FILE_PATH ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/Extras curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip - - fancy_echo "Moving $FILE to $FOLDER ..." - cp $FILE $FOLDER -i + ls -al $FILE + fancy_echo "Overwriting $FILE_PATH ..." + yes | cp -rf $FILE $FILE_PATH + ls -al $FILE_PATH fi From 17f5da0c7d900450569160cf6399a403bb64c73e Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 05:46:16 -0500 Subject: [PATCH 54/98] jtl --- jmeter-rabbitmq-setup.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index e99bb23..45c0daf 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -198,15 +198,15 @@ fi #open http://localhost:15672 # 5672 default port (open is Mac only command) #pause 'Press [Enter] key to continue...' -export JMETER_FILE="rabbitmq_test_run" +export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." # chmod +x jmeter.sh - $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/$JMETER_FILE.jmx -l JMETER_FILE_log.jtl + $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabitmq_test.jmx -l rabitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] - fancy_echo "Process $JMETER_FILE_log.jtl ..." - subl $JMETER_FILE_log.jtl + fancy_echo "Process rabitmq_test.jtl ..." + subl rabitmq_test.jtl END=`date +%s` From bb6b05a7f65972ef5cff0213a927bce818bd7adc Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 06:19:38 -0500 Subject: [PATCH 55/98] jtl --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 45c0daf..a309b02 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -201,12 +201,12 @@ fi export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." # chmod +x jmeter.sh - $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabitmq_test.jmx -l rabitmq_test.jtl + $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] - fancy_echo "Process rabitmq_test.jtl ..." - subl rabitmq_test.jtl + fancy_echo "Process rabbitmq_test.jtl ..." + subl rabbitmq_test.jtl END=`date +%s` From 52f289e07d3fbdf7e3ddd737df7ec361bb5af2bb Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 06:25:56 -0500 Subject: [PATCH 56/98] jmx --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index a309b02..0c1845f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -200,13 +200,13 @@ fi export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." - # chmod +x jmeter.sh + ls -al $REPO1/examples/rabbitmq_test.jmx $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] fancy_echo "Process rabbitmq_test.jtl ..." - subl rabbitmq_test.jtl +# subl rabbitmq_test.jtl END=`date +%s` From 3d9efa280c7389a18790ec0c430252ab5cfa10df Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 06:29:41 -0500 Subject: [PATCH 57/98] pwd jmx --- jmeter-rabbitmq-setup.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 0c1845f..1d4058b 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -200,6 +200,7 @@ fi export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." + pwd ls -al $REPO1/examples/rabbitmq_test.jmx $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & From 2798b7c1f1166c8a765af0de767a9304ad539211 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 06:31:20 -0500 Subject: [PATCH 58/98] pwd jmx --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 1d4058b..6f6118e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -202,7 +202,7 @@ export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." pwd ls -al $REPO1/examples/rabbitmq_test.jmx - $JMETER_HOME/libexec/bin/jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l rabbitmq_test.jtl + $JMETER_HOME/libexec/bin/jmeter.sh -n -t examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] From fc580a5a10213ed929ca86139e085708909edcf6 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 06:32:45 -0500 Subject: [PATCH 59/98] pwd jmx --- jmeter-rabbitmq-setup.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 6f6118e..2e7d837 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -200,8 +200,7 @@ fi export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." - pwd - ls -al $REPO1/examples/rabbitmq_test.jmx + ls -al examples/rabbitmq_test.jmx $JMETER_HOME/libexec/bin/jmeter.sh -n -t examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] From 867c7742a1fbf3db05364be9a0b4735d420a84af Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 10:33:15 -0500 Subject: [PATCH 60/98] praveen --- jmeter-rabbitmq-setup.sh | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 2e7d837..07c0d09 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -24,7 +24,17 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e BEGIN=`date +%s` -fancy_echo "Starting jmeter-rabbitmq-setup.sh ................................." + +PLATFORM='unknown' +UNAMESTR=$(uname) # instead of older `uname` +if [[ "$unamestr" == 'Darwin' ]]; then + PLATFORM='macos' +else [[ "$unamestr" == 'Linux' ]]; then + PLATFORM='linux' # Ubuntu, etc. +elif [[ "$unamestr" == 'FreeBSD' ]]; then + PLATFORM='freebsd' +fi +fancy_echo "Starting jmeter-rabbitmq-setup.sh on $PLATFORM / $OSTYPE ................................." # clear sw_vers # ProductName: Mac OS X @@ -119,23 +129,7 @@ else yes | cp -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi - - -FILE="JMeterPlugins-Extras-1.2.1.zip" # TODO: Check if version has changed since Jan 4, 2018. -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" -if [ -f $FILE_PATH ]; then # file exists within folder - fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE -else - fancy_echo "Downloading $FILE to $FOLDER ..." - # From https://jmeter-plugins.org/wiki/Extras - curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.2.1.zip - ls -al $FILE - fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH - ls -al $FILE_PATH -fi - +NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. if ! command -v ant >/dev/null; then From fb81c88a4861b1b3ed71e67e4490fc2b0b2e05fb Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 10:34:43 -0500 Subject: [PATCH 61/98] praveen --- jmeter-rabbitmq-setup.sh | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 07c0d09..1d9acfe 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -19,21 +19,11 @@ function pause(){ read -p "$*" } - trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e BEGIN=`date +%s` -PLATFORM='unknown' -UNAMESTR=$(uname) # instead of older `uname` -if [[ "$unamestr" == 'Darwin' ]]; then - PLATFORM='macos' -else [[ "$unamestr" == 'Linux' ]]; then - PLATFORM='linux' # Ubuntu, etc. -elif [[ "$unamestr" == 'FreeBSD' ]]; then - PLATFORM='freebsd' -fi fancy_echo "Starting jmeter-rabbitmq-setup.sh on $PLATFORM / $OSTYPE ................................." # clear sw_vers @@ -201,6 +191,7 @@ export JMETER_FILE="rabbitmq_test" fancy_echo "Process rabbitmq_test.jtl ..." # subl rabbitmq_test.jtl +# https://blogs.perficient.com/delivery/blog/2015/04/08/generate-performance-testing-report-with-jmeter-plugins-and-ant/ END=`date +%s` From 73c4b5bfe818f86dd63ebcbdc3f000c5920e7046 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 10:36:46 -0500 Subject: [PATCH 62/98] praveen --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 1d9acfe..19cf135 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -119,7 +119,7 @@ else yes | cp -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi -NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. +# NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. if ! command -v ant >/dev/null; then From 4451f56efce5df35945f7367eb524ffe3c9b4812 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 14:16:55 -0500 Subject: [PATCH 63/98] new jmx --- examples/AMQP Publisher.jmx | 102 ++++++++++++++++++++++++++++++++++++ jmeter-rabbitmq-setup.sh | 6 ++- 2 files changed, 107 insertions(+), 1 deletion(-) create mode 100644 examples/AMQP Publisher.jmx diff --git a/examples/AMQP Publisher.jmx b/examples/AMQP Publisher.jmx new file mode 100644 index 0000000..c357780 --- /dev/null +++ b/examples/AMQP Publisher.jmx @@ -0,0 +1,102 @@ + + + + + + false + false + + + + + + + + continue + + false + 1 + + 10 + 1 + 1502397449000 + 1502397449000 + false + + + + + + Test.Direct + true + false + false + Test.Queue + 100 + / + + + direct + true + false + false + false + 1000 + 1 + localhost + 5672 + guest + guest + false + true + false + 100 + Test 123456 + + + + + + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + + + + + + + + + diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 19cf135..9fca2c7 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -24,7 +24,7 @@ set -e BEGIN=`date +%s` -fancy_echo "Starting jmeter-rabbitmq-setup.sh on $PLATFORM / $OSTYPE ................................." +fancy_echo "Starting jmeter-rabbitmq-setup.sh on $OSTYPE ................................." # clear sw_vers # ProductName: Mac OS X @@ -166,6 +166,7 @@ else fi + if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then fancy_echo "rabbitmq in path already. Skipping install." else @@ -174,6 +175,9 @@ else fi +## TODO: Configure RabbitMQ Exchanges etc. + + fancy_echo "Starting Rabbitmq server in background using nohup ..." nohup rabbitmq-server &>/dev/null & jobs From adebf405bbcddcc7a384822214abb16d2a718cb2 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 16:08:12 -0500 Subject: [PATCH 64/98] jmx from Praveen --- examples/AMQP Publisher.jmx | 102 ------------------ examples/rabbitmq_test.jmx | 209 +++++++++--------------------------- 2 files changed, 48 insertions(+), 263 deletions(-) delete mode 100644 examples/AMQP Publisher.jmx diff --git a/examples/AMQP Publisher.jmx b/examples/AMQP Publisher.jmx deleted file mode 100644 index c357780..0000000 --- a/examples/AMQP Publisher.jmx +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - false - false - - - - - - - - continue - - false - 1 - - 10 - 1 - 1502397449000 - 1502397449000 - false - - - - - - Test.Direct - true - false - false - Test.Queue - 100 - / - - - direct - true - false - false - false - 1000 - 1 - localhost - 5672 - guest - guest - false - true - false - 100 - Test 123456 - - - - - - - - - - - - false - - saveConfig - - - true - true - true - - true - true - true - true - false - true - true - false - false - false - true - false - false - false - true - 0 - true - true - true - - - - - - - - - diff --git a/examples/rabbitmq_test.jmx b/examples/rabbitmq_test.jmx index cdffc49..c357780 100644 --- a/examples/rabbitmq_test.jmx +++ b/examples/rabbitmq_test.jmx @@ -1,7 +1,7 @@ - + - + false false @@ -12,172 +12,57 @@ - stoptest + continue false - 125 + 1 - 8 - 15 - 1361373100000 - 1361373100000 + 10 + 1 + 1502397449000 + 1502397449000 false - - 999999999 - 1 - 000000000 - false - - replyToQueue - + + Test.Direct + true + false + false + Test.Queue + 100 + / + + + direct + true + false + false + false + 1000 + 1 + localhost + 5672 + guest + guest + false + true + false + 100 + Test 123456 + + + + + + + + + - - uniqueId - 0000000 - 1 - 9999999 - 3499272 - false - - - - true - false - - - - my_rpc_exchange - false - false - RPCRequestQueue - RPCMessage.Request.v1_0 - / - - - direct - true - false - false - false - 1000 - 1 - localhost - 5672 - guest - guest - false - false - false - RPCMessage.Request.v1_0 - { - "RequestMessageText": '${uniqueId}' -} - RPCMessageRequest - jMeter_${__threadNum}_${replyToQueue} - ${uniqueId} - - - - - - - my_rpc_exchange - false - false - jMeter_${__threadNum}_${replyToQueue} - RPCMessage.Request.v1_0 - / - - - direct - false - true - true - false - 1000 - 1 - localhost - 5672 - guest - guest - false - false - 0 - 10000 - false - true - - - - - false - - saveConfig - - - true - true - true - - true - true - true - true - false - true - true - false - false - false - false - false - false - false - false - 0 - true - - - - - - - false - - saveConfig - - - true - true - true - - true - true - true - true - false - true - true - false - false - false - false - false - false - false - false - 0 - true - - - - - - + false saveConfig @@ -197,13 +82,15 @@ false false false - false + true false false false - false + true 0 true + true + true From 6e3daa2c5823db66327df742767e52edf77ebd72 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 16:51:29 -0500 Subject: [PATCH 65/98] add exchanges --- jmeter-rabbitmq-setup.sh | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9fca2c7..76cabd7 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -105,7 +105,7 @@ fi -FILE="meter-plugins-manager-0.18.jar" +FILE="jmeter-plugins-manager-0.5.jar" FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" # TODO: Check if version has changed since Jan 4, 2018. if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." @@ -156,6 +156,14 @@ fi pwd java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" +FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +if [ -f $FILE ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Continuing ..." + ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +else + fancy_echo "$FILE not found. Aborting..." + exit +fi if ! command -v rabbitmq-server >/dev/null; then @@ -166,17 +174,19 @@ else fi + fancy_echo "TODO: Configure rabbitmq exchanges ..." + + + if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then - fancy_echo "rabbitmq in path already. Skipping install." + fancy_echo "rabbitmq in path. Continuing ..." else fancy_echo "Add path of rabbitmq /usr/local/sbin ..." export PATH=$PATH:/usr/local/sbin fi -## TODO: Configure RabbitMQ Exchanges etc. - fancy_echo "Starting Rabbitmq server in background using nohup ..." nohup rabbitmq-server &>/dev/null & @@ -193,11 +203,14 @@ export JMETER_FILE="rabbitmq_test" # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] - fancy_echo "Process rabbitmq_test.jtl ..." +# fancy_echo "Process rabbitmq_test.jtl ..." # subl rabbitmq_test.jtl # https://blogs.perficient.com/delivery/blog/2015/04/08/generate-performance-testing-report-with-jmeter-plugins-and-ant/ +# fancy_echo "Display run results (comparing against previous runs) ..." + + END=`date +%s` RUNTIME=$((END-BEGIN)) fancy_echo "Done in $RUNTIME seconds." \ No newline at end of file From 16c321db5dd04b695163209267210442b1e00d10 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 17:00:43 -0500 Subject: [PATCH 66/98] add extra jars --- jmeter-rabbitmq-setup.sh | 53 +++++++++++++++++++++++++++------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 76cabd7..090dc31 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -119,7 +119,6 @@ else yes | cp -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi -# NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. if ! command -v ant >/dev/null; then @@ -135,6 +134,21 @@ fi # Ant can pick up the Test.jmx file, execute it, and generate an easily-readable HTML report. + + fancy_echo "ivy java program running in ivy folder ..." + # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. + java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ + -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" +FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +if [ -f $FILE ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Continuing ..." + ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +else + fancy_echo "$FILE not found. Aborting..." + exit +fi + + FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then # file exists within folder $REPO1 fancy_echo "$FILE was created ..." @@ -152,20 +166,25 @@ fi - fancy_echo "ivy java program running in ivy folder ..." - pwd - java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ - -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" -FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" -if [ -f $FILE ]; then # file exists within folder $REPO1 - fancy_echo "$FILE found. Continuing ..." - ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" + +FILE="JMeterPlugins-Extras-1.4.0" # TODO: Check if version has changed since Jan 4, 2018. + # From https://jmeter-plugins.org/downloads/old/ +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.zip" +if [ -f $FILE_PATH.zip ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.zip else - fancy_echo "$FILE not found. Aborting..." - exit + fancy_echo "Downloading $FILE to $FOLDER ..." + curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.4.0.zip + unzip $FILE.zip + ls -al $FILE + fancy_echo "Overwriting $FILE_PATH ..." + yes | cp -rf $FILE $FILE_PATH + ls -al $FILE_PATH fi + if ! command -v rabbitmq-server >/dev/null; then fancy_echo "Installing rabbitmq-server locally as server under test ..." brew install rabbitmq @@ -173,12 +192,6 @@ else fancy_echo "rabbitmq-server already installed. Skipping install." fi - - fancy_echo "TODO: Configure rabbitmq exchanges ..." - - - - if [[ ":$PATH:" == *":$HOME/usr/local/sbin:"* ]]; then fancy_echo "rabbitmq in path. Continuing ..." else @@ -193,8 +206,14 @@ fi jobs ps + + fancy_echo "TODO: Using rabbitmq API to configure exchanges..." +# https://pulse.mozilla.org/api/ + #open http://localhost:15672 # 5672 default port (open is Mac only command) #pause 'Press [Enter] key to continue...' +curl -i -u guest:guest http://localhost:15672/api/vhosts + export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." From 7b41dcf49e0d2380ffcc0e5f4ba2caa98b70d1d7 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 17:08:02 -0500 Subject: [PATCH 67/98] add client.jar --- jmeter-rabbitmq-setup.sh | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 090dc31..76b67f7 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -134,19 +134,7 @@ fi # Ant can pick up the Test.jmx file, execute it, and generate an easily-readable HTML report. - - fancy_echo "ivy java program running in ivy folder ..." - # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages. - java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ - -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" -FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" -if [ -f $FILE ]; then # file exists within folder $REPO1 - fancy_echo "$FILE found. Continuing ..." - ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" -else - fancy_echo "$FILE not found. Aborting..." - exit -fi +# FILE="$JMETER_HOME/lib/amqp-client.jar" found. FILE="target/dist/JMeterAMQP.jar" @@ -210,9 +198,11 @@ fi fancy_echo "TODO: Using rabbitmq API to configure exchanges..." # https://pulse.mozilla.org/api/ + + #open http://localhost:15672 # 5672 default port (open is Mac only command) #pause 'Press [Enter] key to continue...' -curl -i -u guest:guest http://localhost:15672/api/vhosts +#curl -i -u guest:guest http://localhost:15672/api/vhosts export JMETER_FILE="rabbitmq_test" From 0d213eda848d9c931a5e8a0593c096bba37508c5 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 17:46:29 -0500 Subject: [PATCH 68/98] add client.jar --- jmeter-rabbitmq-setup.sh | 47 +++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 76b67f7..9ef4903 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -121,6 +121,35 @@ else fi +FILE="JMeterPlugins-Extras" # TODO: Check if version has changed since Jan 4, 2018. + # From https://jmeter-plugins.org/downloads/old/ +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.zip" +if [ -f $FILE_PATH.zip ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.zip +else + fancy_echo "Downloading $FILE to $FOLDER ..." + # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras + curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar + # 408K + fancy_echo "Overwriting $FILE_PATH ..." + yes | cp -rf $FILE $FILE_PATH + ls -al $FILE_PATH +fi + + +# FILE="JMeterPlugins-Standard" version 1.4 from Apr 2016 is latest +# See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard +# curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-standard/1.4.0/jmeter-plugins-standard-1.4.0.jar +# into $JMETER_HOME/libexec/lib/ext/ + + +# FILE="JMeterPlugins-ExtrasLibs" version 1.4 from Apr 2016 is latest +# See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras-libs +# curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras-libs/1.4.0/jmeter-plugins-extras-libs-1.4.0.jar +# into $JMETER_HOME/libexec/lib/ext/ + + if ! command -v ant >/dev/null; then fancy_echo "Installing ant utlity ..." brew install ant @@ -155,24 +184,6 @@ fi -FILE="JMeterPlugins-Extras-1.4.0" # TODO: Check if version has changed since Jan 4, 2018. - # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.zip" -if [ -f $FILE_PATH.zip ]; then # file exists within folder - fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.zip -else - fancy_echo "Downloading $FILE to $FOLDER ..." - curl -O http://jmeter-plugins.org/downloads/file/JMeterPlugins-Extras-1.4.0.zip - unzip $FILE.zip - ls -al $FILE - fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH - ls -al $FILE_PATH -fi - - - if ! command -v rabbitmq-server >/dev/null; then fancy_echo "Installing rabbitmq-server locally as server under test ..." brew install rabbitmq From c4ac20ca30f369e87f6498b3a484f2dc6f1ff871 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 18:42:07 -0500 Subject: [PATCH 69/98] add client.jar --- jmeter-rabbitmq-setup.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9ef4903..989f122 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -123,18 +123,18 @@ fi FILE="JMeterPlugins-Extras" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.zip" +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.jar" if [ -f $FILE_PATH.zip ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.zip else - fancy_echo "Downloading $FILE to $FOLDER ..." + fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar # 408K fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH - ls -al $FILE_PATH + yes | cp -rf $FILE $FILE_PATH + ls -al $FILE_PATH fi From fd71555e90c4ac3bbd672826881c0f32bc26fd63 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 18:53:12 -0500 Subject: [PATCH 70/98] add client.jar --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 989f122..512ba31 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -126,14 +126,14 @@ FILE="JMeterPlugins-Extras" # TODO: Check if version has changed since Jan 4, 2 FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.jar" if [ -f $FILE_PATH.zip ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.zip + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.jar else - fancy_echo "Downloading $FILE_PATH ..." + fancy_echo "Downloading $FILE_PATH.jar ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar # 408K fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH + yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi From 88719ef7ab8a5c53181de60d34d8f8a0cff1984b Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 9 Jan 2018 19:38:09 -0500 Subject: [PATCH 71/98] add client.jar --- jmeter-rabbitmq-setup.sh | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 512ba31..7ed8e41 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -121,14 +121,14 @@ else fi -FILE="JMeterPlugins-Extras" # TODO: Check if version has changed since Jan 4, 2018. +FILE="JMeterPlugins-Extras-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE.jar" -if [ -f $FILE_PATH.zip ]; then # file exists within folder +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE.jar + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE else - fancy_echo "Downloading $FILE_PATH.jar ..." + fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar # 408K From 43e045bebed19bf0d22f219fa85dfe576f1ff356 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:12:25 -0500 Subject: [PATCH 72/98] add client.jar --- jmeter-rabbitmq-setup.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 7ed8e41..beb84bb 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -131,8 +131,10 @@ else fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar - # 408K + # 285K fancy_echo "Overwriting $FILE_PATH ..." + echo FILE=$FILE + echo FILE_PATH=$FILE_PATH yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi From 13c2c984b87d74e2cc04a0182a689afb4db42d0b Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:32:51 -0500 Subject: [PATCH 73/98] add client.jar --- jmeter-rabbitmq-setup.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index beb84bb..46254b5 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -121,7 +121,7 @@ else fi -FILE="JMeterPlugins-Extras-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. +FILE="jmeter-plugins-extras-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" if [ -f $FILE_PATH ]; then # file exists within folder @@ -131,14 +131,14 @@ else fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar - # 285K + # 400K received. fancy_echo "Overwriting $FILE_PATH ..." - echo FILE=$FILE - echo FILE_PATH=$FILE_PATH yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi +/usr/local/Cellar/jmeter/3.3/libexec/lib/ext +/usr/local/Cellar/jmeter/3.3/libexec/lib/ext/JMeterPlugins-Extras-1.4.0.jar # FILE="JMeterPlugins-Standard" version 1.4 from Apr 2016 is latest # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard From a5a838a297baa383d9b2bbbf8c4690266008ec95 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:37:28 -0500 Subject: [PATCH 74/98] add client.jar --- jmeter-rabbitmq-setup.sh | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 46254b5..2f7408b 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -116,7 +116,7 @@ else curl -O http://jmeter-plugins.org/downloads/file/$FILE ls -al $FILE fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH + yes | mv -rf $FILE $FILE_PATH ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE fi @@ -133,12 +133,10 @@ else curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar # 400K received. fancy_echo "Overwriting $FILE_PATH ..." - yes | cp -rf $FILE $FILE_PATH + yes | mv -rf $FILE $FILE_PATH ls -al $FILE_PATH fi -/usr/local/Cellar/jmeter/3.3/libexec/lib/ext -/usr/local/Cellar/jmeter/3.3/libexec/lib/ext/JMeterPlugins-Extras-1.4.0.jar # FILE="JMeterPlugins-Standard" version 1.4 from Apr 2016 is latest # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard From acc43fa85b5faa892e1267a307fca5a26aaf623b Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:48:10 -0500 Subject: [PATCH 75/98] add standard --- jmeter-rabbitmq-setup.sh | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 2f7408b..75d3665 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -138,16 +138,39 @@ else fi -# FILE="JMeterPlugins-Standard" version 1.4 from Apr 2016 is latest -# See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard -# curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-standard/1.4.0/jmeter-plugins-standard-1.4.0.jar -# into $JMETER_HOME/libexec/lib/ext/ +FILE="jmeter-plugins-standard-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. + # From https://jmeter-plugins.org/downloads/old/ +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +if [ -f $FILE_PATH ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE +else + fancy_echo "Downloading $FILE_PATH ..." + # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard + curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-standard/1.4.0/jmeter-plugins-standard-1.4.0.jar + # 400K received. + fancy_echo "Overwriting $FILE_PATH ..." + yes | mv -rf $FILE $FILE_PATH + ls -al $FILE_PATH +fi + +FILE="jmeter-plugins-extras-libs-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. + # From https://jmeter-plugins.org/downloads/old/ +FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +if [ -f $FILE_PATH ]; then # file exists within folder + fancy_echo "$FILE already installed. Skipping install." + ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE +else + fancy_echo "Downloading $FILE_PATH ..." + # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras-libs + curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras-libs/1.4.0/jmeter-plugins-extras-libs-1.4.0.jar + # 400K received. + fancy_echo "Overwriting $FILE_PATH ..." + yes | mv -rf $FILE $FILE_PATH + ls -al $FILE_PATH +fi -# FILE="JMeterPlugins-ExtrasLibs" version 1.4 from Apr 2016 is latest -# See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras-libs -# curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras-libs/1.4.0/jmeter-plugins-extras-libs-1.4.0.jar -# into $JMETER_HOME/libexec/lib/ext/ if ! command -v ant >/dev/null; then From 6a9e549ca0b8c0862426eb11ea0dbd1daaebbb73 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:56:25 -0500 Subject: [PATCH 76/98] rename jars --- jmeter-rabbitmq-setup.sh | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 75d3665..85fa94e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -105,28 +105,27 @@ fi -FILE="jmeter-plugins-manager-0.5.jar" -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" # TODO: Check if version has changed since Jan 4, 2018. +FILE="jmeter-plugins-manager-0.5.jar" # TODO: Check if version has changed since Jan 4, 2018. +FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-manager.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE + ls -al $FILE_PATH else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ curl -O http://jmeter-plugins.org/downloads/file/$FILE - ls -al $FILE fancy_echo "Overwriting $FILE_PATH ..." yes | mv -rf $FILE $FILE_PATH - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE + ls -al $FILE_PATH fi FILE="jmeter-plugins-extras-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-extras.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE + ls -al $FILE_PATH else fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras @@ -140,10 +139,10 @@ fi FILE="jmeter-plugins-standard-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-standard.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE + ls -al $FILE_PATH else fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-standard @@ -157,10 +156,10 @@ fi FILE="jmeter-plugins-extras-libs-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ -FILE_PATH="$JMETER_HOME/libexec/lib/ext/$FILE" +FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-extras-libs.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." - ls -al $JMETER_HOME/libexec/lib/ext | grep $FILE + ls -al $FILE_PATH else fancy_echo "Downloading $FILE_PATH ..." # See https://mvnrepository.com/artifact/kg.apc/jmeter-plugins-extras-libs From 152269b9e29b159a4b7c6ff42a228824d2a2f2e1 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 08:59:43 -0500 Subject: [PATCH 77/98] rename jars --- jmeter-rabbitmq-setup.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 85fa94e..90b4f5f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -113,9 +113,9 @@ if [ -f $FILE_PATH ]; then # file exists within folder else fancy_echo "Downloading $FILE to $FOLDER ..." # From https://jmeter-plugins.org/wiki/StandardSet/ - curl -O http://jmeter-plugins.org/downloads/file/$FILE + curl -O http://jmeter-plugins.org/downloads/file/$FILE # 994 received. fancy_echo "Overwriting $FILE_PATH ..." - yes | mv -rf $FILE $FILE_PATH + yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi @@ -139,6 +139,7 @@ fi FILE="jmeter-plugins-standard-1.4.0.jar" # TODO: Check if version has changed since Jan 4, 2018. # From https://jmeter-plugins.org/downloads/old/ + # From https://jmeter-plugins.org/downloads/file/JMeterPlugins-Standard-1.4.0.zip FILE_PATH="$JMETER_HOME/libexec/lib/ext/jmeter-plugins-standard.jar" if [ -f $FILE_PATH ]; then # file exists within folder fancy_echo "$FILE already installed. Skipping install." From 29581a94fb4be03a44b40b5a327f031010a8e181 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 10 Jan 2018 09:00:26 -0500 Subject: [PATCH 78/98] rename jars --- jmeter-rabbitmq-setup.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 90b4f5f..fce1c9f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -132,7 +132,7 @@ else curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras/1.4.0/jmeter-plugins-extras-1.4.0.jar # 400K received. fancy_echo "Overwriting $FILE_PATH ..." - yes | mv -rf $FILE $FILE_PATH + yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi @@ -150,7 +150,7 @@ else curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-standard/1.4.0/jmeter-plugins-standard-1.4.0.jar # 400K received. fancy_echo "Overwriting $FILE_PATH ..." - yes | mv -rf $FILE $FILE_PATH + yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi @@ -167,7 +167,7 @@ else curl -O http://central.maven.org/maven2/kg/apc/jmeter-plugins-extras-libs/1.4.0/jmeter-plugins-extras-libs-1.4.0.jar # 400K received. fancy_echo "Overwriting $FILE_PATH ..." - yes | mv -rf $FILE $FILE_PATH + yes | cp -rf $FILE $FILE_PATH ls -al $FILE_PATH fi From d41b7ec0c1433002e6f44cc7d82e40cbf3140396 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 04:37:47 -0500 Subject: [PATCH 79/98] client add back --- jmeter-rabbitmq-setup.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index fce1c9f..bf4a9bc 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -186,7 +186,19 @@ fi # Ant can pick up the Test.jmx file, execute it, and generate an easily-readable HTML report. -# FILE="$JMETER_HOME/lib/amqp-client.jar" found. + fancy_echo "ivy java program running in ivy folder ..." + # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages? + # Download: + java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ + -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" +# FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +if [ -f $FILE ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Continuing ..." + ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +else + fancy_echo "$FILE not downloaded correctly. Aborting..." + exit +fi FILE="target/dist/JMeterAMQP.jar" @@ -233,6 +245,7 @@ fi # https://pulse.mozilla.org/api/ +pause( "Press [Enter] to continue." ) #open http://localhost:15672 # 5672 default port (open is Mac only command) #pause 'Press [Enter] key to continue...' From 9a7697a7fc7c297cd8fef28d21097296e783ec47 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 08:12:56 -0500 Subject: [PATCH 80/98] client jar --- jmeter-rabbitmq-setup.sh | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index bf4a9bc..a0a0fb9 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -186,21 +186,22 @@ fi # Ant can pick up the Test.jmx file, execute it, and generate an easily-readable HTML report. - fancy_echo "ivy java program running in ivy folder ..." +FILE="amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. +FILE_PATH="$JMETER_HOME/lib/amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. +if [ -f $FILE_PATH ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Continuing ..." + ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" +else + fancy_echo "Downloading $FILE_PATH ..." # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages? # Download: java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" -# FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" -if [ -f $FILE ]; then # file exists within folder $REPO1 - fancy_echo "$FILE found. Continuing ..." - ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" -else - fancy_echo "$FILE not downloaded correctly. Aborting..." - exit + ls -al $FILE_PATH fi + FILE="target/dist/JMeterAMQP.jar" if [ -f $FILE ]; then # file exists within folder $REPO1 fancy_echo "$FILE was created ..." From 304cb9108a146b48a0a6b4400552578d2987b080 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 10:19:51 -0500 Subject: [PATCH 81/98] .ivy2 --- jmeter-rabbitmq-setup.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index a0a0fb9..73387d6 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -197,6 +197,7 @@ else # Download: java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" + cp ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From a1fbfa313d091112d52581588f674eb76e5eebc3 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 10:21:50 -0500 Subject: [PATCH 82/98] .ivy2 --- jmeter-rabbitmq-setup.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 73387d6..6b9bf22 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -197,6 +197,7 @@ else # Download: java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" + # found using command: find / -name abc.dmg cp ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From 9df971f8edd3af93cb7c128516a7ae8ad776cb50 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 10:27:31 -0500 Subject: [PATCH 83/98] Add filename --- jmeter-rabbitmq-setup.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 6b9bf22..d989bb1 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -23,8 +23,8 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e BEGIN=`date +%s` - -fancy_echo "Starting jmeter-rabbitmq-setup.sh on $OSTYPE ................................." +export filename="jmeter-rabbitmq-setup.sh" # this Bash shell script file. +fancy_echo "Starting $FILENAME on $OSTYPE ................................." # clear sw_vers # ProductName: Mac OS X @@ -92,6 +92,7 @@ fi cd $REPO1 pwd #tree + echo "$(git log -1 --format="%ad" -- $filename) $filename" if ! command -v tree >/dev/null; then From a96381fb1cbe16f0e2439d17591d4fbf268dd21c Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 10:29:27 -0500 Subject: [PATCH 84/98] Cap filename --- jmeter-rabbitmq-setup.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index d989bb1..b2afa81 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -23,7 +23,7 @@ trap 'ret=$?; test $ret -ne 0 && printf "failed\n\n" >&2; exit $ret' EXIT set -e BEGIN=`date +%s` -export filename="jmeter-rabbitmq-setup.sh" # this Bash shell script file. +export FILENAME="jmeter-rabbitmq-setup.sh" # this Bash shell script file. fancy_echo "Starting $FILENAME on $OSTYPE ................................." # clear sw_vers @@ -92,7 +92,7 @@ fi cd $REPO1 pwd #tree - echo "$(git log -1 --format="%ad" -- $filename) $filename" + echo "$(git log -1 --format="%ad" -- $FILENAME) $FILENAME" if ! command -v tree >/dev/null; then From 14d448fa22bf8d32d3e43fc29156a87b672e3b2c Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 10:30:54 -0500 Subject: [PATCH 85/98] find file --- jmeter-rabbitmq-setup.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b2afa81..1dc154b 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -198,7 +198,9 @@ else # Download: java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" - # found using command: find / -name abc.dmg + + # found using command: + find / -name amqp-client-3.6.1.jar cp ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From 14259e36197c1c4b70314d93161b8a39bd5d120f Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 14:31:59 -0500 Subject: [PATCH 86/98] ugh --- jmeter-rabbitmq-setup.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 1dc154b..a7e7e7c 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -199,8 +199,7 @@ else java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" - # found using command: - find / -name amqp-client-3.6.1.jar + # found using command: find / -name amqp-client-3.6.1.jar cp ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From 5d1a5a286c0ad97980f0a66600472674d96e8043 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 14:50:32 -0500 Subject: [PATCH 87/98] cp rf --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index a7e7e7c..b3dd9fd 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -200,7 +200,7 @@ else -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" # found using command: find / -name amqp-client-3.6.1.jar - cp ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH + yes | cp -rf ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From 260bf54bcbca0556ad8d63739c823cbd5789f645 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 15:46:23 -0500 Subject: [PATCH 88/98] add libexec --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b3dd9fd..2c80aac 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -188,7 +188,7 @@ fi FILE="amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. -FILE_PATH="$JMETER_HOME/lib/amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. +FILE_PATH="$JMETER_HOME/libexec/lib/amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. if [ -f $FILE_PATH ]; then # file exists within folder $REPO1 fancy_echo "$FILE found. Continuing ..." ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" From 33e2f3a3c0fb3c0e8e35a72cfe2fe1d8342534af Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 15:48:18 -0500 Subject: [PATCH 89/98] add libexec --- jmeter-rabbitmq-setup.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 2c80aac..b3d43b4 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -197,10 +197,11 @@ else # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages? # Download: java -jar ivy/ivy.jar -dependency com.rabbitmq amqp-client 3.6.1 \ - -retrieve "$JMETER_HOME/lab/[artifact](-[classifier]).[ext]" + -retrieve "$JMETER_HOME/libexec/lab/[artifact](-[classifier]).[ext]" # found using command: find / -name amqp-client-3.6.1.jar - yes | cp -rf ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH + #yes | cp -rf ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH + ls -al $FILE_PATH fi From 2d19bd86865f89a543d6c6cf498d03a981affe1f Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 15:53:27 -0500 Subject: [PATCH 90/98] cp from ivy2 --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index b3d43b4..295239e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -200,7 +200,7 @@ else -retrieve "$JMETER_HOME/libexec/lab/[artifact](-[classifier]).[ext]" # found using command: find / -name amqp-client-3.6.1.jar - #yes | cp -rf ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH + yes | cp -rf ~/.ivy2/cache/com.rabbitmq/amqp-client/jars/amqp-client-3.6.1.jar $FILE_PATH ls -al $FILE_PATH fi From e14b91a27a02a8d96ec080bf5ffcf9549775e992 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 17:43:50 -0500 Subject: [PATCH 91/98] ls fix --- jmeter-rabbitmq-setup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 295239e..3a3e56f 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -191,7 +191,7 @@ FILE="amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, FILE_PATH="$JMETER_HOME/libexec/lib/amqp-client-3.6.1.jar" # TODO: Check if version has changed since Jan 4, 2018. if [ -f $FILE_PATH ]; then # file exists within folder $REPO1 fancy_echo "$FILE found. Continuing ..." - ls -al FILE="$JMETER_HOME/lib/amqp-client-3.6.1.jar" + ls -al $FILE_PATH else fancy_echo "Downloading $FILE_PATH ..." # NOTE: JMeterPlugins-Extras-1.4.0.zip now incorporated into Packages? From 6407d3770b578eba9132c43a47391025d32a23bc Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 17:48:43 -0500 Subject: [PATCH 92/98] remove pause --- jmeter-rabbitmq-setup.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 3a3e56f..be92312 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -247,11 +247,12 @@ fi ps - fancy_echo "TODO: Using rabbitmq API to configure exchanges..." +# TODO: Copy in rebbitmq configuration file. << Praveen? +# fancy_echo "TODO: Alternative: Use rabbitmq API to configure exchanges..." # https://pulse.mozilla.org/api/ -pause( "Press [Enter] to continue." ) +#FIX: pause( "Press [Enter] to continue." ) #open http://localhost:15672 # 5672 default port (open is Mac only command) #pause 'Press [Enter] key to continue...' From 9a516e2acb654d5b6c883b2608972bc9c845e982 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 17:53:23 -0500 Subject: [PATCH 93/98] jtl --- jmeter-rabbitmq-setup.sh | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index be92312..00e8e19 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -261,7 +261,7 @@ fi export JMETER_FILE="rabbitmq_test" fancy_echo "Starting JMeter in background for $JMETER_FILE ..." - ls -al examples/rabbitmq_test.jmx + ls -al examples/$JMETER_FILE.jmx $JMETER_HOME/libexec/bin/jmeter.sh -n -t examples/rabbitmq_test.jmx -l rabbitmq_test.jtl # nohup "./jmeter.sh -n -t $REPO1/examples/rabbitmq_test.jmx -l result.jtl" > /dev/null 2>&1 & # -n for NON-GUI mode jmeter -n -t [jmx file] -l [results file] -e -o [Path to output folder] @@ -271,6 +271,15 @@ export JMETER_FILE="rabbitmq_test" # https://blogs.perficient.com/delivery/blog/2015/04/08/generate-performance-testing-report-with-jmeter-plugins-and-ant/ +FILE="$JMETER_FILE.jtl" # created above by JMeter in the current folder (.gitignore'd) +if [ -f $FILE_PATH ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Continuing ..." + ls -al $FILE +else + fancy_echo "JMeter output $FILE not found. Run failed ..." + abort +fi + # fancy_echo "Display run results (comparing against previous runs) ..." From 2c1fa12e5e60084f2f9940a9c16e12827e07dfed Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 18:09:00 -0500 Subject: [PATCH 94/98] jtl to csv --- jmeter-rabbitmq-setup.sh | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 00e8e19..8715a32 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -272,9 +272,17 @@ export JMETER_FILE="rabbitmq_test" FILE="$JMETER_FILE.jtl" # created above by JMeter in the current folder (.gitignore'd) -if [ -f $FILE_PATH ]; then # file exists within folder $REPO1 - fancy_echo "$FILE found. Continuing ..." +if [ -f $FILE ]; then # file exists within folder $REPO1 + fancy_echo "$FILE found. Displaying ..." ls -al $FILE + # Rename to .CSV for a spreadsheet program to open: # libreoffice --calc $FILE + yes | cp -rf $JMETER_FILE.jtl $JMETER_FILE.csv + open $JMETER_FILE.csv -a "Microsoft Excel" + # // or open rabbitmq_test.jtl -a "Microsoft Excel" + # Example contents: + # timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect + # 1516143497026,2,AMQP Publisher,200,OK,Thread Group 1-1,text,true,,11,0,1,1,0,0,0 + else fancy_echo "JMeter output $FILE not found. Run failed ..." abort From 189941fe4a6d6cd587777241b3ff70932e18a87f Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 16 Jan 2018 18:12:42 -0500 Subject: [PATCH 95/98] delete csv --- jmeter-rabbitmq-setup.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 8715a32..db9d01e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -278,11 +278,10 @@ if [ -f $FILE ]; then # file exists within folder $REPO1 # Rename to .CSV for a spreadsheet program to open: # libreoffice --calc $FILE yes | cp -rf $JMETER_FILE.jtl $JMETER_FILE.csv open $JMETER_FILE.csv -a "Microsoft Excel" - # // or open rabbitmq_test.jtl -a "Microsoft Excel" # Example contents: # timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect # 1516143497026,2,AMQP Publisher,200,OK,Thread Group 1-1,text,true,,11,0,1,1,0,0,0 - + rm $JMETER_FILE.csv else fancy_echo "JMeter output $FILE not found. Run failed ..." abort From c86045e6e4ba8722a0808355ace66c1c60610a34 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Wed, 17 Jan 2018 05:02:57 -0500 Subject: [PATCH 96/98] Excel msg --- jmeter-rabbitmq-setup.sh | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index db9d01e..9d3163e 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -273,8 +273,9 @@ export JMETER_FILE="rabbitmq_test" FILE="$JMETER_FILE.jtl" # created above by JMeter in the current folder (.gitignore'd) if [ -f $FILE ]; then # file exists within folder $REPO1 - fancy_echo "$FILE found. Displaying ..." + fancy_echo "$FILE found. Copying .csv for display in Excel ..." ls -al $FILE + # TODO: Check if Microsoft Excel is installed: # Rename to .CSV for a spreadsheet program to open: # libreoffice --calc $FILE yes | cp -rf $JMETER_FILE.jtl $JMETER_FILE.csv open $JMETER_FILE.csv -a "Microsoft Excel" @@ -287,9 +288,9 @@ else abort fi -# fancy_echo "Display run results (comparing against previous runs) ..." +# fancy_echo "TODO: Display run results (comparing against previous runs) ..." END=`date +%s` RUNTIME=$((END-BEGIN)) -fancy_echo "Done in $RUNTIME seconds." \ No newline at end of file +fancy_echo "Done in $RUNTIME seconds." From bee3c94573dcb5f1cf7f4a0bb99a6b7c0799efd2 Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 23 Jan 2018 15:36:14 -0500 Subject: [PATCH 97/98] add rabbitmq calls --- jmeter-rabbitmq-setup.sh | 27 + node_modules/amqplib/CHANGELOG.md | 234 + node_modules/amqplib/LICENSE | 6 + node_modules/amqplib/LICENSE-MIT | 21 + node_modules/amqplib/Makefile | 46 + node_modules/amqplib/README.md | 157 + node_modules/amqplib/callback_api.js | 22 + node_modules/amqplib/channel_api.js | 16 + node_modules/amqplib/examples/headers.js | 42 + .../amqplib/examples/receive_generator.js | 39 + .../amqplib/examples/send_generators.js | 42 + node_modules/amqplib/examples/ssl.js | 64 + .../amqplib/examples/tutorials/README.md | 93 + .../tutorials/callback_api/emit_log.js | 28 + .../tutorials/callback_api/emit_log_direct.js | 30 + .../tutorials/callback_api/emit_log_topic.js | 27 + .../tutorials/callback_api/new_task.js | 27 + .../tutorials/callback_api/receive.js | 30 + .../tutorials/callback_api/receive_logs.js | 36 + .../callback_api/receive_logs_direct.js | 56 + .../callback_api/receive_logs_topic.js | 55 + .../tutorials/callback_api/rpc_client.js | 49 + .../tutorials/callback_api/rpc_server.js | 45 + .../examples/tutorials/callback_api/send.js | 29 + .../examples/tutorials/callback_api/worker.js | 35 + .../amqplib/examples/tutorials/emit_log.js | 19 + .../examples/tutorials/emit_log_direct.js | 20 + .../examples/tutorials/emit_log_topic.js | 19 + .../amqplib/examples/tutorials/new_task.js | 18 + .../amqplib/examples/tutorials/package.json | 16 + .../amqplib/examples/tutorials/receive.js | 21 + .../examples/tutorials/receive_logs.js | 28 + .../examples/tutorials/receive_logs_direct.js | 45 + .../examples/tutorials/receive_logs_topic.js | 44 + .../amqplib/examples/tutorials/rpc_client.js | 53 + .../amqplib/examples/tutorials/rpc_server.js | 39 + .../amqplib/examples/tutorials/send.js | 23 + .../amqplib/examples/tutorials/worker.js | 28 + .../amqplib/examples/waitForConfirms.js | 22 + node_modules/amqplib/package.json | 70 + node_modules/amqplib/test/bitset.js | 68 + node_modules/amqplib/test/callback_api.js | 313 + node_modules/amqplib/test/channel.js | 612 ++ node_modules/amqplib/test/channel_api.js | 584 ++ node_modules/amqplib/test/codec.js | 238 + node_modules/amqplib/test/connect.js | 127 + node_modules/amqplib/test/connection.js | 391 ++ node_modules/amqplib/test/data.js | 255 + node_modules/amqplib/test/frame.js | 199 + node_modules/amqplib/test/mux.js | 166 + node_modules/amqplib/test/util.js | 220 + node_modules/bitsyntax/.npmignore | 3 + node_modules/bitsyntax/.travis.yml | 7 + node_modules/bitsyntax/Makefile | 15 + node_modules/bitsyntax/README.md | 306 + node_modules/bitsyntax/index.js | 10 + node_modules/bitsyntax/package.json | 57 + node_modules/bitsyntax/test/consing.js | 45 + node_modules/bitsyntax/test/matching.js | 187 + node_modules/bluebird/LICENSE | 21 + node_modules/bluebird/README.md | 52 + node_modules/bluebird/changelog.md | 1 + .../bluebird/js/browser/bluebird.core.js | 3781 +++++++++++ .../bluebird/js/browser/bluebird.core.min.js | 31 + node_modules/bluebird/js/browser/bluebird.js | 5623 +++++++++++++++++ .../bluebird/js/browser/bluebird.min.js | 31 + node_modules/bluebird/js/release/any.js | 21 + node_modules/bluebird/js/release/assert.js | 55 + node_modules/bluebird/js/release/async.js | 161 + node_modules/bluebird/js/release/bind.js | 67 + node_modules/bluebird/js/release/bluebird.js | 11 + node_modules/bluebird/js/release/call_get.js | 123 + node_modules/bluebird/js/release/cancel.js | 129 + .../bluebird/js/release/catch_filter.js | 42 + node_modules/bluebird/js/release/context.js | 69 + .../bluebird/js/release/debuggability.js | 919 +++ .../bluebird/js/release/direct_resolve.js | 46 + node_modules/bluebird/js/release/each.js | 30 + node_modules/bluebird/js/release/errors.js | 116 + node_modules/bluebird/js/release/es5.js | 80 + node_modules/bluebird/js/release/filter.js | 12 + node_modules/bluebird/js/release/finally.js | 146 + .../bluebird/js/release/generators.js | 223 + node_modules/bluebird/js/release/join.js | 168 + node_modules/bluebird/js/release/map.js | 168 + node_modules/bluebird/js/release/method.js | 55 + node_modules/bluebird/js/release/nodeback.js | 51 + node_modules/bluebird/js/release/nodeify.js | 58 + node_modules/bluebird/js/release/promise.js | 775 +++ .../bluebird/js/release/promise_array.js | 185 + node_modules/bluebird/js/release/promisify.js | 314 + node_modules/bluebird/js/release/props.js | 118 + node_modules/bluebird/js/release/queue.js | 73 + node_modules/bluebird/js/release/race.js | 49 + node_modules/bluebird/js/release/reduce.js | 172 + node_modules/bluebird/js/release/schedule.js | 61 + node_modules/bluebird/js/release/settle.js | 43 + node_modules/bluebird/js/release/some.js | 148 + .../js/release/synchronous_inspection.js | 103 + node_modules/bluebird/js/release/thenables.js | 86 + node_modules/bluebird/js/release/timers.js | 93 + node_modules/bluebird/js/release/using.js | 226 + node_modules/bluebird/js/release/util.js | 380 ++ node_modules/bluebird/package.json | 101 + node_modules/buffer-more-ints/.npmignore | 2 + node_modules/buffer-more-ints/LICENSE | 19 + node_modules/buffer-more-ints/README.md | 68 + .../buffer-more-ints-tests.js | 207 + .../buffer-more-ints/buffer-more-ints.js | 472 ++ node_modules/buffer-more-ints/package.json | 50 + node_modules/buffer-more-ints/polyfill.js | 71 + node_modules/core-util-is/LICENSE | 19 + node_modules/core-util-is/README.md | 3 + node_modules/core-util-is/float.patch | 604 ++ node_modules/core-util-is/package.json | 62 + node_modules/core-util-is/test.js | 68 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 7 + node_modules/inherits/inherits_browser.js | 23 + node_modules/inherits/package.json | 61 + node_modules/isarray/README.md | 54 + node_modules/isarray/build/build.js | 209 + node_modules/isarray/component.json | 19 + node_modules/isarray/index.js | 3 + node_modules/isarray/package.json | 57 + node_modules/readable-stream/.npmignore | 5 + node_modules/readable-stream/LICENSE | 18 + node_modules/readable-stream/README.md | 15 + node_modules/readable-stream/duplex.js | 1 + node_modules/readable-stream/float.patch | 923 +++ node_modules/readable-stream/package.json | 65 + node_modules/readable-stream/passthrough.js | 1 + node_modules/readable-stream/readable.js | 10 + node_modules/readable-stream/transform.js | 1 + node_modules/readable-stream/writable.js | 1 + node_modules/safe-buffer/.travis.yml | 7 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 ++ node_modules/safe-buffer/index.js | 62 + node_modules/safe-buffer/package.json | 62 + node_modules/safe-buffer/test.js | 101 + node_modules/string_decoder/.npmignore | 2 + node_modules/string_decoder/LICENSE | 20 + node_modules/string_decoder/README.md | 7 + node_modules/string_decoder/index.js | 221 + node_modules/string_decoder/package.json | 53 + package-lock.json | 72 + 148 files changed, 25129 insertions(+) create mode 100644 node_modules/amqplib/CHANGELOG.md create mode 100644 node_modules/amqplib/LICENSE create mode 100644 node_modules/amqplib/LICENSE-MIT create mode 100644 node_modules/amqplib/Makefile create mode 100644 node_modules/amqplib/README.md create mode 100644 node_modules/amqplib/callback_api.js create mode 100644 node_modules/amqplib/channel_api.js create mode 100755 node_modules/amqplib/examples/headers.js create mode 100644 node_modules/amqplib/examples/receive_generator.js create mode 100755 node_modules/amqplib/examples/send_generators.js create mode 100644 node_modules/amqplib/examples/ssl.js create mode 100644 node_modules/amqplib/examples/tutorials/README.md create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/new_task.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/send.js create mode 100755 node_modules/amqplib/examples/tutorials/callback_api/worker.js create mode 100755 node_modules/amqplib/examples/tutorials/emit_log.js create mode 100755 node_modules/amqplib/examples/tutorials/emit_log_direct.js create mode 100755 node_modules/amqplib/examples/tutorials/emit_log_topic.js create mode 100755 node_modules/amqplib/examples/tutorials/new_task.js create mode 100644 node_modules/amqplib/examples/tutorials/package.json create mode 100755 node_modules/amqplib/examples/tutorials/receive.js create mode 100755 node_modules/amqplib/examples/tutorials/receive_logs.js create mode 100755 node_modules/amqplib/examples/tutorials/receive_logs_direct.js create mode 100755 node_modules/amqplib/examples/tutorials/receive_logs_topic.js create mode 100755 node_modules/amqplib/examples/tutorials/rpc_client.js create mode 100755 node_modules/amqplib/examples/tutorials/rpc_server.js create mode 100755 node_modules/amqplib/examples/tutorials/send.js create mode 100755 node_modules/amqplib/examples/tutorials/worker.js create mode 100644 node_modules/amqplib/examples/waitForConfirms.js create mode 100644 node_modules/amqplib/package.json create mode 100644 node_modules/amqplib/test/bitset.js create mode 100644 node_modules/amqplib/test/callback_api.js create mode 100644 node_modules/amqplib/test/channel.js create mode 100644 node_modules/amqplib/test/channel_api.js create mode 100644 node_modules/amqplib/test/codec.js create mode 100644 node_modules/amqplib/test/connect.js create mode 100644 node_modules/amqplib/test/connection.js create mode 100644 node_modules/amqplib/test/data.js create mode 100644 node_modules/amqplib/test/frame.js create mode 100644 node_modules/amqplib/test/mux.js create mode 100644 node_modules/amqplib/test/util.js create mode 100644 node_modules/bitsyntax/.npmignore create mode 100644 node_modules/bitsyntax/.travis.yml create mode 100644 node_modules/bitsyntax/Makefile create mode 100644 node_modules/bitsyntax/README.md create mode 100644 node_modules/bitsyntax/index.js create mode 100644 node_modules/bitsyntax/package.json create mode 100644 node_modules/bitsyntax/test/consing.js create mode 100644 node_modules/bitsyntax/test/matching.js create mode 100644 node_modules/bluebird/LICENSE create mode 100644 node_modules/bluebird/README.md create mode 100644 node_modules/bluebird/changelog.md create mode 100644 node_modules/bluebird/js/browser/bluebird.core.js create mode 100644 node_modules/bluebird/js/browser/bluebird.core.min.js create mode 100644 node_modules/bluebird/js/browser/bluebird.js create mode 100644 node_modules/bluebird/js/browser/bluebird.min.js create mode 100644 node_modules/bluebird/js/release/any.js create mode 100644 node_modules/bluebird/js/release/assert.js create mode 100644 node_modules/bluebird/js/release/async.js create mode 100644 node_modules/bluebird/js/release/bind.js create mode 100644 node_modules/bluebird/js/release/bluebird.js create mode 100644 node_modules/bluebird/js/release/call_get.js create mode 100644 node_modules/bluebird/js/release/cancel.js create mode 100644 node_modules/bluebird/js/release/catch_filter.js create mode 100644 node_modules/bluebird/js/release/context.js create mode 100644 node_modules/bluebird/js/release/debuggability.js create mode 100644 node_modules/bluebird/js/release/direct_resolve.js create mode 100644 node_modules/bluebird/js/release/each.js create mode 100644 node_modules/bluebird/js/release/errors.js create mode 100644 node_modules/bluebird/js/release/es5.js create mode 100644 node_modules/bluebird/js/release/filter.js create mode 100644 node_modules/bluebird/js/release/finally.js create mode 100644 node_modules/bluebird/js/release/generators.js create mode 100644 node_modules/bluebird/js/release/join.js create mode 100644 node_modules/bluebird/js/release/map.js create mode 100644 node_modules/bluebird/js/release/method.js create mode 100644 node_modules/bluebird/js/release/nodeback.js create mode 100644 node_modules/bluebird/js/release/nodeify.js create mode 100644 node_modules/bluebird/js/release/promise.js create mode 100644 node_modules/bluebird/js/release/promise_array.js create mode 100644 node_modules/bluebird/js/release/promisify.js create mode 100644 node_modules/bluebird/js/release/props.js create mode 100644 node_modules/bluebird/js/release/queue.js create mode 100644 node_modules/bluebird/js/release/race.js create mode 100644 node_modules/bluebird/js/release/reduce.js create mode 100644 node_modules/bluebird/js/release/schedule.js create mode 100644 node_modules/bluebird/js/release/settle.js create mode 100644 node_modules/bluebird/js/release/some.js create mode 100644 node_modules/bluebird/js/release/synchronous_inspection.js create mode 100644 node_modules/bluebird/js/release/thenables.js create mode 100644 node_modules/bluebird/js/release/timers.js create mode 100644 node_modules/bluebird/js/release/using.js create mode 100644 node_modules/bluebird/js/release/util.js create mode 100644 node_modules/bluebird/package.json create mode 100644 node_modules/buffer-more-ints/.npmignore create mode 100644 node_modules/buffer-more-ints/LICENSE create mode 100644 node_modules/buffer-more-ints/README.md create mode 100644 node_modules/buffer-more-ints/buffer-more-ints-tests.js create mode 100644 node_modules/buffer-more-ints/buffer-more-ints.js create mode 100644 node_modules/buffer-more-ints/package.json create mode 100644 node_modules/buffer-more-ints/polyfill.js create mode 100644 node_modules/core-util-is/LICENSE create mode 100644 node_modules/core-util-is/README.md create mode 100644 node_modules/core-util-is/float.patch create mode 100644 node_modules/core-util-is/package.json create mode 100644 node_modules/core-util-is/test.js create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/isarray/README.md create mode 100644 node_modules/isarray/build/build.js create mode 100644 node_modules/isarray/component.json create mode 100644 node_modules/isarray/index.js create mode 100644 node_modules/isarray/package.json create mode 100644 node_modules/readable-stream/.npmignore create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/duplex.js create mode 100644 node_modules/readable-stream/float.patch create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/passthrough.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/readable-stream/transform.js create mode 100644 node_modules/readable-stream/writable.js create mode 100644 node_modules/safe-buffer/.travis.yml create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/safe-buffer/test.js create mode 100644 node_modules/string_decoder/.npmignore create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/index.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 package-lock.json diff --git a/jmeter-rabbitmq-setup.sh b/jmeter-rabbitmq-setup.sh index 9d3163e..e8def68 100755 --- a/jmeter-rabbitmq-setup.sh +++ b/jmeter-rabbitmq-setup.sh @@ -247,10 +247,37 @@ fi ps + # TODO: Copy in rebbitmq configuration file. << Praveen? # fancy_echo "TODO: Alternative: Use rabbitmq API to configure exchanges..." # https://pulse.mozilla.org/api/ +# sudo rabbitmqctl list_queues + + + fancy_echo "Add vHost..." +curl -i -u guest:guest -H "content-type:application/json" \ + -XPUT http://localhost:15672/api/vhosts/foo + + + fancy_echo "Create new exchange in the default virtual Rabbitmq host ..." +curl -i -u guest:guest -H "content-type:application/json" \ + -XPUT -d'{"type":"direct","durable":true}' \ + http://localhost:15672/api/exchanges/%2f/my-new-exchange + # No return a body in response to a PUT or DELETE, unless it fails. + + +exit + +# http://hints.macworld.com/article.php?story=20021202054815892 +# On Ubuntu: +# https://askubuntu.com/questions/192050/how-to-run-sudo-command-with-no-password?noredirect=1&lq=1 + + +# Install Node Package amqplib to make RabbitMQ API calls: +# https://www.rabbitmq.com/tutorials/tutorial-one-javascript.html +# npm install amqplib + #FIX: pause( "Press [Enter] to continue." ) diff --git a/node_modules/amqplib/CHANGELOG.md b/node_modules/amqplib/CHANGELOG.md new file mode 100644 index 0000000..2f4c973 --- /dev/null +++ b/node_modules/amqplib/CHANGELOG.md @@ -0,0 +1,234 @@ +# Change log for amqplib + +## Changes in v0.5.2 + + git log v0.5.1..v0.5.2 + + * Increase encoding buffer to accommodate large header values + ([PR 367](https://github.com/squaremo/amqp.node/pull/367)) + * Bring code up to date with new Buffer interface + ([PR 350](https://github.com/squaremo/amqp.node/pull/350)) + * Fix dangling connection problem + ([PR 340](https://github.com/squaremo/amqp.node/pull/340)) + * Clear up URL credentials parsing + ([PR 330](https://github.com/squaremo/amqp.node/pull/330)) + * Allow connection params to be suppied in object + ([PR 304](https://github.com/squaremo/amqp.node/pull/304)) + * Support explicit numeric types in field tables (e.g., headers) + ([PR 389](https://github.com/squaremo/amqp.node/pull/389), from a + suggestion in + [issue 358](https://github.com/squaremo/amqp.node/issues/358)) + +Thank you to all contributors, of PRs, issues and comments. + +## Changes in v0.5.1 + + git log v0.5.0..v0.5.1 + + * Fix mistake in closeBecause + ([PR 298](https://github.com/squaremo/amqp.node/pull/298); thanks + to @lholznagel and others who reported the issue, and to @nfantone + for the rapid fix) + +## Changes in v0.5.0 + + git log v0.4.2..v0.5.0 + + * Port to use bluebird rather than when.js + ([PR 295](https://github.com/squaremo/amqp.node/pull/295); thanks + to @nfantone, and special mention to @myndzi for #158) + * Fixed a problem with using `channel.get` in the callback model + ([PR 283](https://github.com/squaremo/amqp.node/pull/283); good + catch, @shanksauce) + * Added an example that uses generators (thanks @rudijs) + * Fixed a link in the comments relating to heartbeats (thanks + @tapickell) + +## Changes in v0.4.2 + + git log v0.4.1..v0.4.2 + + * Better documentation and examples + * Replace uses of ES6 keyword 'await' + +## Changes in v0.4.1 + + git log v0.4.0..v0.4.1 + + * Tested in Node.JS 0.8 through 4.2 and 5.5 + * Emit an error with the 'close' event if server-initiated + +## Changes in v0.4.0 + + git log v0.3.2..v0.4.0 + + * Tested on Node.JS 0.8 through 4.0 (and intervening io.js releases) + * Change meaning of 'b' fields in tables to match RabbitMQ (and AMQP + specification) + * Can now pass an object in place of connection URL + ([PR 159](https://github.com/squaremo/amqp.node/pull/159); thanks + to @ben-page) + * Operator-initiated connection close no longer results in 'error' + event + ([issue 110](https://github.com/squaremo/amqp.node/issues/110)) + * Channel and Connection errors have now a `.code` field with the + AMQP reply-code, which may help distinguish error cases + ([PR 150](https://github.com/squaremo/amqp.node/pull/150); thanks + to @hippich) + * Connection.close will resolve to an error if the connection is + already closed + ([issue 181](https://github.com/squaremo/amqp.node/issues/181)) + * Connection establishment will resolve with an error if the + TCP-level connection or the handshake times out + ([PR 169](https://github.com/squaremo/amqp.node/pull/169); thanks + to @zweifisch and @RoCat, who both submitted fixes) + * Add the `maxPriority` option as an alias for the `'x-max-priority'` + queue argument + ([PR 180](https://github.com/squaremo/amqp.node/pull/180); thanks + to @ebardes) + +## Changes in v0.3.2 (since v0.3.1) + + git log v0.3.1..v0.3.2 + + * Make the engine specification more flexible to admit io.js releases + +## Changes in v0.3.1 (since v0.3.0) + + git log v0.3.0..v0.3.1 + +### Fixes + + * Fail in the right way when a channel cannot be allocated [issue + 129](https://github.com/squaremo/amqp.node/issues/129) + * Make `waitForConfirms` work properly in callback API [PR + 116](https://github.com/squaremo/amqp.node/pull/116) + +### Enhancements + + * Two new options while connecting: + [timeout](https://github.com/squaremo/amqp.node/pull/118) and [keep + alive](https://github.com/squaremo/amqp.node/pull/125) (thanks to + @rexxars and @jcrugzz respectively) + +## Changes in v0.3.0 (since v0.2.1) + + git log v0.2.1..v0.3.0 + +### Enhancements + + * Allow additional client properties to be set for a connection + [Issue 98](https://github.com/squaremo/amqp.node/issues/98) and + [PR 80](https://github.com/squaremo/amqp.node/pull/80) + * New method in channel API to wait for all unconfirmed messages + [Issue 89](https://github.com/squaremo/amqp.node/issues/89) + * Now supports RabbitMQ's `EXTERNAL` authentication plugin + [Issue 105](https://github.com/squaremo/amqp.node/issues/105) + +## Changes in v0.2.1 (since v0.2.0) + +### Fixes + + * Do tuning negotation properly [PR + 84](https://github.com/squaremo/amqp.node/pull/84) + +## Changes in v0.2.0 (since v0.1.3) + + git log v0.1.3..v0.2.0 + +### Fixes + + * Correctly deal with missing fields (issue 48) + +### Enhancements + + * Added a callback-oriented API, parallel to the existing, + promise-oriented API. + * The response to assertExchange now contains the exchange name, + analagous to assertQueue (issue 49) + * The channel method `prefetch` now has a global flag, to be + [compatible with newer RabbitMQ][rabbitmq-prefetch-global]. + +## Changes in v0.1.3 (since v0.1.2) + + git log v0.1.2..v0.1.3 + +### Enhancements + + * Add support in the API for using Basic.Reject rather than + Basic.Nack, the latter of which is a RabbitMQ extension and not in + older versions of RabbitMQ. + +## Changes in v0.1.2 (since v0.1.1) + + git log v0.1.1..v0.1.2 + +### Fixes + + * Restore support for publishing zero-length messages + +### Enhancements + + * Recognise [authentication failures][rabbitmq-auth-failure] + * An option to set TCP_NODELAY on connection sockets + +## Changes in v0.1.1 (since v0.1.0) + + git log v0.1.0..v0.1.1 + +### Fixes + + * Safer frame construction, no longer relies on allocating a large, + fixed-size buffer and hoping it's big enough + * The ports of RabbitMQ tutorials now avoid a race between publishing + and closing the connection + +### Enhancements + + * Support for RabbitMQ's consumer priority extension + * Support for RabbitMQ's connnection.blocked extension + * Better write speed from batching frames for small messages + * Other minor efficiency gains in method encoding and decoding + * Channel and connection state errors (e.g., trying to write when + closed) include a stack trace from when they moved to that state + * The `arguments` table, passed as an option to some methods, can + include fields in its prototype chain + * Provide the more accurately named `persistent` as a near equivalent + of `deliveryMode` + +## Changes in v0.1.0 (since v0.0.2) + + git log v0.0.2..v0.1.0 + +### Breaking changes + + * Consumer callbacks are invoked with `null` if the consumer is + cancelled (see + [RabbitMQ's consumer cancel notification][rabbitmq-consumer-cancel]) + * In confirm channels, instead of `#publish` and `#sendToQueue` + returning promises, they return a boolean as for normal channels, + and take a Node.JS-style `function (err, ok)` callback for the + server ack or nack + +### Fixes + + * Overlapping channel and connection close frames are dealt with + gracefully + * Exceptions thrown in consumer callbacks are raised as `'error'` + events + * Zero-size messages are handled + * Avoid monkey-patching `Buffer`, and eschew + `require('util')._extend` + +### Enhancements + + * Channels now behave like `Writable` streams with regard to `#publish` + and `#sendToQueue`, returning a boolean from those methods and + emitting `'drain'` + * Connections now multiplex frames from channels fairly + * Low-level channel machinery is now fully callback-based + + +[rabbitmq-consumer-cancel]: http://www.rabbitmq.com/consumer-cancel.html +[rabbitmq-auth-failure]: http://www.rabbitmq.com/auth-notification.html +[rabbitmq-prefetch-global]: http://www.rabbitmq.com/consumer-prefetch.html diff --git a/node_modules/amqplib/LICENSE b/node_modules/amqplib/LICENSE new file mode 100644 index 0000000..62c710d --- /dev/null +++ b/node_modules/amqplib/LICENSE @@ -0,0 +1,6 @@ +amqplib copyright (c) 2013, 2014 + Michael Bridgen + +This package, "amqplib", is licensed under the MIT License. A copy may +be found in the file LICENSE-MIT in this directory, or downloaded from +http://opensource.org/licenses/MIT. diff --git a/node_modules/amqplib/LICENSE-MIT b/node_modules/amqplib/LICENSE-MIT new file mode 100644 index 0000000..d04bc01 --- /dev/null +++ b/node_modules/amqplib/LICENSE-MIT @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013, 2014 Michael Bridgen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/amqplib/Makefile b/node_modules/amqplib/Makefile new file mode 100644 index 0000000..89a50e9 --- /dev/null +++ b/node_modules/amqplib/Makefile @@ -0,0 +1,46 @@ +RABBITMQ_SRC_VERSION=rabbitmq_v3_2_1 +JSON=amqp-rabbitmq-0.9.1.json +RABBITMQ_CODEGEN=https://raw.githubusercontent.com/rabbitmq/rabbitmq-codegen +AMQP_JSON=$(RABBITMQ_CODEGEN)/$(RABBITMQ_SRC_VERSION)/$(JSON) +NODEJS_VERSIONS='0.8' '0.9' '0.10' '0.11' '0.12' '1.6' '2.5' '3.3' '4.2' '5.5' '6.2' '8.9' '9.1' + +MOCHA=./node_modules/.bin/mocha +_MOCHA=./node_modules/.bin/_mocha +UGLIFY=./node_modules/.bin/uglifyjs +ISTANBUL=./node_modules/.bin/istanbul + +.PHONY: test test-all-nodejs all clean coverage + +all: lib/defs.js + +clean: + rm lib/defs.js bin/amqp-rabbitmq-0.9.1.json + rm -rf ./coverage + +lib/defs.js: $(UGLIFY) bin/generate-defs.js bin/amqp-rabbitmq-0.9.1.json + (cd bin; node ./generate-defs.js > ../lib/defs.js) + $(UGLIFY) ./lib/defs.js -o ./lib/defs.js \ + -c 'sequences=false' --comments \ + -b 'indent-level=2' 2>&1 | (grep -v 'WARN' || true) + +test: lib/defs.js + $(MOCHA) --check-leaks -u tdd test/ + +test-all-nodejs: lib/defs.js + for v in $(NODEJS_VERSIONS); \ + do nave use $$v $(MOCHA) -u tdd -R progress test; \ + done + +coverage: $(ISTANBUL) lib/defs.js + $(ISTANBUL) cover $(_MOCHA) -- -u tdd -R progress test/ + $(ISTANBUL) report + @echo "HTML report at file://$$(pwd)/coverage/lcov-report/index.html" + +bin/amqp-rabbitmq-0.9.1.json: + curl -L $(AMQP_JSON) > $@ + +$(ISTANBUL): + npm install + +$(UGLIFY): + npm install diff --git a/node_modules/amqplib/README.md b/node_modules/amqplib/README.md new file mode 100644 index 0000000..9567c8f --- /dev/null +++ b/node_modules/amqplib/README.md @@ -0,0 +1,157 @@ +# AMQP 0-9-1 library and client for Node.JS + +[![Build Status](https://travis-ci.org/squaremo/amqp.node.png)](https://travis-ci.org/squaremo/amqp.node) + + npm install amqplib + + * [Change log][changelog] + * [GitHub pages][gh-pages] + * [API reference][gh-pages-apiref] + * [Examples from RabbitMQ tutorials][tutes] + +A library for making AMQP 0-9-1 clients for Node.JS, and an AMQP 0-9-1 +client for Node.JS v0.8-0.12, v4-v9, and the intervening io.js +releases. + +This library does not implement [AMQP +1.0](https://github.com/squaremo/amqp.node/issues/63) or [AMQP +0-10](https://github.com/squaremo/amqp.node/issues/94). + +Project status: + + - Expected to work + - Complete high-level and low-level APIs (i.e., all bits of the protocol) + - Stable APIs + - A fair few tests + - Measured test coverage + - Ports of the [RabbitMQ tutorials][rabbitmq-tutes] as [examples][tutes] + - Used in production + +Still working on: + + - Getting to 100% (or very close to 100%) test coverage + +## Callback API example + +```javascript +var q = 'tasks'; + +function bail(err) { + console.error(err); + process.exit(1); +} + +// Publisher +function publisher(conn) { + conn.createChannel(on_open); + function on_open(err, ch) { + if (err != null) bail(err); + ch.assertQueue(q); + ch.sendToQueue(q, new Buffer('something to do')); + } +} + +// Consumer +function consumer(conn) { + var ok = conn.createChannel(on_open); + function on_open(err, ch) { + if (err != null) bail(err); + ch.assertQueue(q); + ch.consume(q, function(msg) { + if (msg !== null) { + console.log(msg.content.toString()); + ch.ack(msg); + } + }); + } +} + +require('amqplib/callback_api') + .connect('amqp://localhost', function(err, conn) { + if (err != null) bail(err); + consumer(conn); + publisher(conn); + }); +``` + +## Promise API example + +```javascript +var q = 'tasks'; + +var open = require('amqplib').connect('amqp://localhost'); + +// Publisher +open.then(function(conn) { + return conn.createChannel(); +}).then(function(ch) { + return ch.assertQueue(q).then(function(ok) { + return ch.sendToQueue(q, new Buffer('something to do')); + }); +}).catch(console.warn); + +// Consumer +open.then(function(conn) { + return conn.createChannel(); +}).then(function(ch) { + return ch.assertQueue(q).then(function(ok) { + return ch.consume(q, function(msg) { + if (msg !== null) { + console.log(msg.content.toString()); + ch.ack(msg); + } + }); + }); +}).catch(console.warn); +``` + +## Running tests + + npm test + +To run the tests RabbitMQ is required. Either install it with your package +manager, or use [docker][] to run a RabbitMQ instance. + + docker run -d --name amqp.test -p 5672:5672 rabbitmq + +If prefer not to run RabbitMQ locally it is also possible to use a +instance of RabbitMQ hosted elsewhere. Use the `URL` environment +variable to configure a different amqp host to connect to. You may +also need to do this if docker is not on localhost; e.g., if it's +running in docker-machine. + +One public host is dev.rabbitmq.com: + + URL=amqp://dev.rabbitmq.com npm test + +**NB** You may experience test failures due to timeouts if using the +dev.rabbitmq.com instance. + +You can run it under different versions of Node.JS using [nave][]: + + nave use 0.8 npm test + +or run the tests on all supported versions of Node.JS in one go: + + make test-all-nodejs + +(which also needs `nave` installed, of course). + +Lastly, setting the environment variable `LOG_ERRORS` will cause the +tests to output error messages encountered, to the console; this is +really only useful for checking the kind and formatting of the errors. + + LOG_ERRORS=true npm test + +## Test coverage + + make coverage + open file://`pwd`/coverage/lcov-report/index.html + +[gh-pages]: http://squaremo.github.com/amqp.node/ +[gh-pages-apiref]: http://squaremo.github.com/amqp.node/channel_api.html +[nave]: https://github.com/isaacs/nave +[tutes]: https://github.com/squaremo/amqp.node/tree/master/examples/tutorials +[rabbitmq-tutes]: http://www.rabbitmq.com/getstarted.html +[changelog]: https://github.com/squaremo/amqp.node/blob/master/CHANGELOG.md +[docker]: https://www.docker.com/ diff --git a/node_modules/amqplib/callback_api.js b/node_modules/amqplib/callback_api.js new file mode 100644 index 0000000..1955312 --- /dev/null +++ b/node_modules/amqplib/callback_api.js @@ -0,0 +1,22 @@ +var raw_connect = require('./lib/connect').connect; +var CallbackModel = require('./lib/callback_model').CallbackModel; + +// Supports three shapes: +// connect(url, options, callback) +// connect(url, callback) +// connect(callback) +function connect(url, options, cb) { + if (typeof url === 'function') + cb = url, url = false, options = false; + else if (typeof options === 'function') + cb = options, options = false; + + raw_connect(url, options, function(err, c) { + if (err === null) cb(null, new CallbackModel(c)); + else cb(err); + }); +}; + +module.exports.connect = connect; +module.exports.credentials = require('./lib/credentials'); +module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/channel_api.js b/node_modules/amqplib/channel_api.js new file mode 100644 index 0000000..6c8c4dd --- /dev/null +++ b/node_modules/amqplib/channel_api.js @@ -0,0 +1,16 @@ +var raw_connect = require('./lib/connect').connect; +var ChannelModel = require('./lib/channel_model').ChannelModel; +var Promise = require('bluebird'); + +function connect(url, connOptions) { + return Promise.fromCallback(function(cb) { + return raw_connect(url, connOptions, cb); + }) + .then(function(conn) { + return new ChannelModel(conn); + }); +}; + +module.exports.connect = connect; +module.exports.credentials = require('./lib/credentials'); +module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/examples/headers.js b/node_modules/amqplib/examples/headers.js new file mode 100755 index 0000000..e4f7bcc --- /dev/null +++ b/node_modules/amqplib/examples/headers.js @@ -0,0 +1,42 @@ +#!/usr/bin/env node + +// Example of using a headers exchange + +var amqp = require('../') + +amqp.connect().then(function(conn) { + return conn.createChannel().then(withChannel); +}, console.error); + +function withChannel(ch) { + // NB the type of the exchange is 'headers' + ch.assertExchange('matching exchange', 'headers').then(function(ex) { + ch.assertQueue().then(function(q) { + bindAndConsume(ch, ex, q).then(function() { + send(ch, ex); + }); + }); + }); +} + +function bindAndConsume(ch, ex, q) { + // When using a headers exchange, the headers to be matched go in + // the binding arguments. The routing key is ignore, so best left + // empty. + + // 'x-match' is 'all' or 'any', meaning "all fields must match" or + // "at least one field must match", respectively. The values to be + // matched go in subsequent fields. + ch.bindQueue(q.queue, ex.exchange, '', {'x-match': 'any', + 'foo': 'bar', + 'baz': 'boo'}); + return ch.consume(q.queue, function(msg) { + console.log(msg.content.toString()); + }, {noAck: true}); +} + +function send(ch, ex) { + // The headers for a message are given as an option to `publish`: + ch.publish(ex.exchange, '', Buffer.from('hello'), {headers: {baz: 'boo'}}); + ch.publish(ex.exchange, '', Buffer.from('world'), {headers: {foo: 'bar'}}); +} diff --git a/node_modules/amqplib/examples/receive_generator.js b/node_modules/amqplib/examples/receive_generator.js new file mode 100644 index 0000000..8146de0 --- /dev/null +++ b/node_modules/amqplib/examples/receive_generator.js @@ -0,0 +1,39 @@ +#!/usr/bin/env node + +'use strict'; +const co = require('co'); +const amqp = require('amqplib'); +const readline = require('readline'); + +co(function* () { + const myConsumer = (msg) => { + if (msg !== null) { + console.log('consuming message %s in generator', JSON.stringify(msg.content.toString())); + } + }; + const conn = yield amqp.connect('amqp://localhost'); + try { + // create a message to consume + const q = 'hello'; + const msg = 'Hello World!'; + const channel = yield conn.createChannel(); + yield channel.assertQueue(q); + channel.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + // consume the message + yield channel.consume(q, myConsumer, { noAck: true }); + } + catch (e) { + throw e; + } +}).catch(err => { + console.warn('Error:', err); +}); + +const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout +}); + +// pend until message is consumed +rl.question('newline to exit', () => process.exit()); \ No newline at end of file diff --git a/node_modules/amqplib/examples/send_generators.js b/node_modules/amqplib/examples/send_generators.js new file mode 100755 index 0000000..171778e --- /dev/null +++ b/node_modules/amqplib/examples/send_generators.js @@ -0,0 +1,42 @@ +#!/usr/bin/env node + +'use strict'; + +// NB this requires the module 'co': +// npm install co +const co = require('co'); +const amqp = require('amqplib'); + +co(function* () { + // connection errors are handled in the co .catch handler + const conn = yield amqp.connect('amqp://localhost'); + + // try catch will throw any errors from the yielding the following promises to the co .catch handler + try { + const q = 'hello'; + const msg = 'Hello World!'; + + // use a confirm channel so we can check the message is sent OK. + const channel = yield conn.createConfirmChannel(); + + yield channel.assertQueue(q); + + channel.sendToQueue(q, Buffer.from(msg)); + + // if message has been nacked, this will result in an error (rejected promise); + yield channel.waitForConfirms(); + + console.log(" [x] Sent '%s'", msg); + + channel.close(); + } + catch (e) { + throw e; + } + finally { + conn.close(); + } + +}).catch(err => { + console.warn('Error:', err); +}); diff --git a/node_modules/amqplib/examples/ssl.js b/node_modules/amqplib/examples/ssl.js new file mode 100644 index 0000000..07f1ae1 --- /dev/null +++ b/node_modules/amqplib/examples/ssl.js @@ -0,0 +1,64 @@ +// Example of using a TLS/SSL connection. Note that the server must be +// configured to accept SSL connections; see, for example, +// http://www.rabbitmq.com/ssl.html. +// +// When trying this out, I followed the RabbitMQ SSL guide above, +// almost verbatim. I set the CN of the server certificate to +// 'localhost' rather than $(hostname) (since on my MBP hostname ends +// up being ".local", which is just weird). My client +// certificates etc., are in `../etc/client/`. My testca certificate +// is in `../etc/testca` and server certs etc., in `../etc/server`, +// and I've made a `rabbitmq.config` file, with which I start +// RabbitMQ: +// +// RABBITMQ_CONFIG_FILE=`pwd`/../etc/server/rabbitmq \ +// /usr/local/sbin/rabbitmq-server & +// +// A way to check RabbitMQ's running with SSL OK is to use +// +// openssl s_client -connect localhost:5671 + +var amqp = require('../'); +var fs = require('fs'); + +// Assemble the SSL options; for verification we need at least +// * a certificate to present to the server ('cert', in PEM format) +// * the private key for the certificate ('key', in PEM format) +// * (possibly) a passphrase for the private key +// +// The first two may be replaced with a PKCS12 file ('pfx', in pkcs12 +// format) + +// We will also want to list the CA certificates that we will trust, +// since we're using a self-signed certificate. It is NOT recommended +// to use `rejectUnauthorized: false`. + +// Options for full client and server verification: +var opts = { + cert: fs.readFileSync('../etc/client/cert.pem'), + key: fs.readFileSync('../etc/client/key.pem'), + // cert and key or + // pfx: fs.readFileSync('../etc/client/keycert.p12'), + passphrase: 'MySecretPassword', + ca: [fs.readFileSync('../etc/testca/cacert.pem')] +}; + +// Options for just confidentiality. This requires RabbitMQ's SSL +// configuration to include the items +// +// {verify, verify_none}, +// {fail_if_no_peer_cert,false} +// +// var opts = { ca: [fs.readFileSync('../etc/testca/cacert.pem')] }; + +// Option to use the SSL client certificate for authentication +// opts.credentials = amqp.credentials.external(); + +var open = amqp.connect('amqps://localhost', opts); + +open.then(function(conn) { + process.on('SIGINT', conn.close.bind(conn)); + return conn.createChannel().then(function(ch) { + ch.sendToQueue('foo', Buffer.from('Hello World!')); + }); +}).then(null, console.warn); diff --git a/node_modules/amqplib/examples/tutorials/README.md b/node_modules/amqplib/examples/tutorials/README.md new file mode 100644 index 0000000..333fda3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/README.md @@ -0,0 +1,93 @@ +# RabbitMQ tutorials + +This directory contains the [RabbitMQ tutorials][rabbitmq-tutes], +ported to amqplib. The sub-directory `callback_api` has translations +of the tutorial programs to the callback-oriented API. + +## Preparation + +To run the tutorial code, you need amqplib installed. Assuming you are +in a clone of the amqplib repository, from the tutorials directory: + + npm install + +or to use the latest released version, + + npm install amqplib + +Then just run each file as a script, e.g., in bash + + ./send.js + +or + + node send.js + +or + + nave use 0.8 node send.js + +## [Tutorial one: Hello World!][tute-one] + +A "Hello World" example, with one script sending a message to a queue, +and another receiving messages from the same queue. + + * [send.js](send.js) + * [receive.js](receive.js) + +## [Tutorial two: Work queues][tute-two] + +Using RabbitMQ as a work queue; `new_task` creates a task, and +`worker` processes tasks. Multiple `worker` process will share the +tasks among them. Long-running tasks are simulated by supplying a +string with dots, e.g., '...' to `new_task`. Each dot makes the worker +"work" for a second. + + * [new_task.js](new_task.js) + * [worker.js](worker.js) + +## [Tutorial three: Publish/Subscribe][tute-three] + +Using RabbitMQ as a broadcast mechanism. `emit_log` sends a "log" +message to a fanout exchange, and all `receive_logs` processes receive +log messages. + + * [emit_log.js](emit_log.js) + * [receive_logs.js](receive_logs.js) + +## [Tutorial four: Routing][tute-four] + +Using RabbitMQ as a routing ('somecast') mechanism. `emit_log_direct` +sends a log message with a severity, and all `receive_logs_direct` +processes receive log messages for the severities on which they are +listening. + + * [emit_log_direct.js](emit_log_direct.js) + * [receive_logs_direct.js](receive_logs_direct.js) + +## [Tutorial five: Topics][tute-five] + +Extends the previous tutorial to routing with wildcarded patterns. + + * [emit_log_topic.js](emit_log_topic.js) + * [receive_logs_topic.js](receive_logs_topic.js) + +## [Tutorial six: RPC][tute-six] + +Using RabbitMQ as an RPC intermediary, queueing requests for servers +and routing replies back to clients. + + * [rpc_server.js](rpc_server.js) + * [rpc_client.js](rpc_client.js) + +I depart slightly from the original tutorial code, which I think has +some needless object-orientation (in the Python code; you don't get a +choice about needless object-orientation in Java). + +[rabbitmq-tutes]: http://github.com/rabbitmq/rabbitmq-tutorials +[tute-one]: http://www.rabbitmq.com/tutorials/tutorial-one-python.html +[tute-two]: http://www.rabbitmq.com/tutorials/tutorial-two-python.html +[tute-three]: http://www.rabbitmq.com/tutorials/tutorial-three-python.html +[tute-four]: http://www.rabbitmq.com/tutorials/tutorial-four-python.html +[tute-five]: http://www.rabbitmq.com/tutorials/tutorial-five-python.html +[tute-six]: http://www.rabbitmq.com/tutorials/tutorial-six-python.html diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js new file mode 100755 index 0000000..9ea353d --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var ex = 'logs'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertExchange(ex, 'fanout', {durable: false}); + var msg = process.argv.slice(2).join(' ') || + 'info: Hello World!'; + ch.publish(ex, '', Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js new file mode 100755 index 0000000..bd4e640 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var args = process.argv.slice(2); +var severity = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var ex = 'direct_logs'; + var exopts = {durable: false}; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertExchange(ex, 'direct', exopts, function(err, ok) { + ch.publish(ex, severity, Buffer.from(message)); + ch.close(function() { conn.close(); }); + }); + } + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js new file mode 100755 index 0000000..7601ecf --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js @@ -0,0 +1,27 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var args = process.argv.slice(2); +var key = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + var ex = 'topic_logs', exopts = {durable: false}; + conn.createChannel(function(err, ch) { + ch.assertExchange(ex, 'topic', exopts, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.publish(ex, key, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", key, message); + ch.close(function() { conn.close(); }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/new_task.js b/node_modules/amqplib/examples/tutorials/callback_api/new_task.js new file mode 100755 index 0000000..6122231 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/new_task.js @@ -0,0 +1,27 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var q = 'task_queue'; + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: true}, function(err, _ok) { + if (err !== null) return bail(err, conn); + var msg = process.argv.slice(2).join(' ') || "Hello World!"; + ch.sendToQueue(q, Buffer.from(msg), {persistent: true}); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive.js b/node_modules/amqplib/examples/tutorials/callback_api/receive.js new file mode 100755 index 0000000..c6bb056 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive.js @@ -0,0 +1,30 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var q = 'hello'; + + function on_channel_open(err, ch) { + ch.assertQueue(q, {durable: false}, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.consume(q, function(msg) { // message callback + console.log(" [x] Received '%s'", msg.content.toString()); + }, {noAck: true}, function(_consumeOk) { // consume callback + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + }); + }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js new file mode 100755 index 0000000..4d024e4 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var ex = 'logs'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + var q = ok.queue; + ch.bindQueue(q, ex, ''); + ch.consume(q, logMessage, {noAck: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + console.log(" [*] Waiting for logs. To exit press CTRL+C."); + }); + }); + } + + function logMessage(msg) { + if (msg) + console.log(" [x] '%s'", msg.content.toString()); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js new file mode 100755 index 0000000..9bb9f98 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js @@ -0,0 +1,56 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +var basename = require('path').basename; + +var severities = process.argv.slice(2); +if (severities.length < 1) { + console.log('Usage %s [info] [warning] [error]', + basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + var ex = 'direct_logs', exopts = {durable: false}; + + ch.assertExchange(ex, 'direct', exopts); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + + var queue = ok.queue, i = 0; + + function sub(err) { + if (err !== null) return bail(err, conn); + else if (i < severities.length) { + ch.bindQueue(queue, ex, severities[i], {}, sub); + i++; + } + } + + ch.consume(queue, logMessage, {noAck: true}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + sub(null); + }); + }); + }); +} + +function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js new file mode 100755 index 0000000..2c827c2 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); +var basename = require('path').basename; + +var keys = process.argv.slice(2); +if (keys.length < 1) { + console.log('Usage %s pattern [pattern...]', + basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + var ex = 'topic_logs', exopts = {durable: false}; + + ch.assertExchange(ex, 'topic', exopts); + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + + var queue = ok.queue, i = 0; + + function sub(err) { + if (err !== null) return bail(err, conn); + else if (i < keys.length) { + ch.bindQueue(queue, ex, keys[i], {}, sub); + i++; + } + } + + ch.consume(queue, logMessage, {noAck: true}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + sub(null); + }); + }); + }); +} + +function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js new file mode 100755 index 0000000..abf22a0 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js @@ -0,0 +1,49 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); +var basename = require('path').basename; +var uuid = require('node-uuid'); + +var n; +try { + if (process.argv.length < 3) throw Error('Too few args'); + n = parseInt(process.argv[2]); +} +catch (e) { + console.error(e); + console.warn('Usage: %s number', basename(process.argv[1])); + process.exit(1); +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + + var correlationId = uuid(); + function maybeAnswer(msg) { + if (msg.properties.correlationId === correlationId) { + console.log(' [.] Got %d', msg.content.toString()); + } + else return bail(new Error('Unexpected message'), conn); + ch.close(function() { conn.close(); }); + } + + ch.assertQueue('', {exclusive: true}, function(err, ok) { + if (err !== null) return bail(err, conn); + var queue = ok.queue; + ch.consume(queue, maybeAnswer, {noAck:true}); + console.log(' [x] Requesting fib(%d)', n); + ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { + replyTo: queue, correlationId: correlationId + }); + }); + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js new file mode 100755 index 0000000..dae1d9b --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function fib(n) { + var a = 0, b = 1; + for (var i=0; i < n; i++) { + var c = a + b; + a = b; b = c; + } + return a; +} + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + process.once('SIGINT', function() { conn.close(); }); + + var q = 'rpc_queue'; + + conn.createChannel(function(err, ch) { + ch.assertQueue(q, {durable: false}); + ch.prefetch(1); + ch.consume(q, reply, {noAck:false}, function(err) { + if (err !== null) return bail(err, conn); + console.log(' [x] Awaiting RPC requests'); + }); + + function reply(msg) { + var n = parseInt(msg.content.toString()); + console.log(' [.] fib(%d)', n); + ch.sendToQueue(msg.properties.replyTo, + Buffer.from(fib(n).toString()), + {correlationId: msg.properties.correlationId}); + ch.ack(msg); + } + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/send.js b/node_modules/amqplib/examples/tutorials/callback_api/send.js new file mode 100755 index 0000000..8ff0e4b --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/send.js @@ -0,0 +1,29 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + + var q = 'hello'; + var msg = 'Hello World!'; + + function on_channel_open(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: false}, function(err, ok) { + if (err !== null) return bail(err, conn); + ch.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + ch.close(function() { conn.close(); }); + }); + } + + conn.createChannel(on_channel_open); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/worker.js b/node_modules/amqplib/examples/tutorials/callback_api/worker.js new file mode 100755 index 0000000..ad7d076 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/callback_api/worker.js @@ -0,0 +1,35 @@ +#!/usr/bin/env node + +var amqp = require('amqplib/callback_api'); + +function bail(err, conn) { + console.error(err); + if (conn) conn.close(function() { process.exit(1); }); +} + +function on_connect(err, conn) { + if (err !== null) return bail(err); + process.once('SIGINT', function() { conn.close(); }); + + var q = 'task_queue'; + + conn.createChannel(function(err, ch) { + if (err !== null) return bail(err, conn); + ch.assertQueue(q, {durable: true}, function(err, _ok) { + ch.consume(q, doWork, {noAck: false}); + console.log(" [*] Waiting for messages. To exit press CTRL+C"); + }); + + function doWork(msg) { + var body = msg.content.toString(); + console.log(" [x] Received '%s'", body); + var secs = body.split('.').length - 1; + setTimeout(function() { + console.log(" [x] Done"); + ch.ack(msg); + }, secs * 1000); + } + }); +} + +amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/emit_log.js b/node_modules/amqplib/examples/tutorials/emit_log.js new file mode 100755 index 0000000..2bf7e14 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'logs'; + var ok = ch.assertExchange(ex, 'fanout', {durable: false}) + + var message = process.argv.slice(2).join(' ') || + 'info: Hello World!'; + + return ok.then(function() { + ch.publish(ex, '', Buffer.from(message)); + console.log(" [x] Sent '%s'", message); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/emit_log_direct.js new file mode 100755 index 0000000..0846edf --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log_direct.js @@ -0,0 +1,20 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +var args = process.argv.slice(2); +var severity = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'direct_logs'; + var ok = ch.assertExchange(ex, 'direct', {durable: false}); + + return ok.then(function() { + ch.publish(ex, severity, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", severity, message); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/emit_log_topic.js new file mode 100755 index 0000000..5f643a3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/emit_log_topic.js @@ -0,0 +1,19 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +var args = process.argv.slice(2); +var key = (args.length > 0) ? args[0] : 'info'; +var message = args.slice(1).join(' ') || 'Hello World!'; + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var ex = 'topic_logs'; + var ok = ch.assertExchange(ex, 'topic', {durable: false}); + return ok.then(function() { + ch.publish(ex, key, Buffer.from(message)); + console.log(" [x] Sent %s:'%s'", key, message); + return ch.close(); + }); + }).finally(function() { conn.close(); }) +}).catch(console.log); diff --git a/node_modules/amqplib/examples/tutorials/new_task.js b/node_modules/amqplib/examples/tutorials/new_task.js new file mode 100755 index 0000000..c25cfbc --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/new_task.js @@ -0,0 +1,18 @@ +#!/usr/bin/env node +// Post a new task to the work queue + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var q = 'task_queue'; + var ok = ch.assertQueue(q, {durable: true}); + + return ok.then(function() { + var msg = process.argv.slice(2).join(' ') || "Hello World!"; + ch.sendToQueue(q, Buffer.from(msg), {deliveryMode: true}); + console.log(" [x] Sent '%s'", msg); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/package.json b/node_modules/amqplib/examples/tutorials/package.json new file mode 100644 index 0000000..71f49af --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/package.json @@ -0,0 +1,16 @@ +{ + "name": "amqplib-tutorials", + "version": "0.0.1", + "description": "The RabbitMQ tutorials, ported to amqplib", + "main": "send.js", + "dependencies": { + "amqplib": "../..", + "node-uuid": "*" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": "", + "author": "Michael Bridgen ", + "license": "MPL 2.0" +} diff --git a/node_modules/amqplib/examples/tutorials/receive.js b/node_modules/amqplib/examples/tutorials/receive.js new file mode 100755 index 0000000..b7a7975 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive.js @@ -0,0 +1,21 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + + var ok = ch.assertQueue('hello', {durable: false}); + + ok = ok.then(function(_qok) { + return ch.consume('hello', function(msg) { + console.log(" [x] Received '%s'", msg.content.toString()); + }, {noAck: true}); + }); + + return ok.then(function(_consumeOk) { + console.log(' [*] Waiting for messages. To exit press CTRL+C'); + }); + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs.js b/node_modules/amqplib/examples/tutorials/receive_logs.js new file mode 100755 index 0000000..d592af9 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ok = ch.assertExchange('logs', 'fanout', {durable: false}); + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + ok = ok.then(function(qok) { + return ch.bindQueue(qok.queue, 'logs', '').then(function() { + return qok.queue; + }); + }); + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C'); + }); + + function logMessage(msg) { + console.log(" [x] '%s'", msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/receive_logs_direct.js new file mode 100755 index 0000000..17fc22d --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs_direct.js @@ -0,0 +1,45 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var all = require('bluebird').all; +var basename = require('path').basename; + +var severities = process.argv.slice(2); +if (severities.length < 1) { + console.warn('Usage: %s [info] [warning] [error]', + basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ex = 'direct_logs'; + + var ok = ch.assertExchange(ex, 'direct', {durable: false}); + + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + + ok = ok.then(function(qok) { + var queue = qok.queue; + return all(severities.map(function(sev) { + ch.bindQueue(queue, ex, sev); + })).then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }); + + function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/receive_logs_topic.js new file mode 100755 index 0000000..3e8eb6f --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/receive_logs_topic.js @@ -0,0 +1,44 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var basename = require('path').basename; +var all = require('bluebird').all; + +var keys = process.argv.slice(2); +if (keys.length < 1) { + console.log('Usage: %s pattern [pattern...]', + basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ex = 'topic_logs'; + var ok = ch.assertExchange(ex, 'topic', {durable: false}); + + ok = ok.then(function() { + return ch.assertQueue('', {exclusive: true}); + }); + + ok = ok.then(function(qok) { + var queue = qok.queue; + return all(keys.map(function(rk) { + ch.bindQueue(queue, ex, rk); + })).then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + return ch.consume(queue, logMessage, {noAck: true}); + }); + return ok.then(function() { + console.log(' [*] Waiting for logs. To exit press CTRL+C.'); + }); + + function logMessage(msg) { + console.log(" [x] %s:'%s'", + msg.fields.routingKey, + msg.content.toString()); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_client.js b/node_modules/amqplib/examples/tutorials/rpc_client.js new file mode 100755 index 0000000..47566b3 --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/rpc_client.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); +var basename = require('path').basename; +var Promise = require('bluebird'); +var uuid = require('node-uuid'); + +// I've departed from the form of the original RPC tutorial, which +// needlessly introduces a class definition, and doesn't even +// parameterise the request. + +var n; +try { + if (process.argv.length < 3) throw Error('Too few args'); + n = parseInt(process.argv[2]); +} +catch (e) { + console.error(e); + console.warn('Usage: %s number', basename(process.argv[1])); + process.exit(1); +} + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + return new Promise(function(resolve) { + var corrId = uuid(); + function maybeAnswer(msg) { + if (msg.properties.correlationId === corrId) { + resolve(msg.content.toString()); + } + } + + var ok = ch.assertQueue('', {exclusive: true}) + .then(function(qok) { return qok.queue; }); + + ok = ok.then(function(queue) { + return ch.consume(queue, maybeAnswer, {noAck: true}) + .then(function() { return queue; }); + }); + + ok = ok.then(function(queue) { + console.log(' [x] Requesting fib(%d)', n); + ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { + correlationId: corrId, replyTo: queue + }); + }); + }); + }) + .then(function(fibN) { + console.log(' [.] Got %d', fibN); + }) + .finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_server.js b/node_modules/amqplib/examples/tutorials/rpc_server.js new file mode 100755 index 0000000..84101ce --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/rpc_server.js @@ -0,0 +1,39 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +function fib(n) { + // Do it the ridiculous, but not most ridiculous, way. For better, + // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms + var a = 0, b = 1; + for (var i=0; i < n; i++) { + var c = a + b; + a = b; b = c; + } + return a; +} + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var q = 'rpc_queue'; + var ok = ch.assertQueue(q, {durable: false}); + var ok = ok.then(function() { + ch.prefetch(1); + return ch.consume(q, reply); + }); + return ok.then(function() { + console.log(' [x] Awaiting RPC requests'); + }); + + function reply(msg) { + var n = parseInt(msg.content.toString()); + console.log(' [.] fib(%d)', n); + var response = fib(n); + ch.sendToQueue(msg.properties.replyTo, + Buffer.from(response.toString()), + {correlationId: msg.properties.correlationId}); + ch.ack(msg); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/send.js b/node_modules/amqplib/examples/tutorials/send.js new file mode 100755 index 0000000..59f846e --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/send.js @@ -0,0 +1,23 @@ +#!/usr/bin/env node + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + return conn.createChannel().then(function(ch) { + var q = 'hello'; + var msg = 'Hello World!'; + + var ok = ch.assertQueue(q, {durable: false}); + + return ok.then(function(_qok) { + // NB: `sentToQueue` and `publish` both return a boolean + // indicating whether it's OK to send again straight away, or + // (when `false`) that you should wait for the event `'drain'` + // to fire before writing again. We're just doing the one write, + // so we'll ignore it. + ch.sendToQueue(q, Buffer.from(msg)); + console.log(" [x] Sent '%s'", msg); + return ch.close(); + }); + }).finally(function() { conn.close(); }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/worker.js b/node_modules/amqplib/examples/tutorials/worker.js new file mode 100755 index 0000000..fdb72df --- /dev/null +++ b/node_modules/amqplib/examples/tutorials/worker.js @@ -0,0 +1,28 @@ +#!/usr/bin/env node +// Process tasks from the work queue + +var amqp = require('amqplib'); + +amqp.connect('amqp://localhost').then(function(conn) { + process.once('SIGINT', function() { conn.close(); }); + return conn.createChannel().then(function(ch) { + var ok = ch.assertQueue('task_queue', {durable: true}); + ok = ok.then(function() { ch.prefetch(1); }); + ok = ok.then(function() { + ch.consume('task_queue', doWork, {noAck: false}); + console.log(" [*] Waiting for messages. To exit press CTRL+C"); + }); + return ok; + + function doWork(msg) { + var body = msg.content.toString(); + console.log(" [x] Received '%s'", body); + var secs = body.split('.').length - 1; + //console.log(" [x] Task takes %d seconds", secs); + setTimeout(function() { + console.log(" [x] Done"); + ch.ack(msg); + }, secs * 1000); + } + }); +}).catch(console.warn); diff --git a/node_modules/amqplib/examples/waitForConfirms.js b/node_modules/amqplib/examples/waitForConfirms.js new file mode 100644 index 0000000..d16a1d8 --- /dev/null +++ b/node_modules/amqplib/examples/waitForConfirms.js @@ -0,0 +1,22 @@ +var amqp = require('../'); + +var NUM_MSGS = 20; + +function mkCallback(i) { + return (i % 2) === 0 ? function(err) { + if (err !== null) { console.error('Message %d failed!', i); } + else { console.log('Message %d confirmed', i); } + } : null; +} + +amqp.connect().then(function(c) { + c.createConfirmChannel().then(function(ch) { + for (var i=0; i < NUM_MSGS; i++) { + ch.publish('amq.topic', 'whatever', Buffer.from('blah'), {}, mkCallback(i)); + } + ch.waitForConfirms().then(function() { + console.log('All messages done'); + c.close(); + }).catch(console.error); + }); +}); diff --git a/node_modules/amqplib/package.json b/node_modules/amqplib/package.json new file mode 100644 index 0000000..88fad48 --- /dev/null +++ b/node_modules/amqplib/package.json @@ -0,0 +1,70 @@ +{ + "_from": "amqplib", + "_id": "amqplib@0.5.2", + "_inBundle": false, + "_integrity": "sha512-l9mCs6LbydtHqRniRwYkKdqxVa6XMz3Vw1fh+2gJaaVgTM6Jk3o8RccAKWKtlhT1US5sWrFh+KKxsVUALURSIA==", + "_location": "/amqplib", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "amqplib", + "name": "amqplib", + "escapedName": "amqplib", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.5.2.tgz", + "_shasum": "d2d7313c7ffaa4d10bcf1e6252de4591b6cc7b63", + "_spec": "amqplib", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP", + "author": { + "name": "Michael Bridgen", + "email": "mikeb@squaremobius.net" + }, + "bugs": { + "url": "https://github.com/squaremo/amqp.node/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bitsyntax": "~0.0.4", + "bluebird": "^3.4.6", + "buffer-more-ints": "0.0.2", + "readable-stream": "1.x >=1.1.9", + "safe-buffer": "^5.0.1" + }, + "deprecated": false, + "description": "An AMQP 0-9-1 (e.g., RabbitMQ) library and client.", + "devDependencies": { + "claire": "0.4.1", + "istanbul": "0.1.x", + "mocha": "~1", + "uglify-js": "2.4.x" + }, + "engines": { + "node": ">=0.8 <=9" + }, + "homepage": "http://squaremo.github.io/amqp.node/", + "keywords": [ + "AMQP", + "AMQP 0-9-1", + "RabbitMQ" + ], + "license": "MIT", + "main": "./channel_api.js", + "name": "amqplib", + "repository": { + "type": "git", + "url": "git+https://github.com/squaremo/amqp.node.git" + }, + "scripts": { + "prepublish": "make", + "test": "make test" + }, + "version": "0.5.2" +} diff --git a/node_modules/amqplib/test/bitset.js b/node_modules/amqplib/test/bitset.js new file mode 100644 index 0000000..35e7656 --- /dev/null +++ b/node_modules/amqplib/test/bitset.js @@ -0,0 +1,68 @@ +'use strict'; + +var claire = require('claire'); + +var forAll = claire.forAll, + arb = claire.data, + label = claire.label, + choice = claire.choice, + transform = claire.transform; + +var BitSet = require('../lib/bitset').BitSet; +var PosInt = transform(Math.floor, arb.Positive); + +var EmptyBitSet = label('bitset', transform( + function(size) { + return new BitSet(size); + }, + choice(arb.Nothing, PosInt))); + +suite('BitSet', function() { + +test('get bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.get(bit); + }).asTest()); + +test('clear bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + b.clear(bit); + return !b.get(bit); + }).asTest()); + +test('next set of empty', forAll(EmptyBitSet) + .satisfy(function(b) { + return b.nextSetBit(0) === -1; + }).asTest()); + +test('next set of one bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(0) === bit; + }).asTest()); + +test('next set same bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(bit) === bit; + }).asTest()); + +test('next set following bit', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextSetBit(bit+1) === -1; + }).asTest()); + +test('next clear of empty', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { return b.nextClearBit(bit) === bit; }) + .asTest()); + +test('next clear of one set', forAll(EmptyBitSet, PosInt) + .satisfy(function(b, bit) { + b.set(bit); + return b.nextClearBit(bit) === bit + 1; + }).asTest()); + +}); diff --git a/node_modules/amqplib/test/callback_api.js b/node_modules/amqplib/test/callback_api.js new file mode 100644 index 0000000..5aea0bf --- /dev/null +++ b/node_modules/amqplib/test/callback_api.js @@ -0,0 +1,313 @@ +'use strict'; + +var assert = require('assert'); +var crypto = require('crypto'); +var api = require('../callback_api'); +var util = require('./util'); +var schedule = util.schedule; +var randomString = util.randomString; +var kCallback = util.kCallback; +var domain = require('domain'); +var Buffer = require('safe-buffer').Buffer; + +var URL = process.env.URL || 'amqp://localhost'; + +function connect(cb) { + api.connect(URL, {}, cb); +} + +// Construct a node-style callback from a `done` function +function doneCallback(done) { + return function(err, _) { + if (err == null) done(); + else done(err); + }; +} + +function ignore() {} + +function twice(done) { + var first = function(err) { + if (err == undefined) second = done; + else second = ignore, done(err); + }; + var second = function(err) { + if (err == undefined) first = done; + else first = ignore, done(err); + }; + return {first: function(err) { first(err); }, + second: function(err) { second(err); }}; +} + +// Adapt 'done' to a callback that's expected to fail +function failCallback(done) { + return function(err, _) { + if (err == null) done(new Error('Expected failure, got ' + val)); + else done(); + }; +} + +function waitForMessages(ch, q, k) { + ch.checkQueue(q, function(e, ok) { + if (e != null) return k(e); + else if (ok.messageCount > 0) return k(null, ok); + else schedule(waitForMessages.bind(null, ch, q, k)); + }); +} + + +suite('connect', function() { + +test('at all', function(done) { + connect(doneCallback(done)); +}); + +}); + +function channel_test_fn(method) { + return function(name, chfun) { + test(name, function(done) { + connect(kCallback(function(c) { + c[method](kCallback(function(ch) { + chfun(ch, done); + }, done)); + }, done)); + }); + }; +} +var channel_test = channel_test_fn('createChannel'); +var confirm_channel_test = channel_test_fn('createConfirmChannel'); + +suite('channel open', function() { + +channel_test('at all', function(ch, done) { + done(); +}); + +channel_test('open and close', function(ch, done) { + ch.close(doneCallback(done)); +}); + +}); + +suite('assert, check, delete', function() { + +channel_test('assert, check, delete queue', function(ch, done) { + ch.assertQueue('test.cb.queue', {}, kCallback(function(q) { + ch.checkQueue('test.cb.queue', kCallback(function(ok) { + ch.deleteQueue('test.cb.queue', {}, doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('assert, check, delete exchange', function(ch, done) { + ch.assertExchange( + 'test.cb.exchange', 'topic', {}, kCallback(function(ex) { + ch.checkExchange('test.cb.exchange', kCallback(function(ok) { + ch.deleteExchange('test.cb.exchange', {}, doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('fail on check non-queue', function(ch, done) { + var both = twice(done); + ch.on('error', failCallback(both.first)); + ch.checkQueue('test.cb.nothere', failCallback(both.second)); +}); + +channel_test('fail on check non-exchange', function(ch, done) { + var both = twice(done); + ch.on('error', failCallback(both.first)); + ch.checkExchange('test.cb.nothere', failCallback(both.second)); +}); + +}); + +suite('bindings', function() { + +channel_test('bind queue', function(ch, done) { + ch.assertQueue('test.cb.bindq', {}, kCallback(function(q) { + ch.assertExchange( + 'test.cb.bindex', 'fanout', {}, kCallback(function(ex) { + ch.bindQueue(q.queue, ex.exchange, '', {}, + doneCallback(done)); + }, done)); + }, done)); +}); + +channel_test('bind exchange', function(ch, done) { + ch.assertExchange( + 'test.cb.bindex1', 'fanout', {}, kCallback(function(ex1) { + ch.assertExchange( + 'test.cb.bindex2', 'fanout', {}, kCallback(function(ex2) { + ch.bindExchange(ex1.exchange, + ex2.exchange, '', {}, + doneCallback(done)); + }, done)); + }, done)); +}); + +}); + +suite('sending messages', function() { + +channel_test('send to queue and consume noAck', function(ch, done) { + var msg = randomString(); + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e !== null) return done(e); + ch.consume(q.queue, function(m) { + if (m.content.toString() == msg) done(); + else done(new Error("message content doesn't match:" + + msg + " =/= " + m.content.toString())); + }, {noAck: true, exclusive: true}); + ch.sendToQueue(q.queue, Buffer.from(msg)); + }); +}); + +channel_test('send to queue and consume ack', function(ch, done) { + var msg = randomString(); + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e !== null) return done(e); + ch.consume(q.queue, function(m) { + if (m.content.toString() == msg) { + ch.ack(m); + done(); + } + else done(new Error("message content doesn't match:" + + msg + " =/= " + m.content.toString())); + }, {noAck: false, exclusive: true}); + ch.sendToQueue(q.queue, Buffer.from(msg)); + }); +}); + +channel_test('send to and get from queue', function(ch, done) { + ch.assertQueue('', {exclusive: true}, function(e, q) { + if (e != null) return done(e); + var msg = randomString(); + ch.sendToQueue(q.queue, Buffer.from(msg)); + waitForMessages(ch, q.queue, function(e, _) { + if (e != null) return done(e); + ch.get(q.queue, {noAck: true}, function(e, m) { + if (e != null) + return done(e); + else if (!m) + return done(new Error('Empty (false) not expected')); + else if (m.content.toString() == msg) + return done(); + else + return done( + new Error('Messages do not match: ' + + msg + ' =/= ' + m.content.toString())); + }); + }); + }); +}); + +}); + +suite('ConfirmChannel', function() { + +confirm_channel_test('Receive confirmation', function(ch, done) { + // An unroutable message, on the basis that you're not allowed a + // queue with an empty name, and you can't make bindings to the + // default exchange. Tricky eh? + ch.publish('', '', Buffer.from('foo'), {}, done); +}); + +confirm_channel_test('Wait for confirms', function(ch, done) { + for (var i=0; i < 1000; i++) { + ch.publish('', '', Buffer.from('foo'), {}); + } + ch.waitForConfirms(done); +}); + +}); + +suite("Error handling", function() { + +/* +I don't like having to do this, but there appears to be something +broken about domains in Node.JS v0.8 and mocha. Apparently it has to +do with how mocha and domains hook into error propogation: +https://github.com/visionmedia/mocha/issues/513 (summary: domains in +Node.JS v0.8 don't prevent uncaughtException from firing, and that's +what mocha uses to detect .. an uncaught exception). + +Using domains with amqplib *does* work in practice in Node.JS v0.8: +that is, it's possible to throw an exception in a callback and deal +with it in the active domain, and thereby avoid it crashing the +program. + */ +if (util.versionGreaterThan(process.versions.node, '0.8')) { + test('Throw error in connection open callback', function(done) { + var dom = domain.createDomain(); + dom.on('error', failCallback(done)); + connect(dom.bind(function(err, conn) { + throw new Error('Spurious connection open callback error'); + })); + }); +} + +// TODO: refactor {error_test, channel_test} +function error_test(name, fun) { + test(name, function(done) { + var dom = domain.createDomain(); + dom.run(function() { + connect(kCallback(function(c) { + // Seems like there were some unironed wrinkles in 0.8's + // implementation of domains; explicitly adding the connection + // to the domain makes sure any exception thrown in the course + // of processing frames is handled by the domain. For other + // versions of Node.JS, this ends up being belt-and-braces. + dom.add(c); + c.createChannel(kCallback(function(ch) { + fun(ch, done, dom); + }, done)); + }, done)); + }); + }); +} + +error_test('Channel open callback throws an error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + throw new Error('Error in open callback'); +}); + +error_test('RPC callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.prefetch(0, false, function(err, ok) { + throw new Error('Spurious callback error'); + }); +}); + +error_test('Get callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.assertQueue('test.cb.get-with-error', {}, function(err, ok) { + ch.get('test.cb.get-with-error', {noAck: true}, function() { + throw new Error('Spurious callback error'); + }); + }); +}); + +error_test('Consume callback throws error', function(ch, done, dom) { + dom.on('error', failCallback(done)); + ch.assertQueue('test.cb.consume-with-error', {}, function(err, ok) { + ch.consume('test.cb.consume-with-error', ignore, {noAck: true}, function() { + throw new Error('Spurious callback error'); + }); + }); +}); + +error_test('Get from non-queue invokes error k', function(ch, done, dom) { + var both = twice(failCallback(done)); + dom.on('error', both.first); + ch.get('', {}, both.second); +}); + +error_test('Consume from non-queue invokes error k', function(ch, done, dom) { + var both = twice(failCallback(done)); + dom.on('error', both.first); + ch.consume('', both.second); +}); + +}); diff --git a/node_modules/amqplib/test/channel.js b/node_modules/amqplib/test/channel.js new file mode 100644 index 0000000..a8a5a05 --- /dev/null +++ b/node_modules/amqplib/test/channel.js @@ -0,0 +1,612 @@ +// Test the channel machinery + +'use strict'; + +var assert = require('assert'); +var Promise = require('bluebird'); +var Channel = require('../lib/channel').Channel; +var Connection = require('../lib/connection').Connection; +var util = require('./util'); +var succeed = util.succeed, fail = util.fail, latch = util.latch; +var completes = util.completes; +var defs = require('../lib/defs'); +var conn_handshake = require('./connection').connection_handshake; +var OPEN_OPTS = require('./connection').OPEN_OPTS; +var Buffer = require('safe-buffer').Buffer; + +var LOG_ERRORS = process.env.LOG_ERRORS; + +function baseChannelTest(client, server) { + return function(done) { + var bothDone = latch(2, done); + var pair = util.socketPair(); + var c = new Connection(pair.client); + + if (LOG_ERRORS) c.on('error', console.warn); + + c.open(OPEN_OPTS, function(err, ok) { + if (err === null) client(c, bothDone); + else fail(bothDone); + }); + + pair.server.read(8); // discard the protocol header + var s = util.runServer(pair.server, function(send, await) { + conn_handshake(send, await) + .then(function() { + server(send, await, bothDone); + }, fail(bothDone)); + }); + }; +} + +function channelTest(client, server) { + return baseChannelTest( + function(conn, done) { + var ch = new Channel(conn); + if (LOG_ERRORS) ch.on('error', console.warn); + client(ch, done, conn); + }, + function(send, await, done) { + channel_handshake(send, await) + .then(function(ch) { + return server(send, await, done, ch); + }).then(null, fail(done)); // so you can return a promise to let + // errors bubble out + } + ); +}; + +function channel_handshake(send, await) { + return await(defs.ChannelOpen)() + .then(function(open) { + assert.notEqual(0, open.channel); + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, open.channel); + return open.channel; + }); +} + +// fields for deliver and publish and get-ok +var DELIVER_FIELDS = { + consumerTag: 'fake', + deliveryTag: 1, + redelivered: false, + exchange: 'foo', + routingKey: 'bar', + replyCode: defs.constants.NO_ROUTE, + replyText: 'derp', +}; + +function open(ch) { + return Promise.try(function() { + ch.allocate(); + return Promise.fromCallback(function(cb) { + ch._rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk, cb); + }); + }); +} + +suite("channel open and close", function() { + +test("open", channelTest( + function(ch, done) { + open(ch).then(succeed(done), fail(done)); + }, + function(send, await, done) { + done(); + })); + +test("bad server", baseChannelTest( + function(c, done) { + var ch = new Channel(c); + open(ch).then(fail(done), succeed(done)); + }, + function(send, await, done) { + return await(defs.ChannelOpen)() + .then(function(open) { + send(defs.ChannelCloseOk, {}, open.channel); + }).then(succeed(done), fail(done)); + })); + +test("open, close", channelTest( + function(ch, done) { + open(ch) + .then(function() { + return new Promise(function(resolve) { + ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS, resolve); + }); + }) + .then(succeed(done), fail(done)); + }, + function(send, await, done, ch) { + return await(defs.ChannelClose)() + .then(function(close) { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("server close", channelTest( + function(ch, done) { + ch.on('error', function(error) { + assert.strictEqual(504, error.code); + succeed(done)(); + }); + open(ch); + }, + function(send, await, done, ch) { + send(defs.ChannelClose, { + replyText: 'Forced close', + replyCode: defs.constants.CHANNEL_ERROR, + classId: 0, methodId: 0 + }, ch); + await(defs.ChannelCloseOk)() + .then(succeed(done), fail(done)); + })); + +test("overlapping channel/server close", channelTest( + function(ch, done, conn) { + var both = latch(2, done); + conn.on('error', succeed(both)); + ch.on('close', succeed(both)); + open(ch).then(function() { + ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS); + }, fail(both)); + }, + function(send, await, done, ch) { + await(defs.ChannelClose)() + .then(function() { + send(defs.ConnectionClose, { + replyText: 'Got there first', + replyCode: defs.constants.INTERNAL_ERROR, + classId: 0, methodId: 0 + }, 0); + }) + .then(await(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + +test("double close", channelTest( + function(ch, done) { + open(ch).then(function() { + ch.closeBecause("First close", defs.constants.REPLY_SUCCESS); + // NB no synchronisation, we do this straight away + assert.throws(function() { + ch.closeBecause("Second close", defs.constants.REPLY_SUCCESS); + }); + }).then(succeed(done), fail(done)); + }, + function(send, await, done, ch) { + await(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, { + }, ch); + }) + .then(succeed(done), fail(done)); + })); + +}); //suite + +suite("channel machinery", function() { + +test("RPC", channelTest( + function(ch, done) { + var rpcLatch = latch(3, done); + open(ch).then(function() { + + function wheeboom(err, f) { + if (err !== null) rpcLatch(err); + else rpcLatch(); + } + + var fields = { + prefetchCount: 10, + prefetchSize: 0, + global: false + }; + + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); + }).then(null, fail(rpcLatch)); + }, + function(send, await, done, ch) { + function sendOk(f) { + send(defs.BasicQosOk, {}, ch); + } + + return await(defs.BasicQos)() + .then(sendOk) + .then(await(defs.BasicQos)) + .then(sendOk) + .then(await(defs.BasicQos)) + .then(sendOk) + .then(succeed(done), fail(done)); + })); + +test("Bad RPC", channelTest( + function(ch, done) { + // We want to see the RPC rejected and the channel closed (with an + // error) + var errLatch = latch(2, done); + ch.on('error', function(error) { + assert.strictEqual(505, error.code); + succeed(errLatch)(); + }); + + open(ch) + .then(function() { + ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, + function(err) { + if (err !== null) errLatch(); + else errLatch(new Error('Expected RPC failure')); + }); + }, fail(errLatch)); + }, + function(send, await, done, ch) { + return await()() + .then(function() { + send(defs.BasicGetEmpty, {clusterId: ''}, ch); + }) // oh wait! that was wrong! expect a channel close + .then(await(defs.ChannelClose)) + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("RPC on closed channel", channelTest( + function(ch, done) { + open(ch); + + var close = new Promise(function(resolve) { + ch.on('error', function(error) { + assert.strictEqual(504, error.code); + resolve(); + }); + }); + + function failureCb(resolve, reject) { + return function(err) { + if (err !== null) resolve(); + else reject(); + } + } + + var fail1 = new Promise(function(resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, + failureCb(resolve, reject)); + }); + + var fail2 = new Promise(function(resolve, reject) { + return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, + failureCb(resolve, reject)); + }); + + Promise.join(close, fail1, fail2) + .then(succeed(done)) + .catch(fail(done)); + }, + function(send, await, done, ch) { + await(defs.BasicRecover)() + .then(function() { + send(defs.ChannelClose, { + replyText: 'Nuh-uh!', + replyCode: defs.constants.CHANNEL_ERROR, + methodId: 0, classId: 0 + }, ch); + return await(defs.ChannelCloseOk); + }) + .then(succeed(done)) + .catch(fail(done)); + })); + +test("publish all < single chunk threshold", channelTest( + function(ch, done) { + open(ch) + .then(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.from('foobar')); + }) + .then(succeed(done), fail(done)); + }, + function(send, await, done, ch) { + await(defs.BasicPublish)() + .then(await(defs.BasicProperties)) + .then(await(undefined)) // content frame + .then(function(f) { + assert.equal('foobar', f.content.toString()); + }).then(succeed(done), fail(done)); + })); + +test("publish content > single chunk threshold", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(3000)); + }, done); + }, + function(send, await, done, ch) { + await(defs.BasicPublish)() + .then(await(defs.BasicProperties)) + .then(await(undefined)) // content frame + .then(function(f) { + assert.equal(3000, f.content.length); + }).then(succeed(done), fail(done)); + })); + +test("publish method & headers > threshold", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, { + headers: {foo: Buffer.alloc(3000)} + }, Buffer.from('foobar')); + }, done); + }, + function(send, await, done, ch) { + await(defs.BasicPublish)() + .then(await(defs.BasicProperties)) + .then(await(undefined)) // content frame + .then(function(f) { + assert.equal('foobar', f.content.toString()); + }).then(succeed(done), fail(done)); + })); + +test("publish zero-length message", channelTest( + function(ch, done) { + open(ch); + completes(function() { + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(0)); + ch.sendMessage({ + exchange: 'foo', routingKey: 'bar', + mandatory: false, immediate: false, ticket: 0 + }, {}, Buffer.alloc(0)); + }, done); + }, + function(send, await, done, ch) { + await(defs.BasicPublish)() + .then(await(defs.BasicProperties)) + // no content frame for a zero-length message + .then(await(defs.BasicPublish)) + .then(succeed(done), fail(done)); + })); + +test("delivery", channelTest( + function(ch, done) { + open(ch); + ch.on('delivery', function(m) { + completes(function() { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + })); + +test("zero byte msg", channelTest( + function(ch, done) { + open(ch); + ch.on('delivery', function(m) { + completes(function() { + assert.deepEqual(Buffer.alloc(0), m.content); + }, done); + }); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('')); + }, done); + })); + +test("bad delivery", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('error', function(error) { + assert.strictEqual(505, error.code); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function(send, await, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + // now send another deliver without having sent the content + send(defs.BasicDeliver, DELIVER_FIELDS, ch); + return await(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("bad content send", channelTest( + function(ch, done) { + completes(function() { + open(ch); + assert.throws(function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {}, null); + }); + }, done); + }, + function(send, await, done, ch) { + done(); + })); + +test("bad properties send", channelTest( + function(ch, done) { + completes(function() { + open(ch); + assert.throws(function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {contentEncoding: 7}, + Buffer.from('foobar')); + }); + }, done); + }, + function(send, await, done, ch) { + done(); + })); + +test("bad consumer", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('delivery', function() { + throw new Error("I am a bad consumer"); + }); + ch.on('error', function(error) { + assert.strictEqual(541, error.code); + succeed(errorAndClose)(); + }); + ch.on('close', succeed(errorAndClose)); + open(ch); + }, + function(send, await, done, ch) { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + return await(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("bad send in consumer", channelTest( + function(ch, done) { + var errorAndClose = latch(2, done); + ch.on('close', succeed(errorAndClose)); + ch.on('error', function(error) { + assert.strictEqual(541, error.code); + succeed(errorAndClose)(); + }); + + ch.on('delivery', function() { + ch.sendMessage({routingKey: 'foo', + exchange: 'amq.direct'}, + {}, null); // can't send null + }); + + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicDeliver, DELIVER_FIELDS, ch, + Buffer.from('barfoo')); + }, done); + return await(defs.ChannelClose)() + .then(function() { + send(defs.ChannelCloseOk, {}, ch); + }).then(succeed(done), fail(done)); + })); + +test("return", channelTest( + function(ch, done) { + ch.on('return', function(m) { + completes(function() { + assert.equal('barfoo', m.content.toString()); + }, done); + }); + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicReturn, DELIVER_FIELDS, ch, Buffer.from('barfoo')); + }, done); + })); + +test("cancel", channelTest( + function(ch, done) { + ch.on('cancel', function(f) { + completes(function() { + assert.equal('product of society', f.consumerTag); + }, done); + }); + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicCancel, { + consumerTag: 'product of society', + nowait: false + }, ch); + }, done); + })); + +function confirmTest(variety, Method) { + return test('confirm ' + variety, channelTest( + function(ch, done) { + ch.on(variety, function(f) { + completes(function() { + assert.equal(1, f.deliveryTag); + }, done); + }); + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(Method, { + deliveryTag: 1, + multiple: false + }, ch); + }, done); + })); +} + +confirmTest("ack", defs.BasicAck); +confirmTest("nack", defs.BasicNack); + +test("out-of-order acks", channelTest( + function(ch, done) { + var allConfirms = latch(3, function() { + completes(function() { + assert.equal(0, ch.unconfirmed.length); + assert.equal(4, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + ch.pushConfirmCallback(allConfirms); + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 3, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + })); + +test("not all out-of-order acks", channelTest( + function(ch, done) { + var allConfirms = latch(2, function() { + completes(function() { + assert.equal(1, ch.unconfirmed.length); + assert.equal(3, ch.lwm); + }, done); + }); + ch.pushConfirmCallback(allConfirms); // tag = 1 + ch.pushConfirmCallback(allConfirms); // tag = 2 + ch.pushConfirmCallback(function() { + done(new Error('Confirm callback should not be called')); + }); + open(ch); + }, + function(send, await, done, ch) { + completes(function() { + send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); + send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); + }, done); + })); + +}); diff --git a/node_modules/amqplib/test/channel_api.js b/node_modules/amqplib/test/channel_api.js new file mode 100644 index 0000000..99c9f9c --- /dev/null +++ b/node_modules/amqplib/test/channel_api.js @@ -0,0 +1,584 @@ +'use strict'; + +var assert = require('assert'); +var api = require('../channel_api'); +var util = require('./util'); +var succeed = util.succeed, fail = util.fail; +var schedule = util.schedule; +var randomString = util.randomString; +var Promise = require('bluebird'); +var Buffer = require('safe-buffer').Buffer; + +var URL = process.env.URL || 'amqp://localhost'; + +function connect() { + return api.connect(URL); +} + +// Expect this promise to fail, and flip the results accordingly. +function expectFail(promise) { + return new Promise(function(resolve, reject) { + return promise.then(reject).catch(resolve); + }); +} + +// I'll rely on operations being rejected, rather than the channel +// close error, to detect failure. +function ignore () {} +function ignoreErrors(c) { + c.on('error', ignore); return c; +} +function logErrors(c) { + c.on('error', console.warn); return c; +} + +// Run a test with `name`, given a function that takes an open +// channel, and returns a promise that is resolved on test success or +// rejected on test failure. +function channel_test(chmethod, name, chfun) { + test(name, function(done) { + connect(URL).then(logErrors).then(function(c) { + c[chmethod]().then(ignoreErrors).then(chfun) + .then(succeed(done), fail(done)) + // close the connection regardless of what happens with the test + .finally(function() {c.close();}); + }); + }); +} + +var chtest = channel_test.bind(null, 'createChannel'); + +suite("connect", function() { + +test("at all", function(done) { + connect(URL).then(function(c) { + return c.close() + ;}).then(succeed(done), fail(done)); +}); + +chtest("create channel", ignore); // i.e., just don't bork + +}); + +var QUEUE_OPTS = {durable: false}; +var EX_OPTS = {durable: false}; + +suite("assert, check, delete", function() { + +chtest("assert and check queue", function(ch) { + return ch.assertQueue('test.check-queue', QUEUE_OPTS) + .then(function(qok) { + return ch.checkQueue('test.check-queue'); + }); +}); + +chtest("assert and check exchange", function(ch) { + return ch.assertExchange('test.check-exchange', 'direct', EX_OPTS) + .then(function(eok) { + assert.equal('test.check-exchange', eok.exchange); + return ch.checkExchange('test.check-exchange'); + }); +}); + +chtest("fail on reasserting queue with different options", + function(ch) { + var q = 'test.reassert-queue'; + return ch.assertQueue( + q, {durable: false, autoDelete: true}) + .then(function() { + return expectFail( + ch.assertQueue(q, {durable: false, + autoDelete: false})); + }); + }); + +chtest("fail on checking a queue that's not there", function(ch) { + return expectFail(ch.checkQueue('test.random-' + randomString())); +}); + +chtest("fail on checking an exchange that's not there", function(ch) { + return expectFail(ch.checkExchange('test.random-' + randomString())); +}); + +chtest("fail on reasserting exchange with different type", + function(ch) { + var ex = 'test.reassert-ex'; + return ch.assertExchange(ex, 'fanout', EX_OPTS) + .then(function() { + return expectFail( + ch.assertExchange(ex, 'direct', EX_OPTS)); + }); + }); + +chtest("channel break on publishing to non-exchange", function(ch) { + return new Promise(function(resolve) { + ch.on('error', resolve); + ch.publish(randomString(), '', Buffer.from('foobar')); + }); +}); + +chtest("delete queue", function(ch) { + var q = 'test.delete-queue'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.checkQueue(q)) + .then(function() { + return ch.deleteQueue(q);}) + .then(function() { + return expectFail(ch.checkQueue(q));}); +}); + +chtest("delete exchange", function(ch) { + var ex = 'test.delete-exchange'; + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.checkExchange(ex)) + .then(function() { + return ch.deleteExchange(ex);}) + .then(function() { + return expectFail(ch.checkExchange(ex));}); +}); + +}); + +// Wait for the queue to meet the condition; useful for waiting for +// messages to arrive, for example. +function waitForQueue(q, condition) { + return connect(URL).then(function(c) { + return c.createChannel() + .then(function(ch) { + return ch.checkQueue(q).then(function(qok) { + function check() { + return ch.checkQueue(q).then(function(qok) { + if (condition(qok)) { + c.close(); + return qok; + } + else schedule(check); + }); + } + return check(); + }); + }); + }); +} + +// Return a promise that resolves when the queue has at least `num` +// messages. If num is not supplied its assumed to be 1. +function waitForMessages(q, num) { + var min = (num === undefined) ? 1 : num; + return waitForQueue(q, function(qok) { + return qok.messageCount >= min; + }); +} + +suite("sendMessage", function() { + +// publish different size messages +chtest("send to queue and get from queue", function(ch) { + var q = 'test.send-to-q'; + var msg = randomString(); + return Promise.join(ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg)); + return waitForMessages(q); + }) + .then(function() { + return ch.get(q, {noAck: true}); + }) + .then(function(m) { + assert(m); + assert.equal(msg, m.content.toString()); + }); +}); + +chtest("send (and get) zero content to queue", function(ch) { + var q = 'test.send-to-q'; + var msg = Buffer.alloc(0); + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, msg); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(m); + assert.deepEqual(msg, m.content); + }); +}); + +}); + +suite("binding, consuming", function() { + +// bind, publish, get +chtest("route message", function(ch) { + var ex = 'test.route-message'; + var q = 'test.route-message-q'; + var msg = randomString(); + + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindQueue(q, ex, '', {})) + .then(function() { + ch.publish(ex, '', Buffer.from(msg)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(m); + assert.equal(msg, m.content.toString()); + }); +}); + +// send to queue, purge, get-empty +chtest("purge queue", function(ch) { + var q = 'test.purge-queue'; + return ch.assertQueue(q, {durable: false}) + .then(function() { + ch.sendToQueue(q, Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { + ch.purgeQueue(q); + return ch.get(q, {noAck: true});}) + .then(function(m) { + assert(!m); // get-empty + }); +}); + +// bind again, unbind, publish, get-empty +chtest("unbind queue", function(ch) { + var ex = 'test.unbind-queue-ex'; + var q = 'test.unbind-queue'; + var viabinding = randomString(); + var direct = randomString(); + + return Promise.join( + ch.assertExchange(ex, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindQueue(q, ex, '', {})) + .then(function() { + ch.publish(ex, '', Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { // message got through! + return ch.get(q, {noAck:true}) + .then(function(m) {assert(m);});}) + .then(function() { + return ch.unbindQueue(q, ex, '', {});}) + .then(function() { + // via the no-longer-existing binding + ch.publish(ex, '', Buffer.from(viabinding)); + // direct to the queue + ch.sendToQueue(q, Buffer.from(direct)); + return waitForMessages(q);}) + .then(function() {return ch.get(q)}) + .then(function(m) { + // the direct to queue message got through, the via-binding + // message (sent first) did not + assert.equal(direct, m.content.toString()); + }); +}); + +// To some extent this is now just testing semantics of the server, +// but we can at least try out a few settings, and consume. +chtest("consume via exchange-exchange binding", function(ch) { + var ex1 = 'test.ex-ex-binding1', ex2 = 'test.ex-ex-binding2'; + var q = 'test.ex-ex-binding-q'; + var rk = 'test.routing.key', msg = randomString(); + return Promise.join( + ch.assertExchange(ex1, 'direct', EX_OPTS), + ch.assertExchange(ex2, 'fanout', + {durable: false, internal: true}), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindExchange(ex2, ex1, rk, {}), + ch.bindQueue(q, ex2, '', {})) + .then(function() { + return new Promise(function(resolve, reject) { + function delivery(m) { + if (m.content.toString() === msg) resolve(); + else reject(new Error("Wrong message")); + } + ch.consume(q, delivery, {noAck: true}) + .then(function() { + ch.publish(ex1, rk, Buffer.from(msg)); + }); + }); + }); +}); + +// bind again, unbind, publish, get-empty +chtest("unbind exchange", function(ch) { + var source = 'test.unbind-ex-source'; + var dest = 'test.unbind-ex-dest'; + var q = 'test.unbind-ex-queue'; + var viabinding = randomString(); + var direct = randomString(); + + return Promise.join( + ch.assertExchange(source, 'fanout', EX_OPTS), + ch.assertExchange(dest, 'fanout', EX_OPTS), + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + ch.bindExchange(dest, source, '', {}), + ch.bindQueue(q, dest, '', {})) + .then(function() { + ch.publish(source, '', Buffer.from('foobar')); + return waitForMessages(q);}) + .then(function() { // message got through! + return ch.get(q, {noAck:true}) + .then(function(m) {assert(m);});}) + .then(function() { + return ch.unbindExchange(dest, source, '', {});}) + .then(function() { + // via the no-longer-existing binding + ch.publish(source, '', Buffer.from(viabinding)); + // direct to the queue + ch.sendToQueue(q, Buffer.from(direct)); + return waitForMessages(q);}) + .then(function() {return ch.get(q)}) + .then(function(m) { + // the direct to queue message got through, the via-binding + // message (sent first) did not + assert.equal(direct, m.content.toString()); + }); +}); + +// This is a bit convoluted. Sorry. +chtest("cancel consumer", function(ch) { + var q = 'test.consumer-cancel'; + var ctag; + var recv1 = new Promise(function (resolve, reject) { + Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q), + // My callback is 'resolve the promise in `arrived`' + ch.consume(q, resolve, {noAck:true}) + .then(function(ok) { + ctag = ok.consumerTag; + ch.sendToQueue(q, Buffer.from('foo')); + })); + }); + + // A message should arrive because of the consume + return recv1.then(function() { + var recv2 = Promise.join( + ch.cancel(ctag).then(function() { + return ch.sendToQueue(q, Buffer.from('bar')); + }), + // but check a message did arrive in the queue + waitForMessages(q)) + .then(function() { + return ch.get(q, {noAck:true}); + }) + .then(function(m) { + // I'm going to reject it, because I flip succeed/fail + // just below + if (m.content.toString() === 'bar') { + throw new Error(); + } + }); + + return expectFail(recv2); + }); +}); + +chtest("cancelled consumer", function(ch) { + var q = 'test.cancelled-consumer'; + return new Promise(function(resolve, reject) { + return Promise.join( + ch.assertQueue(q), + ch.purgeQueue(q), + ch.consume(q, function(msg) { + if (msg === null) resolve(); + else reject(new Error('Message not expected')); + })) + .then(function() { + return ch.deleteQueue(q); + }); + }); +}); + +// ack, by default, removes a single message from the queue +chtest("ack", function(ch) { + var q = 'test.ack'; + var msg1 = randomString(), msg2 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), + ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + ch.sendToQueue(q, Buffer.from(msg2)); + return waitForMessages(q, 2); + }) + .then(function() { + return ch.get(q, {noAck: false}) + }) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.ack(m); + // %%% is there a race here? may depend on + // rabbitmq-sepcific semantics + return ch.get(q); + }) + .then(function(m) { + assert(m); + assert.equal(msg2, m.content.toString()); + }); +}); + +// Nack, by default, puts a message back on the queue (where in the +// queue is up to the server) +chtest("nack", function(ch) { + var q = 'test.nack'; + var msg1 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: false})}) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.nack(m); + return waitForMessages(q);}) + .then(function() { + return ch.get(q);}) + .then(function(m) { + assert(m); + assert.equal(msg1, m.content.toString()); + }); +}); + +// reject is a near-synonym for nack, the latter of which is not +// available in earlier RabbitMQ (or in AMQP proper). +chtest("reject", function(ch) { + var q = 'test.reject'; + var msg1 = randomString(); + + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + ch.sendToQueue(q, Buffer.from(msg1)); + return waitForMessages(q);}) + .then(function() { + return ch.get(q, {noAck: false})}) + .then(function(m) { + assert.equal(msg1, m.content.toString()); + ch.reject(m); + return waitForMessages(q);}) + .then(function() { + return ch.get(q);}) + .then(function(m) { + assert(m); + assert.equal(msg1, m.content.toString()); + }); +}); + +chtest("prefetch", function(ch) { + var q = 'test.prefetch'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), + ch.prefetch(1)) + .then(function() { + ch.sendToQueue(q, Buffer.from('foobar')); + ch.sendToQueue(q, Buffer.from('foobar')); + return waitForMessages(q, 2); + }) + .then(function() { + return new Promise(function(resolve) { + var messageCount = 0; + function receive(msg) { + ch.ack(msg); + if (++messageCount > 1) { + resolve(messageCount); + } + } + return ch.consume(q, receive, {noAck: false}) + }); + }) + .then(function(c) { + return assert.equal(2, c); + }); +}); + +chtest('close', function(ch) { + // Resolving promise guarantees + // channel is closed + return ch.close(); +}); + +}); + +var confirmtest = channel_test.bind(null, 'createConfirmChannel'); + +suite("confirms", function() { + +confirmtest('message is confirmed', function(ch) { + var q = 'test.confirm-message'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + return ch.sendToQueue(q, Buffer.from('bleep')); + }); +}); + +// Usually one can provoke the server into confirming more than one +// message in an ack by simply sending a few messages in quick +// succession; a bit unscientific I know. Luckily we can eavesdrop on +// the acknowledgements coming through to see if we really did get a +// multi-ack. +confirmtest('multiple confirms', function(ch) { + var q = 'test.multiple-confirms'; + return Promise.join( + ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) + .then(function() { + var multipleRainbows = false; + ch.on('ack', function(a) { + if (a.multiple) multipleRainbows = true; + }); + + function prod(num) { + var cs = []; + + function sendAndPushPromise() { + var conf = Promise.fromCallback(function(cb) { + return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb); + }); + cs.push(conf); + } + + for (var i=0; i < num; i++) sendAndPushPromise(); + + return Promise.all(cs).then(function() { + if (multipleRainbows) return true; + else if (num > 500) throw new Error( + "Couldn't provoke the server" + + " into multi-acking with " + num + + " messages; giving up"); + else { + //console.warn("Failed with " + num + "; trying " + num * 2); + return prod(num * 2); + } + }); + } + return prod(5); + }); +}); + +confirmtest('wait for confirms', function(ch) { + for (var i=0; i < 1000; i++) { + ch.publish('', '', Buffer.from('foobar'), {}); + } + return ch.waitForConfirms(); +}) + +}); diff --git a/node_modules/amqplib/test/codec.js b/node_modules/amqplib/test/codec.js new file mode 100644 index 0000000..55a326f --- /dev/null +++ b/node_modules/amqplib/test/codec.js @@ -0,0 +1,238 @@ +'use strict'; + +var codec = require('../lib/codec'); +var defs = require('../lib/defs'); +var assert = require('assert'); +var ints = require('buffer-more-ints'); +var Buffer = require('safe-buffer').Buffer +var C = require('claire'); +var forAll = C.forAll; + +// These just test known encodings; to generate the answers I used +// RabbitMQ's binary generator module. + +var testCases = [ + // integers + ['byte', {byte: 112}, [4,98,121,116,101,98,112]], + ['byte max value', {byte: 127}, [4,98,121,116,101,98,127]], + ['byte min value', {byte: -128}, [4,98,121,116,101,98,128]], + ['< -128 promoted to signed short', {short: -129}, [5,115,104,111,114,116,115,255,127]], + ['> 127 promoted to short', {short: 128}, [5,115,104,111,114,116,115,0,128]], + ['< 2^15 still a short', {short: 0x7fff}, [5,115,104,111,114,116,115,127,255]], + ['-2^15 still a short', {short: -0x8000}, [5,115,104,111,114,116,115,128,0]], + ['>= 2^15 promoted to int', {int: 0x8000}, [3,105,110,116,73,0,0,128,0]], + ['< -2^15 promoted to int', {int: -0x8001}, [3,105,110,116,73,255,255,127,255]], + ['< 2^31 still an int', {int: 0x7fffffff}, [3,105,110,116,73,127,255,255,255]], + ['>= -2^31 still an int', {int: -0x80000000}, [3,105,110,116,73,128,0,0,0]], + ['>= 2^31 promoted to long', {long: 0x80000000}, [4,108,111,110,103,108,0,0,0,0,128,0,0,0]], + ['< -2^31 promoted to long', {long: -0x80000001}, [4,108,111,110,103,108,255,255,255,255,127,255,255,255]], + + // floating point + ['float value', {double: 0.5}, [6,100,111,117,98,108,101,100,63,224,0,0,0,0,0,0]], + ['negative float value', {double: -0.5}, [6,100,111,117,98,108,101,100,191,224,0,0,0,0,0,0]], + // %% test some boundaries of precision? + + // string + ['string', {string: "boop"}, [6,115,116,114,105,110,103,83,0,0,0,4,98,111,111,112]], + + // buffer -> byte array + ['byte array from buffer', {bytes: Buffer.from([1,2,3,4])}, + [5,98,121,116,101,115,120,0,0,0,4,1,2,3,4]], + + // boolean, void + ['true', {bool: true}, [4,98,111,111,108,116,1]], + ['false', {bool: false}, [4,98,111,111,108,116,0]], + ['null', {'void': null}, [4,118,111,105,100,86]], + + // array, object + ['array', {array: [6, true, "foo"]}, + [5,97,114,114,97,121,65,0,0,0,12,98,6,116,1,83,0,0,0,3,102,111,111]], + ['object', {object: {foo: "bar", baz: 12}}, + [6,111,98,106,101,99,116,70,0,0,0,18,3,102,111,111,83,0, + 0,0,3,98,97,114,3,98,97,122,98,12]], + + // exotic types + ['timestamp', {timestamp: {'!': 'timestamp', value: 1357212277527}}, + [9,116,105,109,101,115,116,97,109,112,84,0,0,1,60,0,39,219,23]], + ['decimal', {decimal: {'!': 'decimal', value: {digits: 2345, places: 2}}}, + [7,100,101,99,105,109,97,108,68,2,0,0,9,41]], + ['float', {float: {'!': 'float', value: 0.1}}, + [5,102,108,111,97,116,102,61,204,204,205]], +]; + +function bufferToArray(b) { + return Array.prototype.slice.call(b); +} + +suite("Implicit encodings", function() { + + testCases.forEach(function(tc) { + var name = tc[0], val = tc[1], expect = tc[2]; + test(name, function() { + var buffer = Buffer.alloc(1000); + var size = codec.encodeTable(buffer, val, 0); + var result = buffer.slice(4, size); + assert.deepEqual(expect, bufferToArray(result)); + }); + }); +}); + +// Whole frames + +var amqp = require('./data'); + +function roundtrip_table(t) { + var buf = Buffer.alloc(4096); + var size = codec.encodeTable(buf, t, 0); + var decoded = codec.decodeFields(buf.slice(4, size)); // ignore the length-prefix + try { + assert.deepEqual(removeExplicitTypes(t), decoded); + } + catch (e) { return false; } + return true; +} + +function roundtrips(T) { + return forAll(T).satisfy(function(v) { return roundtrip_table({value: v}); }); +} + +suite("Roundtrip values", function() { + [ + amqp.Octet, + amqp.ShortStr, + amqp.LongStr, + amqp.UShort, + amqp.ULong, + amqp.ULongLong, + amqp.UShort, + amqp.Short, + amqp.Long, + amqp.Bit, + amqp.Decimal, + amqp.Timestamp, + amqp.Double, + amqp.Float, + amqp.FieldArray, + amqp.FieldTable + ].forEach(function(T) { + test(T.toString() + ' roundtrip', roundtrips(T).asTest()); + }); +}); + +// When encoding, you can supply explicitly-typed fields like `{'!': +// int32, 50}`. Most of these do not appear in the decoded values, so +// to compare like-to-like we have to remove them from the input. +function removeExplicitTypes(input) { + switch (typeof input) { + case 'object': + if (input == null) { + return null; + } + if (Array.isArray(input)) { + var newArr = []; + for (var i = 0; i < input.length; i++) { + newArr[i] = removeExplicitTypes(input[i]); + } + return newArr; + } + if (Buffer.isBuffer(input)) { + return input; + } + switch (input['!']) { + case 'timestamp': + case 'decimal': + case 'float': + return input; + case undefined: + var newObj = {} + for (var k in input) { + newObj[k] = removeExplicitTypes(input[k]); + } + return newObj; + default: + return input.value; + } + + default: + return input; + } +} + +// Asserts that the decoded fields are equal to the original fields, +// or equal to a default where absent in the original. The defaults +// depend on the type of method or properties. +// +// This works slightly different for methods and properties: for +// methods, each field must have a value, so the default is +// substituted for undefined values when encoding; for properties, +// fields may be absent in the encoded value, so a default is +// substituted for missing fields when decoding. The effect is the +// same so far as these tests are concerned. +function assertEqualModuloDefaults(original, decodedFields) { + var args = defs.info(original.id).args; + for (var i=0; i < args.length; i++) { + var arg = args[i]; + var originalValue = original.fields[arg.name]; + var decodedValue = decodedFields[arg.name]; + try { + if (originalValue === undefined) { + // longstr gets special treatment here, since the defaults are + // given as strings rather than buffers, but the decoded values + // will be buffers. + assert.deepEqual((arg.type === 'longstr') ? + Buffer.from(arg.default) : arg.default, + decodedValue); + } + else { + assert.deepEqual(removeExplicitTypes(originalValue), decodedValue); + } + } + catch (assertionErr) { + var methodOrProps = defs.info(original.id).name; + assertionErr.message += ' (frame ' + methodOrProps + + ' field ' + arg.name + ')'; + throw assertionErr; + } + } + // %%% TODO make sure there's no surplus fields + return true; +} + +// This is handy for elsewhere +module.exports.assertEqualModuloDefaults = assertEqualModuloDefaults; + +function roundtripMethod(Method) { + return forAll(Method).satisfy(function(method) { + var buf = defs.encodeMethod(method.id, 0, method.fields); + // FIXME depends on framing, ugh + var fs1 = defs.decode(method.id, buf.slice(11, buf.length)); + assertEqualModuloDefaults(method, fs1); + return true; + }); +} + +function roundtripProperties(Properties) { + return forAll(Properties).satisfy(function(properties) { + var buf = defs.encodeProperties(properties.id, 0, properties.size, + properties.fields); + // FIXME depends on framing, ugh + var fs1 = defs.decode(properties.id, buf.slice(19, buf.length)); + assert.equal(properties.size, ints.readUInt64BE(buf, 11)); + assertEqualModuloDefaults(properties, fs1); + return true; + }); +} + +suite("Roundtrip methods", function() { + amqp.methods.forEach(function(Method) { + test(Method.toString() + ' roundtrip', + roundtripMethod(Method).asTest()); + }); +}); + +suite("Roundtrip properties", function() { + amqp.properties.forEach(function(Properties) { + test(Properties.toString() + ' roundtrip', + roundtripProperties(Properties).asTest()); + }); +}); diff --git a/node_modules/amqplib/test/connect.js b/node_modules/amqplib/test/connect.js new file mode 100644 index 0000000..277c364 --- /dev/null +++ b/node_modules/amqplib/test/connect.js @@ -0,0 +1,127 @@ +'use strict'; + +var connect = require('../lib/connect').connect; +var Buffer = require('safe-buffer').Buffer +var credentialsFromUrl = require('../lib/connect').credentialsFromUrl; +var assert = require('assert'); +var util = require('./util'); +var net = require('net'); +var fail = util.fail, succeed = util.succeed, + kCallback = util.kCallback, + succeedIfAttributeEquals = util.succeedIfAttributeEquals; +var format = require('util').format; + +var URL = process.env.URL || 'amqp://localhost'; + +suite("Credentials", function() { + + function checkCreds(creds, user, pass, done) { + if (creds.mechanism != 'PLAIN') { + return done('expected mechanism PLAIN'); + } + if (creds.username != user || creds.password != pass) { + return done(format("expected '%s', '%s'; got '%s', '%s'", + user, pass, creds.username, creds.password)); + } + done(); + } + + test("no creds", function(done) { + var parts = {auth: ''}; + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'guest', 'guest', done); + }); + test("usual user:pass", function(done) { + var parts = {auth: 'user:pass'}; + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'user', 'pass', done); + }); + test("missing user", function(done) { + var parts = {auth: ':password'}; + var creds = credentialsFromUrl(parts); + checkCreds(creds, '', 'password', done); + }); + test("missing password", function(done) { + var parts = {auth: 'username'}; + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'username', '', done); + }); + test("colon in password", function(done) { + var parts = {auth: 'username:pass:word'}; + var creds = credentialsFromUrl(parts); + checkCreds(creds, 'username', 'pass:word', done); + }); +}); + +suite("Connect API", function() { + + test("Connection refused", function(done) { + connect('amqp://localhost:23450', {}, + kCallback(fail(done), succeed(done))); + }); + + // %% this ought to fail the promise, rather than throwing an error + test("bad URL", function() { + assert.throws(function() { + connect('blurble'); + }); + }); + + test("wrongly typed open option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var q = parts.query || {}; + q.frameMax = 'NOT A NUMBER'; + parts.query = q; + var u = url.format(parts); + connect(u, {}, kCallback(fail(done), succeed(done))); + }); + + test("using custom heartbeat option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var config = parts.query || {}; + config.heartbeat = 20; + connect(config, {}, kCallback(succeedIfAttributeEquals('heartbeat', 20, done), fail(done))); + }); + + test("wrongly typed heartbeat option", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var config = parts.query || {}; + config.heartbeat = 'NOT A NUMBER'; + connect(config, {}, kCallback(fail(done), succeed(done))); + }); + + test("using plain credentials", function(done) { + var url = require('url'); + var parts = url.parse(URL, true); + var u = 'guest', p = 'guest'; + if (parts.auth) { + var auth = parts.auth.split(":"); + u = auth[0], p = auth[1]; + } + connect(URL, {credentials: require('../lib/credentials').plain(u, p)}, + kCallback(succeed(done), fail(done))); + }); + + test("using unsupported mechanism", function(done) { + var creds = { + mechanism: 'UNSUPPORTED', + response: function() { return Buffer.from(''); } + }; + connect(URL, {credentials: creds}, + kCallback(fail(done), succeed(done))); + }); + + test("with a given connection timeout", function(done) { + var timeoutServer = net.createServer(function() {}).listen(31991); + + connect('amqp://localhost:31991', {timeout: 50}, function(err, val) { + timeoutServer.close(); + if (val) done(new Error('Expected connection timeout, did not')); + else done(); + }); + }); + +}); diff --git a/node_modules/amqplib/test/connection.js b/node_modules/amqplib/test/connection.js new file mode 100644 index 0000000..cec3c3d --- /dev/null +++ b/node_modules/amqplib/test/connection.js @@ -0,0 +1,391 @@ +'use strict'; + +var assert = require('assert'); +var defs = require('../lib/defs'); +var Buffer = require('safe-buffer').Buffer; +var Connection = require('../lib/connection').Connection; +var HEARTBEAT = require('../lib/frame').HEARTBEAT; +var HB_BUF = require('../lib/frame').HEARTBEAT_BUF; +var util = require('./util'); +var succeed = util.succeed, fail = util.fail, latch = util.latch; +var completes = util.completes; +var kCallback = util.kCallback; + +var LOG_ERRORS = process.env.LOG_ERRORS; + +var OPEN_OPTS = { + // start-ok + 'clientProperties': {}, + 'mechanism': 'PLAIN', + 'response': Buffer.from(['', 'guest', 'guest'].join(String.fromCharCode(0))), + 'locale': 'en_US', + + // tune-ok + 'channelMax': 0, + 'frameMax': 0, + 'heartbeat': 0, + + // open + 'virtualHost': '/', + 'capabilities': '', + 'insist': 0 +}; +module.exports.OPEN_OPTS = OPEN_OPTS; + +function happy_open(send, await) { + // kick it off + send(defs.ConnectionStart, + {versionMajor: 0, + versionMinor: 9, + serverProperties: {}, + mechanisms: Buffer.from('PLAIN'), + locales: Buffer.from('en_US')}); + return await(defs.ConnectionStartOk)() + .then(function(f) { + send(defs.ConnectionTune, + {channelMax: 0, + heartbeat: 0, + frameMax: 0}); + }) + .then(await(defs.ConnectionTuneOk)) + .then(await(defs.ConnectionOpen)) + .then(function(f) { + send(defs.ConnectionOpenOk, + {knownHosts: ''}); + }); +} +module.exports.connection_handshake = happy_open; + +function connectionTest(client, server) { + return function(done) { + var bothDone = latch(2, done); + var pair = util.socketPair(); + var c = new Connection(pair.client); + if (LOG_ERRORS) c.on('error', console.warn); + client(c, bothDone); + + // NB only not a race here because the writes are synchronous + var protocolHeader = pair.server.read(8); + assert.deepEqual(Buffer.from("AMQP" + String.fromCharCode(0,0,9,1)), + protocolHeader); + + var s = util.runServer(pair.server, function(send, await) { + server(send, await, bothDone, pair.server); + }); + }; +} + +suite("Connection errors", function() { + + test("socket close during open", function(done) { + // RabbitMQ itself will take at least 3 seconds to close the socket + // in the event of a handshake problem. Instead of using a live + // connection, I'm just going to pretend. + var pair = util.socketPair(); + var conn = new Connection(pair.client); + pair.server.on('readable', function() { + pair.server.end(); + }); + conn.open({}, kCallback(fail(done), succeed(done))); + }); + + test("bad frame during open", function(done) { + var ss = util.socketPair(); + var conn = new (require('../lib/connection').Connection)(ss.client); + ss.server.on('readable', function() { + ss.server.write(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); + }); + conn.open({}, kCallback(fail(done), succeed(done))); + }); + +}); + +suite("Connection open", function() { + +test("happy", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(succeed(done), fail(done))); + }, + function(send, await, done) { + happy_open(send, await).then(succeed(done), fail(done)); + })); + +test("wrong first frame", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function(send, await, done) { + // bad server! bad! whatever were you thinking? + completes(function() { + send(defs.ConnectionTune, + {channelMax: 0, + heartbeat: 0, + frameMax: 0}); + }, done); + })); + +test("unexpected socket close", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); + }, + function(send, await, done, socket) { + send(defs.ConnectionStart, + {versionMajor: 0, + versionMinor: 9, + serverProperties: {}, + mechanisms: Buffer.from('PLAIN'), + locales: Buffer.from('en_US')}); + return await(defs.ConnectionStartOk)() + .then(function() { + socket.end(); + }) + .then(succeed(done), fail(done)); + })); + +}); + +suite("Connection running", function() { + +test("wrong frame on channel 0", connectionTest( + function(c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done) { + happy_open(send, await) + .then(function() { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 0); + }) + .then(await(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}, 0); + }).then(succeed(done), fail(done)); + })); + +test("unopened channel", connectionTest( + function(c, done) { + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done) { + happy_open(send, await) + .then(function() { + // there's actually nothing that would plausibly be sent to a + // just opened connection, so this is violating more than one + // rule. Nonetheless. + send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 3); + }) + .then(await(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}, 0); + }).then(succeed(done), fail(done)); + })); + +test("unexpected socket close", connectionTest( + function(c, done) { + var errorAndClosed = latch(2, done); + c.on('error', succeed(errorAndClosed)); + c.on('close', succeed(errorAndClosed)); + c.open(OPEN_OPTS, kCallback(function() { + c.sendHeartbeat(); + }, fail(errorAndClosed))); + }, + function(send, await, done, socket) { + happy_open(send, await) + .then(await()) + .then(function() { + socket.end(); + }).then(succeed(done)); + })); + +test("connection.blocked", connectionTest( + function(c, done) { + c.on('blocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done, socket) { + happy_open(send, await) + .then(function() { + send(defs.ConnectionBlocked, {reason: 'felt like it'}, 0); + }) + .then(succeed(done)); + })); + +test("connection.unblocked", connectionTest( + function(c, done) { + c.on('unblocked', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done, socket) { + happy_open(send, await) + .then(function() { + send(defs.ConnectionUnblocked, {}, 0); + }) + .then(succeed(done)); + })); + + +}); + +suite("Connection close", function() { + +test("happy", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open(OPEN_OPTS, kCallback(function(_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, function() {})); + }, + function(send, await, done) { + happy_open(send, await) + .then(await(defs.ConnectionClose)) + .then(function(close) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +test("interleaved close frames", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', done); + c.open(OPEN_OPTS, kCallback(function(_ok) { + c.close(kCallback(succeed(done), fail(done))); + }, done)); + }, + function(send, await, done) { + happy_open(send, await) + .then(await(defs.ConnectionClose)) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Ha!", + replyCode: defs.constants.REPLY_SUCCESS, + methodId: 0, classId: 0 + }); + }) + .then(await(defs.ConnectionCloseOk)) + .then(function(f) { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +test("server error close", connectionTest( + function(c, done0) { + var done = latch(2, done0); + c.on('close', succeed(done)); + c.on('error', succeed(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done) { + happy_open(send, await) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Begone", + replyCode: defs.constants.INTERNAL_ERROR, + methodId: 0, classId: 0 + }); + }) + .then(await(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + +test("operator-intiated close", connectionTest( + function(c, done) { + c.on('close', succeed(done)); + c.on('error', fail(done)); + c.open(OPEN_OPTS); + }, + function(send, await, done) { + happy_open(send, await) + .then(function(f) { + send(defs.ConnectionClose, { + replyText: "Begone", + replyCode: defs.constants.CONNECTION_FORCED, + methodId: 0, classId: 0 + }); + }) + .then(await(defs.ConnectionCloseOk)) + .then(succeed(done), fail(done)); + })); + + +test("double close", connectionTest( + function(c, done) { + c.open(OPEN_OPTS, kCallback(function() { + c.close(); + // NB no synchronisation, we do this straight away + assert.throws(function() { + c.close(); + }); + done(); + }, done)); + }, + function(send, await, done) { + happy_open(send, await) + .then(await(defs.ConnectionClose)) + .then(function() { + send(defs.ConnectionCloseOk, {}); + }) + .then(succeed(done), fail(done)); + })); + +}); + +suite("heartbeats", function() { + +var heartbeat = require('../lib/heartbeat'); + +setup(function() { + heartbeat.UNITS_TO_MS = 20; +}); + +teardown(function() { + heartbeat.UNITS_TO_MS = 1000; +}); + +test("send heartbeat after open", connectionTest( + function(c, done) { + completes(function() { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + // Don't leave the error waiting to happen for the next test, this + // confuses mocha awfully + c.on('error', function() {}); + c.open(opts); + }, done); + }, + function(send, await, done, socket) { + var timer; + happy_open(send, await) + .then(function() { + timer = setInterval(function() { + socket.write(HB_BUF); + }, heartbeat.UNITS_TO_MS); + }) + .then(await()) + .then(function(hb) { + if (hb === HEARTBEAT) done(); + else done("Next frame after silence not a heartbeat"); + clearInterval(timer); + }); + })); + +test("detect lack of heartbeats", connectionTest( + function(c, done) { + var opts = Object.create(OPEN_OPTS); + opts.heartbeat = 1; + c.on('error', succeed(done)); + c.open(opts); + }, + function(send, await, done, socket) { + happy_open(send, await) + .then(succeed(done), fail(done)); + // conspicuously not sending anything ... + })); + +}); diff --git a/node_modules/amqplib/test/data.js b/node_modules/amqplib/test/data.js new file mode 100644 index 0000000..2fa9bf0 --- /dev/null +++ b/node_modules/amqplib/test/data.js @@ -0,0 +1,255 @@ +// Property-based testing representations of various things in AMQP + +'use strict'; + +var C = require('claire'); +var Buffer = require('safe-buffer').Buffer; +var forAll = C.forAll; +var arb = C.data; +var transform = C.transform; +var repeat = C.repeat; +var label = C.label; +var sequence = C.sequence; +var asGenerator = C.asGenerator; +var sized = C.sized; +var recursive = C.recursive; +var choice = C.choice; +var Undefined = C.Undefined; + +// Stub these out so we can use outside tests +// if (!suite) var suite = function() {} +// if (!test) var test = function() {} + +// These aren't exported in claire/index. so I could have to reproduce +// them I guess. +function choose(a, b) { + return Math.random() * (b - a) + a; +} + +function chooseInt(a, b) { + return Math.floor(choose(a, b)); +} + +function rangeInt(name, a, b) { + return label(name, + asGenerator(function(_) { return chooseInt(a, b); })); +} + +function toFloat32(i) { + var b = Buffer.alloc(4); + b.writeFloatBE(i, 0); + return b.readFloatBE(0); +} + +function floatChooser(maxExp) { + return function() { + var n = Number.NaN; + while (isNaN(n)) { + var mantissa = Math.random() * 2 - 1; + var exponent = chooseInt(0, maxExp); + n = Math.pow(mantissa, exponent); + } + return n; + } +} + +function explicitType(t, underlying) { + return label(t, transform(function(n) { + return {'!': t, value: n}; + }, underlying)); +} + +// FIXME null, byte array, others? + +var Octet = rangeInt('octet', 0, 255); +var ShortStr = label('shortstr', + transform(function(s) { + return s.substr(0, 255); + }, arb.Str)); + +var LongStr = label('longstr', + transform( + function(bytes) { return Buffer.from(bytes); }, + repeat(Octet))); + +var UShort = rangeInt('short-uint', 0, 0xffff); +var ULong = rangeInt('long-uint', 0, 0xffffffff); +var ULongLong = rangeInt('longlong-uint', 0, 0xffffffffffffffff); +var Short = rangeInt('short-int', -0x8000, 0x7fff); +var Long = rangeInt('long-int', -0x80000000, 0x7fffffff); +var LongLong = rangeInt('longlong-int', -0x8000000000000000, + 0x7fffffffffffffff); +var Bit = label('bit', arb.Bool); +var Double = label('double', asGenerator(floatChooser(308))); +var Float = label('float', transform(toFloat32, floatChooser(38))); +var Timestamp = label('timestamp', transform( + function(n) { + return {'!': 'timestamp', value: n}; + }, ULongLong)); +var Decimal = label('decimal', transform( + function(args) { + return {'!': 'decimal', value: {places: args[1], digits: args[0]}}; + }, sequence(arb.UInt, Octet))); + +// Signed 8 bit int +var Byte = rangeInt('byte', -128, 127); + +// Explicitly typed values +var ExByte = explicitType('byte', Byte); +var ExInt8 = explicitType('int8', Byte); +var ExShort = explicitType('short', Short); +var ExInt16 = explicitType('int16', Short); +var ExInt = explicitType('int', Long); +var ExInt32 = explicitType('int32', Long); +var ExLong = explicitType('long', LongLong); +var ExInt64 = explicitType('int64', LongLong); + +var FieldArray = label('field-array', recursive(function() { + return arb.Array( + arb.Null, + LongStr, ShortStr, + Octet, UShort, ULong, ULongLong, + Byte, Short, Long, LongLong, + ExByte, ExInt8, ExShort, ExInt16, + ExInt, ExInt32, ExLong, ExInt64, + Bit, Float, Double, FieldTable, FieldArray) +})); + +var FieldTable = label('table', recursive(function() { + return sized(function() { return 5; }, + arb.Object( + arb.Null, + LongStr, ShortStr, Octet, + UShort, ULong, ULongLong, + Byte, Short, Long, LongLong, + ExByte, ExInt8, ExShort, ExInt16, + ExInt, ExInt32, ExLong, ExInt64, + Bit, Float, Double, FieldArray, FieldTable)) +})); + +// Internal tests of our properties +var domainProps = [ + [Octet, function(n) { return n >= 0 && n < 256; }], + [ShortStr, function(s) { return typeof s === 'string' && s.length < 256; }], + [LongStr, function(s) { return Buffer.isBuffer(s); }], + [UShort, function(n) { return n >= 0 && n <= 0xffff; }], + [ULong, function(n) { return n >= 0 && n <= 0xffffffff; }], + [ULongLong, function(n) { + return n >= 0 && n <= 0xffffffffffffffff; }], + [Short, function(n) { return n >= -0x8000 && n <= 0x8000; }], + [Long, function(n) { return n >= -0x80000000 && n < 0x80000000; }], + [LongLong, function(n) { return n >= -0x8000000000000000 && n < 0x8000000000000000; }], + [Bit, function(b) { return typeof b === 'boolean'; }], + [Double, function(f) { return !isNaN(f) && isFinite(f); }], + [Float, function(f) { return !isNaN(f) && isFinite(f) && (Math.log(Math.abs(f)) * Math.LOG10E) < 309; }], + [Decimal, function(d) { + return d['!'] === 'decimal' && + d.value['places'] <= 255 && + d.value['digits'] <= 0xffffffff; + }], + [Timestamp, function(t) { return t['!'] === 'timestamp'; }], + [FieldTable, function(t) { return typeof t === 'object'; }], + [FieldArray, function(a) { return Array.isArray(a); }] +]; + +suite("Domains", function() { + domainProps.forEach(function(p) { + test(p[0] + ' domain', + forAll(p[0]).satisfy(p[1]).asTest({times: 500})); + }); +}); + +// For methods and properties (as opposed to field table values) it's +// easier just to accept and produce numbers for timestamps. +var ArgTimestamp = label('timestamp', ULongLong); + +// These are the domains used in method arguments +var ARG_TYPES = { + 'octet': Octet, + 'shortstr': ShortStr, + 'longstr': LongStr, + 'short': UShort, + 'long': ULong, + 'longlong': ULongLong, + 'bit': Bit, + 'table': FieldTable, + 'timestamp': ArgTimestamp +}; + +function argtype(thing) { + if (thing.default === undefined) { + return ARG_TYPES[thing.type]; + } + else { + return choice(ARG_TYPES[thing.type], Undefined); + } +} + +function zipObject(vals, names) { + var obj = {}; + vals.forEach(function(v, i) { obj[names[i]] = v; }); + return obj; +} + +function name(arg) { return arg.name; } + +var defs = require('../lib/defs'); + +function method(info) { + var domain = sequence.apply(null, info.args.map(argtype)); + var names = info.args.map(name); + return label(info.name, transform(function(fieldVals) { + return {id: info.id, + fields: zipObject(fieldVals, names)}; + }, domain)); +} + +function properties(info) { + var types = info.args.map(argtype); + types.unshift(ULongLong); // size + var domain = sequence.apply(null, types); + var names = info.args.map(name); + return label(info.name, transform(function(fieldVals) { + return {id: info.id, + size: fieldVals[0], + fields: zipObject(fieldVals.slice(1), names)}; + }, domain)); +} + +var methods = []; +var propertieses = []; + +for (var k in defs) { + if (k.substr(0, 10) === 'methodInfo') { + methods.push(method(defs[k])); + methods[defs[k].name] = method(defs[k]); + } + else if (k.substr(0, 14) === 'propertiesInfo') { + propertieses.push(properties(defs[k])); + propertieses[defs[k].name] = properties(defs[k]); + } +}; + +module.exports = { + Octet: Octet, + ShortStr: ShortStr, + LongStr: LongStr, + UShort: UShort, + ULong: ULong, + ULongLong: ULongLong, + Short: Short, + Long: Long, + LongLong: LongLong, + Bit: Bit, + Double: Double, + Float: Float, + Timestamp: Timestamp, + Decimal: Decimal, + FieldArray: FieldArray, + FieldTable: FieldTable, + + methods: methods, + properties: propertieses +}; + +module.exports.rangeInt = rangeInt; diff --git a/node_modules/amqplib/test/frame.js b/node_modules/amqplib/test/frame.js new file mode 100644 index 0000000..26ac3b1 --- /dev/null +++ b/node_modules/amqplib/test/frame.js @@ -0,0 +1,199 @@ +'use strict'; + +var assert = require('assert'); +var succeed = require('./util').succeed; +var fail = require('./util').fail; +var Buffer = require('safe-buffer').Buffer; +var connection = require('../lib/connection'); +var Frames = connection.Connection; +var HEARTBEAT = require('../lib/frame').HEARTBEAT; +var Stream = require('stream'); +var PassThrough = Stream.PassThrough || + require('readable-stream/passthrough'); + +var defs = require('../lib/defs'); + +// We'll need to supply a stream which we manipulate ourselves + +function inputs() { + // don't coalesce buffers, since that could mess up properties + // (e.g., encoded frame size) + return new PassThrough({objectMode: true}); +} + +var HB = Buffer.from([defs.constants.FRAME_HEARTBEAT, + 0, 0, // channel 0 + 0, 0, 0, 0, // zero size + defs.constants.FRAME_END]); + +suite("Explicit parsing", function() { + + test('Parse heartbeat', function() { + var input = inputs(); + var frames = new Frames(input); + input.write(HB); + assert(frames.recvFrame() === HEARTBEAT); + assert(!frames.recvFrame()); + }); + + test('Parse partitioned', function() { + var input = inputs(); + var frames = new Frames(input); + input.write(HB.slice(0, 3)); + assert(!frames.recvFrame()); + input.write(HB.slice(3)); + assert(frames.recvFrame() === HEARTBEAT); + assert(!frames.recvFrame()); + }); + + function testBogusFrame(name, bytes) { + test(name, function(done) { + var input = inputs(); + var frames = new Frames(input); + frames.frameMax = 5; //for the max frame test + input.write(Buffer.from(bytes)); + frames.step(function(err, frame) { + if (err != null) done(); + else done(new Error('Was a bogus frame!')); + }); + }); + } + + testBogusFrame('Wrong sized frame', + [defs.constants.FRAME_BODY, + 0,0, 0,0,0,0, // zero length + 65, // but a byte! + defs.constants.FRAME_END]); + + testBogusFrame('Unknown method frame', + [defs.constants.FRAME_METHOD, + 0,0, 0,0,0,4, + 0,0,0,0, // garbage ID + defs.constants.FRAME_END]); + + testBogusFrame('> max frame', + [defs.constants.FRAME_BODY, + 0,0, 0,0,0,6, // too big! + 65,66,67,68,69,70, + defs.constants.FRAME_END]); + +}); + +// Now for a bit more fun. + +var amqp = require('./data'); +var claire = require('claire'); +var choice = claire.choice; +var forAll = claire.forAll; +var repeat = claire.repeat; +var label = claire.label; +var sequence = claire.sequence; +var transform = claire.transform; +var sized = claire.sized; + +var assertEqualModuloDefaults = + require('./codec').assertEqualModuloDefaults; + +var Trace = label('frame trace', + repeat(choice.apply(choice, amqp.methods))); + +suite("Parsing", function() { + + function testPartitioning(partition) { + return forAll(Trace).satisfy(function(t) { + var bufs = []; + var input = inputs(); + var frames = new Frames(input); + var i = 0, ex; + frames.accept = function(f) { + // A minor hack to make sure we get the assertion exception; + // otherwise, it's just a test that we reached the line + // incrementing `i` for each frame. + try { + assertEqualModuloDefaults(t[i], f.fields); + } + catch (e) { + ex = e; + } + i++; + }; + + t.forEach(function(f) { + f.channel = 0; + bufs.push(defs.encodeMethod(f.id, 0, f.fields)); + }); + + partition(bufs).forEach(input.write.bind(input)); + frames.acceptLoop(); + if (ex) throw ex; + return i === t.length; + }).asTest({times: 20}) + }; + + test("Parse trace of methods", + testPartitioning(function(bufs) { return bufs; })); + + test("Parse concat'd methods", + testPartitioning(function(bufs) { + return [Buffer.concat(bufs)]; + })); + + test("Parse partitioned methods", + testPartitioning(function(bufs) { + var full = Buffer.concat(bufs); + var onethird = Math.floor(full.length / 3); + var twothirds = 2 * onethird; + return [ + full.slice(0, onethird), + full.slice(onethird, twothirds), + full.slice(twothirds) + ]; + })); +}); + +var FRAME_MAX_MAX = 4096 * 4; +var FRAME_MAX_MIN = 4096; + +var FrameMax = amqp.rangeInt('frame max', + FRAME_MAX_MIN, + FRAME_MAX_MAX); + +var Body = sized(function(_n) { + return Math.floor(Math.random() * FRAME_MAX_MAX); +}, repeat(amqp.Octet)); + +var Content = transform(function(args) { + return { + method: args[0].fields, + header: args[1].fields, + body: Buffer.from(args[2]) + } +}, sequence(amqp.methods['BasicDeliver'], + amqp.properties['BasicProperties'], Body)); + +suite("Content framing", function() { + test("Adhere to frame max", + forAll(Content, FrameMax).satisfy(function(content, max) { + var input = inputs(); + var frames = new Frames(input); + frames.frameMax = max; + frames.sendMessage( + 0, + defs.BasicDeliver, content.method, + defs.BasicProperties, content.header, + content.body); + var f, i = 0, largest = 0; + while (f = input.read()) { + i++; + if (f.length > largest) largest = f.length; + if (f.length > max) { + return false; + } + } + // The ratio of frames to 'contents' should always be >= 2 + // (one properties frame and at least one content frame); > 2 + // indicates fragmentation. The largest is always, of course <= frame max + //console.log('Frames: %d; frames per message: %d; largest frame %d', i, i / t.length, largest); + return true; + }).asTest()); +}); diff --git a/node_modules/amqplib/test/mux.js b/node_modules/amqplib/test/mux.js new file mode 100644 index 0000000..fef6e13 --- /dev/null +++ b/node_modules/amqplib/test/mux.js @@ -0,0 +1,166 @@ +'use strict'; + +var assert = require('assert'); +var Mux = require('../lib/mux').Mux; +var PassThrough = require('stream').PassThrough || + require('readable-stream/passthrough'); + +var latch = require('./util').latch; +var schedule = require('./util').schedule; + +function stream() { + return new PassThrough({objectMode: true}); +} + +function readAllObjects(s, cb) { + var objs = []; + + function read() { + var v = s.read(); + while (v !== null) { + objs.push(v); + v = s.read(); + } + } + + s.on('end', function() { cb(objs); }); + s.on('readable', read); + + read(); +} + +test("single input", function(done) { + var input = stream(); + var output = stream(); + input.on('end', function() { output.end() }); + + var mux = new Mux(output); + mux.pipeFrom(input); + + var data = [1,2,3,4,5,6,7,8,9]; + // not 0, it's treated specially by PassThrough for some reason. By + // 'specially' I mean it breaks the stream. See e.g., + // https://github.com/isaacs/readable-stream/pull/55 + data.forEach(input.write.bind(input)); + + readAllObjects(output, function(vals) { + assert.deepEqual(data, vals); + done(); + }); + + input.end(); +}); + +test("two sequential inputs", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var data = [1,2,3,4,5,6,7,8,9]; + data.forEach(function(v) { input1.write(v); }); + + input1.on('end', function() { + data.forEach(function (v) { input2.write(v); }); + input2.end(); + }); + input2.on('end', function() { output.end(); }); + + input1.end(); + readAllObjects(output, function(vs) { + assert.equal(2 * data.length, vs.length); + done(); + }); +}); + +test("two interleaved inputs", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var endLatch = latch(2, function() { output.end(); }); + input1.on('end', endLatch); + input2.on('end', endLatch); + + var data = [1,2,3,4,5,6,7,8,9]; + data.forEach(function(v) { input1.write(v); }); + input1.end(); + + data.forEach(function(v) { input2.write(v); }); + input2.end(); + + readAllObjects(output, function(vs) { + assert.equal(2 * data.length, vs.length); + done(); + }); +}); + +test("unpipe", function(done) { + var input = stream(); + var output = stream(); + var mux = new Mux(output); + + var pipedData = [1,2,3,4,5]; + var unpipedData = [6,7,8,9]; + + mux.pipeFrom(input); + + schedule(function() { + pipedData.forEach(input.write.bind(input)); + mux.unpipeFrom(input); + + schedule(function() { + unpipedData.forEach(input.write.bind(input)); + input.end(); + schedule(function() { + // exhaust so that 'end' fires + var v; while (v = input.read()); + }); + }); + }); + + input.on('end', function() { + output.end(); + }); + + readAllObjects(output, function(vals) { + try { + assert.deepEqual(pipedData, vals); + done(); + } + catch (e) { done(e); } + }); +}); + +test("roundrobin", function(done) { + var input1 = stream(); + var input2 = stream(); + var output = stream(); + var mux = new Mux(output); + + mux.pipeFrom(input1); + mux.pipeFrom(input2); + + var endLatch = latch(2, function() { output.end(); }); + input1.on('end', endLatch); + input2.on('end', endLatch); + + var ones = [1,1,1,1,1]; + ones.forEach(function(v) { input1.write(v); }); + input1.end(); + + var twos = [2,2,2,2,2]; + twos.forEach(function(v) { input2.write(v); }); + input2.end(); + + readAllObjects(output, function(vs) { + assert.deepEqual([1,2,1,2,1,2,1,2,1,2], vs); + done(); + }); + +}); diff --git a/node_modules/amqplib/test/util.js b/node_modules/amqplib/test/util.js new file mode 100644 index 0000000..0617ca9 --- /dev/null +++ b/node_modules/amqplib/test/util.js @@ -0,0 +1,220 @@ +'use strict'; + +var Promise = require('bluebird'); +var crypto = require('crypto'); +var Connection = require('../lib/connection').Connection; +var PassThrough = + require('stream').PassThrough || + require('readable-stream/passthrough'); +var defs = require('../lib/defs'); +var assert = require('assert'); + +var schedule = (typeof setImmediate === 'function') ? + setImmediate : process.nextTick; + +function randomString() { + var hash = crypto.createHash('sha1'); + hash.update(crypto.randomBytes(64)); + return hash.digest('base64'); +} + + +// Set up a socket pair {client, server}, such that writes to the +// client are readable from the server, and writes to the server are +// readable at the client. +// +// +---+ +---+ +// | C | | S | +// --write->| l |----->| e |--read--> +// | i | | r | +// <--read--| e |<-----| v |<-write-- +// | n | | e | +// | t | | r | +// +---+ +---+ +// +// I also need to make sure that end called on either socket affects +// the other. + +function socketPair() { + var server = new PassThrough(); + var client = new PassThrough(); + server.write = client.push.bind(client); + client.write = server.push.bind(server); + function end(chunk, encoding) { + if (chunk) this.push(chunk, encoding); + this.push(null); + } + server.end = end.bind(client); + client.end = end.bind(server); + + return {client: client, server: server}; +} + +function runServer(socket, run) { + var frames = new Connection(socket); + // We will be closing the socket without doing a closing handshake, + // so cheat + frames.expectSocketClose = true; + // We also need to create some channel buffers, again a cheat + frames.freshChannel(null); + frames.freshChannel(null); + frames.freshChannel(null); + + function send(id, fields, channel, content) { + channel = channel || 0; + if (content) { + schedule(function() { + frames.sendMessage(channel, id, fields, + defs.BasicProperties, fields, + content); + }); + } + else { + schedule(function() { + frames.sendMethod(channel, id, fields); + }); + } + } + + function await(method) { + return function() { + return new Promise(function(resolve, reject) { + if (method) { + frames.step(function(e, f) { + if (e !== null) return reject(e); + if (f.id === method) + resolve(f); + else + reject(new Error("Expected method: " + method + + ", got " + f.id)); + }); + } + else { + frames.step(function(e, f) { + if (e !== null) return reject(e); + else resolve(f); + }); + } + }); + }; + } + run(send, await); + return frames; +} + +// Produce a callback that will complete the test successfully +function succeed(done) { + return function() { done(); } +} + +// Produce a callback that will complete the test successfully +// only if the value is an object, it has the specified +// attribute, and its value is equals to the expected value +function succeedIfAttributeEquals(attribute, value, done) { + return function(object) { + if (object && !(object instanceof Error) && value === object[attribute]) { + return done(); + } + + done(new Error(attribute + " is not equal to " + value)); + }; +} + +// Produce a callback that will fail the test, given either an error +// (to be used as a failure continuation) or any other value (to be +// used as a success continuation when failure is expected) +function fail(done) { + return function(err) { + if (err instanceof Error) done(err); + else done(new Error("Expected to fail, instead got " + err.toString())); + } +} + +// Create a function that will call done once it's been called itself +// `count` times. If it's called with an error value, it will +// immediately call done with that error value. +function latch(count, done) { + var awaiting = count; + var alive = true; + return function(err) { + if (err instanceof Error && alive) { + alive = false; + done(err); + } + else { + awaiting--; + if (awaiting === 0 && alive) { + alive = false; + done(); + } + } + }; +} + +// Call a thunk with a continuation that will be called with an error +// if the thunk throws one, or nothing if it runs to completion. +function completes(thunk, done) { + try { + thunk(); + done(); + } + catch (e) { done(e); } +} + +// Construct a Node.JS-style callback from a success continuation and +// an error continuation +function kCallback(k, ek) { + return function(err, val) { + if (err === null) k && k(val); + else ek && ek(err); + }; +} + +// A noddy way to make tests depend on the node version. +function versionGreaterThan(actual, spec) { + + function int(e) { return parseInt(e); } + + var version = actual.split('.').map(int); + var desired = spec.split('.').map(int); + for (var i=0; i < desired.length; i++) { + var a = version[i], b = desired[i]; + if (a != b) return a > b; + } + return false; +} + +suite('versionGreaterThan', function() { + +test('full spec', function() { + assert(versionGreaterThan('0.8.26', '0.6.12')); + assert(versionGreaterThan('0.8.26', '0.8.21')); +}); + +test('partial spec', function() { + assert(versionGreaterThan('0.9.12', '0.8')); +}); + +test('not greater', function() { + assert(!versionGreaterThan('0.8.12', '0.8.26')); + assert(!versionGreaterThan('0.6.2', '0.6.12')); + assert(!versionGreaterThan('0.8.29', '0.8')); +}); + +test + +}); + +module.exports = { + socketPair: socketPair, + runServer: runServer, + succeed: succeed, + succeedIfAttributeEquals: succeedIfAttributeEquals, + fail: fail, + latch: latch, + completes: completes, + kCallback: kCallback, + schedule: schedule, + randomString: randomString, + versionGreaterThan: versionGreaterThan +}; diff --git a/node_modules/bitsyntax/.npmignore b/node_modules/bitsyntax/.npmignore new file mode 100644 index 0000000..40338d5 --- /dev/null +++ b/node_modules/bitsyntax/.npmignore @@ -0,0 +1,3 @@ +sketches +*~ +scratch diff --git a/node_modules/bitsyntax/.travis.yml b/node_modules/bitsyntax/.travis.yml new file mode 100644 index 0000000..2b0d3cb --- /dev/null +++ b/node_modules/bitsyntax/.travis.yml @@ -0,0 +1,7 @@ +language: node_js + +node_js: + - "0.10" + - "0.8" + - "0.6" + - "0.11" diff --git a/node_modules/bitsyntax/Makefile b/node_modules/bitsyntax/Makefile new file mode 100644 index 0000000..ee27ab8 --- /dev/null +++ b/node_modules/bitsyntax/Makefile @@ -0,0 +1,15 @@ +.PHONY: test all + +GRAMMAR=lib/grammar.pegjs +PEGJS=./node_modules/.bin/pegjs + +all: lib/parser.js + +lib/parser.js: $(PEGJS) + $(PEGJS) $(GRAMMAR) $@ + +$(PEGJS): + npm install + +test: lib/parser.js + ./node_modules/.bin/mocha --check-leaks -R list -u tdd test/*.js diff --git a/node_modules/bitsyntax/README.md b/node_modules/bitsyntax/README.md new file mode 100644 index 0000000..02eed9b --- /dev/null +++ b/node_modules/bitsyntax/README.md @@ -0,0 +1,306 @@ +# Byte-wise matching for Node.JS + +[![Build Status](https://travis-ci.org/squaremo/bitsyntax-js.png?branch=master)](https://travis-ci.org/squaremo/bitsyntax-js) + +Gives a compact syntax for parsing and constructing byte buffers, +derived from [Erlang's bit +syntax](http://www.erlang.org/doc/programming_examples/bit_syntax.html#id64858). + +```js +var bitsyntax = require('bitsyntax'); +var pattern = bitsyntax.matcher('len:8/integer, str:len/binary'); +var bound = pattern(new Buffer([4, 0x41, 0x42, 0x43, 0x44])); +bound.str +// => +``` + +A typical use of this is parsing byte streams from sockets. For +example, size-prefixed frames: + +```js +var framePattern = bitsyntax.matcher('len:32/integer, frame:len/binary, rest/binary'); +socket.on('data', function process(data) { + var m; + if (m = framePattern(data)) { + emit('frame', m.frame); + process(m.rest); + } + else { + stashForNextData(data); + } +}); +``` + +Patterns can also be used to construct byte buffers from supplied +values: + +```js +var spdyDataFrame = require('bitsyntax') + .builder('streamId:32, flags:8, length:24, data/binary'); + +spdyDataFrame({streamId:5, flags:0, length:bin.length, data:bin}); +``` + +One or more segments of a pattern may also be supplied in multiple +arguments, if that is more convenient; this makes it easier to split a +long pattern over lines: + +```js +var p = bitsyntax.matcher('size:8, payload:size/binary', + 'rest/binary'); +``` + +## API + +### `matcher` + +Compiles a pattern as a string (or strings), to a function that will +return either a map of bindings, or `false`, given a buffer and +optionally an environment. The environment contains values for bound +variables in the pattern (if there are any). + +```js +var p = bitsyntax.matcher('header:headerSize/binary, rest/binary'); +var b = p(new Buffer([1, 2, 3, 4, 5]), {headerSize: 3}); +b.header +// => +``` + +A matcher will return `false` if the supplied buffer does not match +the pattern; for example, if it has too few bytes, or a literal is not +present. + +```js +var p = bitsyntax.matcher('"foo=", str/binary'); +p(new Buffer("bar=humbug")); +// => false +``` + +### `parse` and `match` + +When composed, equivalent to `matcher`; may be useful if you want to +examine the internal structure of patterns. + +`parse` takes strings as for `matcher`, and returns the internal +representation of the pattern. `match` takes this representation, a +buffer, and optionally an environment, and returns the bindings or +`false` (as with `matcher`). + +```js +var p = bitsyntax.parse('header:headerSize/binary', + 'rest/binary'); +var b = bitsyntax.match(p, new Buffer([1, 2, 3, 4, 5]), + {headerSize: 3}); +b.header +// => +``` + +### `builder` + +Takes a pattern and returns a function that will construct a byte +buffer, given values for the variables mentioned in the pattern. + +```js +var cons = bitsyntax.builder('size:8, bin/binary'); +cons({size:6, bin:new Buffer('foobar')}); +// => +``` + +Patterns supplied to builders are slightly different to patterns +supplied for matching, as noted below. + +### `build` + +Takes a parsed pattern and a map of variable values, and returns a +buffer. As with `match`, may be useful to debug patterns. + +```js +var pattern = bitsyntax.parse('size:8, bin:size/binary'); +bitsyntax.build(pattern, {size:6, bin: new Buffer('foobar')}); +// => +``` + +### `write` + +Writes variable values into a buffer, at an offset, according to the +parsed pattern given. Returns the finishing offset, i.e., the supplied +offset plus the number of bytes written. + +```js +var pattern = bitsyntax.parse('size:8, bin/binary'); +var buf = new Buffer(7); +bitsyntax.write(buf, 0, pattern, + {size:6, bin: new Buffer('foobar')}); +// => 7 +buf +// => +``` + +## Patterns + +Patterns are sequences of segments, each matching a value. Segments +have the general form + + value:size/type_specifier_list + +The size and type specifier list may be omitted, giving three extra +variations: + + value + value:size + value/type_specifier_list + +The type specifier list is a list of keywords separated by +hyphens. Type specifiers are described below. + +Patterns are generally supplied as strings, with a comma-separated +series of segments. + +### Variable or value + +The first part of a segment gives a variable name or a literal +value. If a variable name is given, the value matched by the segment +will be bound to that variable name for the rest of the pattern. If a +literal value is given, the matched value must equal that value. If a +variable's value is given in the environment, the matched value must +equal the provided value. + +When used in a builder, the literal value will be copied into the +buffer according to the type it is given. A variable name indicates a +slot into which a value supplied to the builder will be copied. + +The special variable name `_` discards the value matched; i.e., it +simply skips over the appropriate number of bits in the input. '_' is +not allowed in builder patterns. + +### Size and unit + +The size of a segment is given following the value or variable, +separated with a colon: + + foo:32 + +The unit is given in the list of specifiers as `'unit' and +an integer from 0..256, separated by a colon: + + foo:4/integer-unit:8 + +The size is the number of units in the value; the unit is given as a +number of bits. Unit can be of use, for example, when you want to +match integers of a number of bytes rather than a number of bits. + +For integers and floats, the default unit is 1 bit; to keep things +aligned on byte boundaries, `unit * size` must currently be a multiple +of 8. For binaries the default unit is 8, and the unit must be a +multiple of 8. + +If the size is omitted and the type is integer, the size defaults to +8. If the size is omitted and the type is binary, the segment will +match all remaining bytes in the input; such a segment may only be +used at the end of a pattern, when matching. + +The size may also be given as an integer variable matched earlier in +the pattern, as in the example given at the top. When constructing, a +size may be a variable referring to the supplied environment. + +In builders, numbers will be rounded, masked or padded to fit the size +and units given; for example, `'256:8'` gives the binary `Buffer<00>` +because the lowest eight bits are 0; `'255:16` gives the binary +`Buffer<00 ff>`. + +### Type name specifier + +One of `integer`, `binary`, `string`, `float`. If not given, the +default is `integer`. + +An integer is a big- or little-endian, signed or unsigned +integer. Integers up to 32 bits are supported. Signed integers are +two's complement format. In JavaScript, only integers between -(2^53) +and 2^53 can be represented, and bitwise operators are only defined on +32-bit signed integers. + +A binary is simply a byte buffer; usually this will result in a slice +of the input buffer being returned, so beware mutation. + +A string is a UTF8 string consisting of the given number of bytes. + +A float is a 32- or 64-bit IEEE754 floating-point value (this is the +standard JavaScript uses, as do Java and Erlang). + +### Endianness specifier + +Integers may be big- or little-endian; this refers to which 'end' of +the bytes making up the integer are most significant. In network +protocols integers are usually big-endian, meaning the first +(left-most) byte is the most significant, but this is not always the +case. + +A specifier of `big` means the integer will be parsed (or written into +the result) as big-endian, and `little` means the integer will be +parsed or written as little-endian. The default is big-endian. + +### Signedness specifier + +Integer segments may include a specifier of `signed` or `unsigned`. A +signed integer is parsed as two's complement format. The default is +unsigned. + +Signedness is ignored in builders. + +### Literal strings + +A quoted string appearing in a pattern is a shorthand for the bytes in +its UTF8 encoding. For example, + + "foobar", _/binary + +matches any buffer that starts with the bytes `0x66, 0x6f, 0x6f, 0x62, +0x61, 0x72`. + +When used in a builder, a quoted string is copied into the result as +the bytes of its UTF8 encoding. + +## Examples + +In the following the matched bytes are given in array notation for +convenience. Bear in mind that `match()` actually takes a buffer for +the bytes to match against. The phrase "returns X as Y" or "binds X as +Y" means the return value is an object with value X mapped to the key +Y. + + 54 + +Matches the single byte `54`. + + 54:32 + +Matches the bytes [0,0,0,54]. + + 54:32/little + +Matches the bytes [54,0,0,0]. + + 54:4/unit:8 + +Matches the bytes [0,0,0,54]. + + int:32/signed + +Matches a binary of four bytes, and returns a signed 32-bit integer as +`int`. + + len:16, str:len/binary + +Matches a binary of `2 + len` bytes, and returns an unsigned 16-bit +integer as `len` and a buffer of length `len` as `str`. + + len:16, _:len/binary, rest/binary + +Matches a binary of at least `2 + len` bytes, binds an unsigned 16-bit +integer as `len`, ignores the next `len` bytes, and binds the +remaining (possibly zero-length) binary as `rest`. + + s:8, key:s/binary, value/binary + +When given the environment `{s:6, key: "foobar"}`, will match a binary +starting with [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, ...]. diff --git a/node_modules/bitsyntax/index.js b/node_modules/bitsyntax/index.js new file mode 100644 index 0000000..3a894a9 --- /dev/null +++ b/node_modules/bitsyntax/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports.parse = require('./lib/parse').parse; +module.exports.match = require('./lib/interp').match; +module.exports.build = require('./lib/constructor').build; +module.exports.write = require('./lib/constructor').write; + +module.exports.matcher = module.exports.compile = + require('./lib/compile').compile; +module.exports.builder = require('./lib/compile').compile_builder; diff --git a/node_modules/bitsyntax/package.json b/node_modules/bitsyntax/package.json new file mode 100644 index 0000000..147b299 --- /dev/null +++ b/node_modules/bitsyntax/package.json @@ -0,0 +1,57 @@ +{ + "_from": "bitsyntax@~0.0.4", + "_id": "bitsyntax@0.0.4", + "_inBundle": false, + "_integrity": "sha1-6xDMb4K4xJDj6FaY8H6D1G4MuoI=", + "_location": "/bitsyntax", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bitsyntax@~0.0.4", + "name": "bitsyntax", + "escapedName": "bitsyntax", + "rawSpec": "~0.0.4", + "saveSpec": null, + "fetchSpec": "~0.0.4" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.0.4.tgz", + "_shasum": "eb10cc6f82b8c490e3e85698f07e83d46e0cba82", + "_spec": "bitsyntax@~0.0.4", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", + "author": { + "name": "Michael Bridgen", + "email": "=0.6" + }, + "homepage": "https://github.com/squaremo/bitsyntax-js#readme", + "main": "./index", + "name": "bitsyntax", + "repository": { + "type": "git", + "url": "git://github.com/squaremo/bitsyntax-js.git" + }, + "scripts": { + "prepublish": "make all", + "test": "make test" + }, + "version": "0.0.4" +} diff --git a/node_modules/bitsyntax/test/consing.js b/node_modules/bitsyntax/test/consing.js new file mode 100644 index 0000000..4f1cd67 --- /dev/null +++ b/node_modules/bitsyntax/test/consing.js @@ -0,0 +1,45 @@ +var assert = require('assert'); +var parse = require('../').parse; +var build = require('../').build; +var builder = require('../').builder; +var write = require('../').write; + +TEST_CASES = [ + ['n:8', {n:255}, [255]], + ['n:16', {n: 0xf0f0}, [240, 240]], + ['n:32', {n: 0x12345678}, [18,52,86,120]], + ['n:64', {n: 0xffffffffffffffff}, [255,255,255,255,255,255,255,255]], + + ['n:8, s/binary', {n: 255, s: new Buffer("foobar")}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], + ['n:8, "foobar", m:8', {n: 255, m:0}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0]], + ['n:8, s:n/binary', {n:6, s: new Buffer('foobar')}, [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], + ['n:8, s:n/binary', {n:4, s: new Buffer('foobar')}, [4, 0x66, 0x6f, 0x6f, 0x62]], + ['n:size', {n:4, size:8}, [4]], + ['206:n/unit:8', {n:1}, [206]] +]; + +function bufferToArray(buf) { + return Array.prototype.slice.call(buf); +} + +suite("Construction", function() { + TEST_CASES.forEach(function(c) { + var p = parse(c[0]); + test(c[0], function() { + assert.deepEqual(c[2], bufferToArray(build(p, c[1]))); + }); + test(c[0], function() { + var buf = new Buffer(1024); + var end = write(buf, 7, p, c[1]); + buf = buf.slice(7, end); + assert.deepEqual(c[2], bufferToArray(buf)); + }); + test(c[0], function() { + var cons = builder(c[0]); + var buf = cons(c[1]); + assert.deepEqual(c[2], bufferToArray(buf)); + }); + + }); + +}); diff --git a/node_modules/bitsyntax/test/matching.js b/node_modules/bitsyntax/test/matching.js new file mode 100644 index 0000000..1d5abe0 --- /dev/null +++ b/node_modules/bitsyntax/test/matching.js @@ -0,0 +1,187 @@ +var match = require('../').match; +var parse = require('../').parse; +var compile = require('../').matcher; +var assert = require('assert'); + + +var INT_TESTS = [ + ['n:8', + [[[255], 255]]], + ['n:8/signed', + [[[255], -1]]], + ['n:1/unit:8', + [[[129], 129]]], + ['n:1/unit:8-signed', + [[[129], -127]]], + + ['n:16', + [[[1, 255], 511]]], + ['n:16/signed', + [[[255, 65], -191]]], + ['n:16/little', + [[[255, 1], 511]]], + ['n:16/signed-little', + [[[65, 255], -191]]], + + ['n:32', + [[[45, 23, 97, 102], 756506982]]], + ['n:32/signed', + [[[245, 23, 97, 102], -183017114]]], + ['n:32/little', + [[[245, 23, 97, 102], 1717639157]]], + ['n:32/signed-little', + [[[245, 23, 97, 129], -2124343307]]], + + ['n:4/signed-little-unit:8', + [[[245, 23, 97, 129], -2124343307]]], + + ['n:64', + [[[1,2,3,4,5,6,7,8], 72623859790382856]]], + ['n:64/signed', + [[[255,2,3,4,5,6,7,8], -71491328285473016]]], + ['n:64/little', + [[[1,2,3,4,5,6,7,8], 578437695752307201]]], + ['n:64/little-signed', + [[[1,2,3,4,5,6,7,255], -70080650589044223]]], + ['n:8/signed-unit:8-little', + [[[1,2,3,4,5,6,7,255], -70080650589044223]]], +]; + +suite("Integer", + function() { + + INT_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + assert.deepEqual({n: tc[1]}, match(pattern, new Buffer(tc[0]))); + }); + test(p[0], function() { + assert.deepEqual({n: tc[1]}, cpattern(new Buffer(tc[0]))); + }); + }); + }); + }); + + +// test cases largely constructed in Erlang using e.g., +// Pi = math:pi(), <>. +FLOAT_TESTS = [ + ['n:32/float', + [[[64,73,15,219], Math.PI], + [[0, 0, 0, 0], 0.0 ]]], + + ['n:64/float', + [[[64,9,33,251,84,68,45,24], Math.PI], + [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], + + ['n:32/float-little', + [[[219, 15, 73, 64], Math.PI], + [[0, 0, 0, 0], 0.0]]], + + ['n:64/float-little', + [[[24, 45, 68, 84, 251, 33, 9, 64], Math.PI], + [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], + + ['n:4/float-unit:8', + [[[64,73,15,219], Math.PI], + [[0, 0, 0, 0], 0.0]]] +]; + +suite("Float", + function() { + var precision = 0.00001; + FLOAT_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + var m = match(pattern, new Buffer(tc[0])); + assert.ok(m.n !== undefined); + assert.ok(Math.abs(tc[1] - m.n) < precision); + }); + test(p[0], function() { + var m = cpattern(new Buffer(tc[0])); + assert.ok(m.n !== undefined); + assert.ok(Math.abs(tc[1] - m.n) < precision); + }); + }); + }); + }); + +BINARY_TESTS = [ + ['n:0/unit:8-binary', []], + ['n:1/unit:8-binary', [93]], + ['n:5/unit:8-binary', [1, 2, 3, 4, 5]], + ['n:32/unit:1-binary', [255, 254, 253, 252]] +]; + +suite("Binary", + function() { + BINARY_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + var prest = p[0] + ', _/binary'; + var patternrest = parse(prest); + var cpatternrest = compile(prest); + test(p[0], function() { + assert.deepEqual({n: new Buffer(p[1])}, + match(pattern, new Buffer(p[1]))); + assert.deepEqual({n: new Buffer(p[1])}, + cpattern(new Buffer(p[1]))); + }); + test(prest, function() { + var plusgarbage = p[1].concat([5, 98, 23, 244]); + assert.deepEqual({n: new Buffer(p[1])}, + match(patternrest, new Buffer(plusgarbage))); + assert.deepEqual({n: new Buffer(p[1])}, + cpatternrest(new Buffer(plusgarbage))); + }); + }); + }); + +var VAR_TESTS = [ + ['size, n:size', + [[[8, 5], 5], + [[32, 0, 0, 0, 167], 167]]], + + ['size, n:size/binary', + [[[2, 5, 6], new Buffer([5, 6])]]], + + ['a, b:a, n:b', + [[[8, 32, 0, 0, 2, 100], 612]]] +]; + +suite("Environment", + function() { + VAR_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + var cpattern = compile(p[0]); + p[1].forEach(function(tc) { + test(p[0], function() { + assert.deepEqual(tc[1], match(pattern, new Buffer(tc[0])).n); + }); + test(p[0], function() { + assert.deepEqual(tc[1], cpattern(new Buffer(tc[0])).n); + }); + }); + }); + }); + +STRING_TESTS = [ + ['"foobar", n:8', "foobarA", 'A'.charCodeAt(0)], + ['n:8, "foobar", _/binary', "CfoobarGARBAGE", 'C'.charCodeAt(0)], + ['"foo, :-bar\\"", n:8, "another"', 'foo, :-bar"Zanother', 'Z'.charCodeAt(0)] +]; + +suite("String", + function() { + STRING_TESTS.forEach(function(p) { + var pattern = parse(p[0]); + test(p[0], function() { + var res = match(pattern, new Buffer(p[1])); + assert.equal(res.n, p[2]); + }); + }); + }); diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE new file mode 100644 index 0000000..ae732d5 --- /dev/null +++ b/node_modules/bluebird/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 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. diff --git a/node_modules/bluebird/README.md b/node_modules/bluebird/README.md new file mode 100644 index 0000000..ba82f73 --- /dev/null +++ b/node_modules/bluebird/README.md @@ -0,0 +1,52 @@ + + Promises/A+ logo + + +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) +[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) + +**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) + +# Introduction + +Bluebird is a fully featured promise library with focus on innovative features and performance + +See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. + +For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). + +# Questions and issues + +The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. + + + +## Thanks + +Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. + +# License + +The MIT License (MIT) + +Copyright (c) 2013-2017 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. + diff --git a/node_modules/bluebird/changelog.md b/node_modules/bluebird/changelog.md new file mode 100644 index 0000000..73b2eb6 --- /dev/null +++ b/node_modules/bluebird/changelog.md @@ -0,0 +1 @@ +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/node_modules/bluebird/js/browser/bluebird.core.js b/node_modules/bluebird/js/browser/bluebird.core.js new file mode 100644 index 0000000..85b7791 --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.core.js @@ -0,0 +1,3781 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.1 + * Features enabled: core + * Features disabled: 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":17,"./schedule":18,"./util":21}],2:[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); +}; +}; + +},{}],3:[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":15}],4:[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":21}],5:[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":10,"./util":21}],6:[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; +}; + +},{}],7:[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(); + var self = this; + setTimeout(function() { + self._notifyUnhandledRejection(); + }, 1); +}; + +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; + } + } + return Promise; +}; + +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 && error.name != "SyntaxError") { + 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: error.name == "SyntaxError" ? 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":9,"./util":21}],8:[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); + } +}; +}; + +},{}],9:[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":10,"./util":21}],10:[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; + } + }; +} + +},{}],11:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); + +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 === NEXT_FILTER) { + return ret; + } else 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); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + 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 Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; + +},{"./catch_filter":5,"./util":21}],12:[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 (!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, 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 (!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); + 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":21}],13:[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":21}],14:[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":9,"./es5":10,"./util":21}],15:[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, NEXT_FILTER); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + 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("Catch statement predicate: " + + "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" && + 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) { + if (executor === INTERNAL) return; + 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.5.1"; + + 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; + +}; + +},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[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 {}; + case -6: return new Map(); + } +} + +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":21}],17:[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.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; + +},{}],18:[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":21}],19:[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; +}; + +},{}],20:[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":21}],21:[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 instanceof Error || + (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]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +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, + hasEnvVariables: hasEnvVariables, + 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":10}]},{},[3])(3) +}); ;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/node_modules/bluebird/js/browser/bluebird.core.min.js b/node_modules/bluebird/js/browser/bluebird.core.min.js new file mode 100644 index 0000000..6aca6aa --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.core.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.1 + * Features enabled: core + * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[a]={exports:{}};t[a][0].call(u.exports,function(e){var n=t[a][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var o="function"==typeof _dereq_&&_dereq_,a=0;a0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=s},{"./queue":17,"./schedule":18,"./util":21}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},s=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var f={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,a,void 0,u,f),l._then(s,c,void 0,u,f),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],3:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),a=o.tryCatch,s=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=a,t.prototype._peekContext=s,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+I.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?I.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function f(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function h(){this._trace=new x(this._peekContext())}function _(t,e){if(H(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=E(t);I.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),I.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=C(s),l=c.length-1;l>=0;--l){var u=c[l];if(!V.test(u)){var p=u.match(Q);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var f=c[0],l=0;l0&&(a="\n"+s[l-1]);break}}var h="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=E(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n=0;--s)if(r[s]===o){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[i]!==c)break;e.pop(),i--}e=r}}function C(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function E(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:C(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(I.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof N?N(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){B.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||k(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():I.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+T(e)+">, no stack trace)"}function T(t){var e=41;return t.lengtha||0>s||!n||!r||n!==r||a>=s||(nt=function(t){if(D.test(t))return!0;var e=R(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function x(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,x),e>32&&this.uncycle()}var O,A,N,L=e._getDomain,B=e._async,U=t("./errors").Warning,I=t("./util"),H=I.canAttachTrace,D=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,V=/\((?:timers\.js):\d+:\d+\)/,Q=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,G=null,M=!1,W=!(0==I.env("BLUEBIRD_DEBUG")||!I.env("BLUEBIRD_DEBUG")&&"development"!==I.env("NODE_ENV")),$=!(0==I.env("BLUEBIRD_WARNINGS")||!W&&!I.env("BLUEBIRD_WARNINGS")),z=!(0==I.env("BLUEBIRD_LONG_STACK_TRACES")||!W&&!I.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=I.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!I.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=L();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=L();O="function"==typeof t?null===e?t:I.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),B.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),B.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&P()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!I.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!I.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!I.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return I.isNode?function(){return process.emit.apply(process,arguments)}:I.global?function(t){var e="on"+t.toLowerCase(),n=I.global[e];return n?(n.apply(I.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){B.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){B.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,X=ot.warnings,I.isObject(n)&&"wForgottenReturn"in n&&(X=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(B.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=s,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=a,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;I.inherits(x,Error),n.CapturedTrace=x,x.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var a=e[r].stack,s=n[a];if(void 0!==s&&s!==r){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>s?(c._parent=e[s+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},x.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=E(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(C(i.stack.split("\n"))),i=i._parent;b(r),m(r),I.notEnumerableProp(t,"stack",g(n,r)),I.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,G=e;var n=Error.captureStackTrace;return nt=function(t){return D.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,G=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(G=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,G=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(N=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?N=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:I.isNode||"string"!=typeof(new Error).stack||(N=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return z&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return f},checkForgottenReturns:d,setBounds:S,warn:y,deprecated:v,CapturedTrace:x,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":9,"./util":21}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],9:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,a,s=t("./es5"),c=s.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,a=RangeError}catch(v){o=r("TypeError","type error"),a=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),g=0;g1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return l.call(this,this.promise._target()._settledValue())}function c(t){return a(this,t)?void 0:(f.e=t,f)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var h=n(u,i);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),f.e=_,f}h.isPending()&&h._attachCancellationCallback(new o(this))}return h._then(s,c,void 0,this,void 0)}}}return i.isRejected()?(a(this),f.e=t,f):(a(this),t)}var u=t("./util"),p=e.CancellationError,f=u.errorObj,h=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){a(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var a=arguments[r];if(!u.isObject(a))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(a)));i[o++]=a}i.length=o;var s=arguments[r];return this._passThrough(h(i,s,this),1,void 0,l)},i}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,a){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var a=t("./util"),s=a.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+a.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=s(t).apply(this,arguments),a=r._popContext();return o.checkForgottenReturns(i,a,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+a.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=a.isArray(l)?s(t).apply(u,l):s(t).call(u,l)}else c=s(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===a.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":21}],14:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return p("Catch statement predicate: expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,C,void 0); +},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new k(this).promise()},i.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=x(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new k(t).promise()},i.cast=function(t){var e=E(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var a=void 0!==o,s=a?o:new i(b),l=this._target(),u=l._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var p=c();if(0!==(50397184&u)){var f,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,f=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new m("late cancellation observer"),l._attachExtraTrace(_),f=e),v.invoke(d,l,{handler:null===p?f:"function"==typeof f&&h.domainBind(p,f),promise:s,receiver:r,value:_})}else l._addCallbacks(t,e,s,r,p);return s},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=f),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=f),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:h.domainBind(i,e));else{var a=4*o-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this[a+1]=null===i?e:h.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=E(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var a=this._length();a>0&&r._migrateCallback0(this);for(var s=1;a>s;++s)r._migrateCallbackAt(this,s);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new m("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===C?n&&"number"==typeof n.length?o=x(t).apply(this._boundValue(),n):(o=S,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=x(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===S?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,a,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var a=t instanceof i,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,x(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof k?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,h.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,E,p,F),t("./bind")(i,b,E,F),t("./cancel")(i,k,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,E,b,v,c),i.Promise=i,i.version="3.5.1",h.toFastProperties(i),h.toFastProperties(i.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new i(b)),F.setBounds(d.firstLineError,h.lastLineError),i}},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function a(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function s(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(s,o),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var s=o._bitField;if(this._values=o,0===(50397184&s))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(o)},s.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,a=null,s=0;n>s;++s){var c=r(t[s],i);c instanceof e?(c=c._target(),a=c._bitField):a=null,o?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):o=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):o=this._promiseFulfilled(c,s)}o||i._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;no;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityn;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function f(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function h(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return N.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{u(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function C(t){return{}.toString.call(t)}function w(t,e,n){for(var r=F.names(t),i=0;i10||t[0]>0}(),D.isNode&&D.toFastProperties(process);try{throw new Error}catch(V){D.lastLineError=V}e.exports=D},{"./es5":10}]},{},[3])(3)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.js b/node_modules/bluebird/js/browser/bluebird.js new file mode 100644 index 0000000..2bc524b --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.js @@ -0,0 +1,5623 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.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(); + 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(); + var self = this; + setTimeout(function() { + self._notifyUnhandledRejection(); + }, 1); +}; + +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; + } + } + return Promise; +}; + +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 && error.name != "SyntaxError") { + 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: error.name == "SyntaxError" ? 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, NEXT_FILTER) { +var util = _dereq_("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); + +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 === NEXT_FILTER) { + return ret; + } else 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); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + 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 Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; + +},{"./catch_filter":7,"./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", String(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 (!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, 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 (!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); + 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, NEXT_FILTER); +var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = _dereq_("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + 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("Catch statement predicate: " + + "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" && + 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) { + if (executor === INTERNAL) return; + 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.5.1"; +_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 {}; + case -6: return new Map(); + } +} + +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, isMap ? -6 : -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.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 instanceof Error || + (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]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +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, + hasEnvVariables: hasEnvVariables, + 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; } \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/bluebird/js/browser/bluebird.min.js new file mode 100644 index 0000000..e02a9cd --- /dev/null +++ b/node_modules/bluebird/js/browser/bluebird.min.js @@ -0,0 +1,31 @@ +/* @preserve + * The MIT License (MIT) + * + * Copyright (c) 2013-2017 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.5.1 + * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each +*/ +!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),c=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,Q=e,$=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return i(this,t,e,0)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,r){return i(t,r,e,0)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},i}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=e._async;u.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!f.isObject(o))return p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(x.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new E(this).promise()},i.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=h),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=h),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.warnings()){var o="a promise was rejected with a non-error: "+f.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?t._cancel():r.cancel()):"function"==typeof e?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.1",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),f.toFastProperties(i),f.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),x.setBounds(d.firstLineError,f.lastLineError),i}},{"./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(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nc;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:f.domainBind(s,n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,i===o?this._eachValues=Array(this._length):0===i?this._eachValues=null:this._eachValues=void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s&&"function"==typeof s.resolve){var l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t), +this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.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()},r=e.prototype.error=e.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()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=P;return P=null,t.apply(this,arguments)}catch(e){return T.e=e,T}}function i(t){return P=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i10||t[0]>0}(),B.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/release/any.js b/node_modules/bluebird/js/release/any.js new file mode 100644 index 0000000..05a6228 --- /dev/null +++ b/node_modules/bluebird/js/release/any.js @@ -0,0 +1,21 @@ +"use strict"; +module.exports = function(Promise) { +var SomePromiseArray = Promise._SomePromiseArray; +function any(promises) { + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(1); + ret.setUnwrap(); + ret.init(); + return promise; +} + +Promise.any = function (promises) { + return any(promises); +}; + +Promise.prototype.any = function () { + return any(this); +}; + +}; diff --git a/node_modules/bluebird/js/release/assert.js b/node_modules/bluebird/js/release/assert.js new file mode 100644 index 0000000..4518231 --- /dev/null +++ b/node_modules/bluebird/js/release/assert.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = (function(){ +var AssertionError = (function() { + function AssertionError(a) { + this.constructor$(a); + this.message = a; + this.name = "AssertionError"; + } + AssertionError.prototype = new Error(); + AssertionError.prototype.constructor = AssertionError; + AssertionError.prototype.constructor$ = Error; + return AssertionError; +})(); + +function getParams(args) { + var params = []; + for (var i = 0; i < args.length; ++i) params.push("arg" + i); + return params; +} + +function nativeAssert(callName, args, expect) { + try { + var params = getParams(args); + var constructorArgs = params; + constructorArgs.push("return " + + callName + "("+ params.join(",") + ");"); + var fn = Function.apply(null, constructorArgs); + return fn.apply(null, args); + } catch (e) { + if (!(e instanceof SyntaxError)) { + throw e; + } else { + return expect; + } + } +} + +return function assert(boolExpr, message) { + if (boolExpr === true) return; + + if (typeof boolExpr === "string" && + boolExpr.charAt(0) === "%") { + var nativeCallName = boolExpr; + var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];}; + if (nativeAssert(nativeCallName, args, message) === message) return; + message = (nativeCallName + " !== " + message); + } + + var ret = new AssertionError(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(ret, assert); + } + throw ret; +}; +})(); diff --git a/node_modules/bluebird/js/release/async.js b/node_modules/bluebird/js/release/async.js new file mode 100644 index 0000000..41f6655 --- /dev/null +++ b/node_modules/bluebird/js/release/async.js @@ -0,0 +1,161 @@ +"use strict"; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = require("./schedule"); +var Queue = require("./queue"); +var util = require("./util"); + +function Async() { + this._customScheduler = false; + this._isTickUsed = false; + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); + this._haveDrainedQueues = false; + this._trampolineEnabled = true; + var self = this; + this.drainQueues = function () { + self._drainQueues(); + }; + this._schedule = schedule; +} + +Async.prototype.setScheduler = function(fn) { + var prev = this._schedule; + this._schedule = fn; + this._customScheduler = true; + return prev; +}; + +Async.prototype.hasCustomScheduler = function() { + return this._customScheduler; +}; + +Async.prototype.enableTrampoline = function() { + this._trampolineEnabled = true; +}; + +Async.prototype.disableTrampolineIfNecessary = function() { + if (util.hasDevTools) { + this._trampolineEnabled = false; + } +}; + +Async.prototype.haveItemsQueued = function () { + return this._isTickUsed || this._haveDrainedQueues; +}; + + +Async.prototype.fatalError = function(e, isNode) { + if (isNode) { + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + + "\n"); + process.exit(2); + } else { + this.throwLater(e); + } +}; + +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } +}; + +function AsyncInvokeLater(fn, receiver, arg) { + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncInvoke(fn, receiver, arg) { + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +} + +function AsyncSettlePromises(promise) { + this._normalQueue._pushOne(promise); + this._queueTick(); +} + +if (!util.hasDevTools) { + Async.prototype.invokeLater = AsyncInvokeLater; + Async.prototype.invoke = AsyncInvoke; + Async.prototype.settlePromises = AsyncSettlePromises; +} else { + Async.prototype.invokeLater = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvokeLater.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + setTimeout(function() { + fn.call(receiver, arg); + }, 100); + }); + } + }; + + Async.prototype.invoke = function (fn, receiver, arg) { + if (this._trampolineEnabled) { + AsyncInvoke.call(this, fn, receiver, arg); + } else { + this._schedule(function() { + fn.call(receiver, arg); + }); + } + }; + + Async.prototype.settlePromises = function(promise) { + if (this._trampolineEnabled) { + AsyncSettlePromises.call(this, promise); + } else { + this._schedule(function() { + promise._settlePromises(); + }); + } + }; +} + +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 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; diff --git a/node_modules/bluebird/js/release/bind.js b/node_modules/bluebird/js/release/bind.js new file mode 100644 index 0000000..fc3379d --- /dev/null +++ b/node_modules/bluebird/js/release/bind.js @@ -0,0 +1,67 @@ +"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); +}; +}; diff --git a/node_modules/bluebird/js/release/bluebird.js b/node_modules/bluebird/js/release/bluebird.js new file mode 100644 index 0000000..1c36cf3 --- /dev/null +++ b/node_modules/bluebird/js/release/bluebird.js @@ -0,0 +1,11 @@ +"use strict"; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = require("./promise")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; diff --git a/node_modules/bluebird/js/release/call_get.js b/node_modules/bluebird/js/release/call_get.js new file mode 100644 index 0000000..0ed7714 --- /dev/null +++ b/node_modules/bluebird/js/release/call_get.js @@ -0,0 +1,123 @@ +"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 = require("./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 $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; + 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); +}; +}; diff --git a/node_modules/bluebird/js/release/cancel.js b/node_modules/bluebird/js/release/cancel.js new file mode 100644 index 0000000..7a12415 --- /dev/null +++ b/node_modules/bluebird/js/release/cancel.js @@ -0,0 +1,129 @@ +"use strict"; +module.exports = function(Promise, PromiseArray, apiRejection, debug) { +var util = require("./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(); +}; + +}; diff --git a/node_modules/bluebird/js/release/catch_filter.js b/node_modules/bluebird/js/release/catch_filter.js new file mode 100644 index 0000000..0f24ce2 --- /dev/null +++ b/node_modules/bluebird/js/release/catch_filter.js @@ -0,0 +1,42 @@ +"use strict"; +module.exports = function(NEXT_FILTER) { +var util = require("./util"); +var getKeys = require("./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; +}; diff --git a/node_modules/bluebird/js/release/context.js b/node_modules/bluebird/js/release/context.js new file mode 100644 index 0000000..c307414 --- /dev/null +++ b/node_modules/bluebird/js/release/context.js @@ -0,0 +1,69 @@ +"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; +}; diff --git a/node_modules/bluebird/js/release/debuggability.js b/node_modules/bluebird/js/release/debuggability.js new file mode 100644 index 0000000..6956804 --- /dev/null +++ b/node_modules/bluebird/js/release/debuggability.js @@ -0,0 +1,919 @@ +"use strict"; +module.exports = function(Promise, Context) { +var getDomain = Promise._getDomain; +var async = Promise._async; +var Warning = require("./errors").Warning; +var util = require("./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 && + (false || + 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(); + var self = this; + setTimeout(function() { + self._notifyUnhandledRejection(); + }, 1); +}; + +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; + } + } + return Promise; +}; + +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 && error.name != "SyntaxError") { + 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: error.name == "SyntaxError" ? 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 +}; +}; diff --git a/node_modules/bluebird/js/release/direct_resolve.js b/node_modules/bluebird/js/release/direct_resolve.js new file mode 100644 index 0000000..a890298 --- /dev/null +++ b/node_modules/bluebird/js/release/direct_resolve.js @@ -0,0 +1,46 @@ +"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); + } +}; +}; diff --git a/node_modules/bluebird/js/release/each.js b/node_modules/bluebird/js/release/each.js new file mode 100644 index 0000000..e4f3d05 --- /dev/null +++ b/node_modules/bluebird/js/release/each.js @@ -0,0 +1,30 @@ +"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; +}; + diff --git a/node_modules/bluebird/js/release/errors.js b/node_modules/bluebird/js/release/errors.js new file mode 100644 index 0000000..f62f323 --- /dev/null +++ b/node_modules/bluebird/js/release/errors.js @@ -0,0 +1,116 @@ +"use strict"; +var es5 = require("./es5"); +var Objectfreeze = es5.freeze; +var util = require("./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 +}; diff --git a/node_modules/bluebird/js/release/es5.js b/node_modules/bluebird/js/release/es5.js new file mode 100644 index 0000000..ea41d5a --- /dev/null +++ b/node_modules/bluebird/js/release/es5.js @@ -0,0 +1,80 @@ +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; + } + }; +} diff --git a/node_modules/bluebird/js/release/filter.js b/node_modules/bluebird/js/release/filter.js new file mode 100644 index 0000000..ed57bf0 --- /dev/null +++ b/node_modules/bluebird/js/release/filter.js @@ -0,0 +1,12 @@ +"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); +}; +}; diff --git a/node_modules/bluebird/js/release/finally.js b/node_modules/bluebird/js/release/finally.js new file mode 100644 index 0000000..d57444b --- /dev/null +++ b/node_modules/bluebird/js/release/finally.js @@ -0,0 +1,146 @@ +"use strict"; +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { +var util = require("./util"); +var CancellationError = Promise.CancellationError; +var errorObj = util.errorObj; +var catchFilter = require("./catch_filter")(NEXT_FILTER); + +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 === NEXT_FILTER) { + return ret; + } else 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); +}; + +Promise.prototype.tapCatch = function (handlerOrPredicate) { + var len = arguments.length; + if(len === 1) { + return this._passThrough(handlerOrPredicate, + 1, + undefined, + finallyHandler); + } else { + 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 Promise.reject(new TypeError( + "tapCatch statement predicate: " + + "expecting an object but got " + util.classString(item) + )); + } + } + catchInstances.length = j; + var handler = arguments[i]; + return this._passThrough(catchFilter(catchInstances, handler, this), + 1, + undefined, + finallyHandler); + } + +}; + +return PassThroughHandlerContext; +}; diff --git a/node_modules/bluebird/js/release/generators.js b/node_modules/bluebird/js/release/generators.js new file mode 100644 index 0000000..500c280 --- /dev/null +++ b/node_modules/bluebird/js/release/generators.js @@ -0,0 +1,223 @@ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise, + Proxyable, + debug) { +var errors = require("./errors"); +var TypeError = errors.TypeError; +var util = require("./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", String(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; +}; +}; diff --git a/node_modules/bluebird/js/release/join.js b/node_modules/bluebird/js/release/join.js new file mode 100644 index 0000000..4945e3f --- /dev/null +++ b/node_modules/bluebird/js/release/join.js @@ -0,0 +1,168 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, + getDomain) { +var util = require("./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 $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; + +}; diff --git a/node_modules/bluebird/js/release/map.js b/node_modules/bluebird/js/release/map.js new file mode 100644 index 0000000..976f15e --- /dev/null +++ b/node_modules/bluebird/js/release/map.js @@ -0,0 +1,168 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = require("./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); +}; + + +}; diff --git a/node_modules/bluebird/js/release/method.js b/node_modules/bluebird/js/release/method.js new file mode 100644 index 0000000..ce9e4db --- /dev/null +++ b/node_modules/bluebird/js/release/method.js @@ -0,0 +1,55 @@ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { +var util = require("./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); + } +}; +}; diff --git a/node_modules/bluebird/js/release/nodeback.js b/node_modules/bluebird/js/release/nodeback.js new file mode 100644 index 0000000..71e69eb --- /dev/null +++ b/node_modules/bluebird/js/release/nodeback.js @@ -0,0 +1,51 @@ +"use strict"; +var util = require("./util"); +var maybeWrapAsError = util.maybeWrapAsError; +var errors = require("./errors"); +var OperationalError = errors.OperationalError; +var es5 = require("./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 $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; + promise._fulfill(args); + } + promise = null; + }; +} + +module.exports = nodebackForPromise; diff --git a/node_modules/bluebird/js/release/nodeify.js b/node_modules/bluebird/js/release/nodeify.js new file mode 100644 index 0000000..ce2b190 --- /dev/null +++ b/node_modules/bluebird/js/release/nodeify.js @@ -0,0 +1,58 @@ +"use strict"; +module.exports = function(Promise) { +var util = require("./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; +}; +}; diff --git a/node_modules/bluebird/js/release/promise.js b/node_modules/bluebird/js/release/promise.js new file mode 100644 index 0000000..f4a641c --- /dev/null +++ b/node_modules/bluebird/js/release/promise.js @@ -0,0 +1,775 @@ +"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 = require("./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 = require("./es5"); +var Async = require("./async"); +var async = new Async(); +es5.defineProperty(Promise, "_async", {value: async}); +var errors = require("./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 = require("./thenables")(Promise, INTERNAL); +var PromiseArray = + require("./promise_array")(Promise, INTERNAL, + tryConvertToPromise, apiRejection, Proxyable); +var Context = require("./context")(Promise); + /*jshint unused:false*/ +var createContext = Context.create; +var debug = require("./debuggability")(Promise, Context); +var CapturedTrace = debug.CapturedTrace; +var PassThroughHandlerContext = + require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); +var catchFilter = require("./catch_filter")(NEXT_FILTER); +var nodebackForPromise = require("./nodeback"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +function check(self, executor) { + if (self == null || self.constructor !== Promise) { + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); + } + if (typeof executor !== "function") { + throw new TypeError("expecting a function but got " + util.classString(executor)); + } + +} + +function Promise(executor) { + if (executor !== INTERNAL) { + check(this, executor); + } + this._bitField = 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + 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("Catch statement predicate: " + + "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" && + 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) { + if (executor === INTERNAL) return; + 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); + +require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, + debug); +require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); +require("./cancel")(Promise, PromiseArray, apiRejection, debug); +require("./direct_resolve")(Promise); +require("./synchronous_inspection")(Promise); +require("./join")( + Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); +Promise.Promise = Promise; +Promise.version = "3.5.1"; +require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./call_get.js')(Promise); +require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); +require('./timers.js')(Promise, INTERNAL, debug); +require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); +require('./nodeify.js')(Promise); +require('./promisify.js')(Promise, INTERNAL); +require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); +require('./settle.js')(Promise, PromiseArray, debug); +require('./some.js')(Promise, PromiseArray, apiRejection); +require('./filter.js')(Promise, INTERNAL); +require('./each.js')(Promise, INTERNAL); +require('./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; + +}; diff --git a/node_modules/bluebird/js/release/promise_array.js b/node_modules/bluebird/js/release/promise_array.js new file mode 100644 index 0000000..0fb303e --- /dev/null +++ b/node_modules/bluebird/js/release/promise_array.js @@ -0,0 +1,185 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection, Proxyable) { +var util = require("./util"); +var isArray = util.isArray; + +function toResolutionValue(val) { + switch(val) { + case -2: return []; + case -3: return {}; + case -6: return new Map(); + } +} + +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; +}; diff --git a/node_modules/bluebird/js/release/promisify.js b/node_modules/bluebird/js/release/promisify.js new file mode 100644 index 0000000..aa98e5b --- /dev/null +++ b/node_modules/bluebird/js/release/promisify.js @@ -0,0 +1,314 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var THIS = {}; +var util = require("./util"); +var nodebackForPromise = require("./nodeback"); +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = require("./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); +}; +}; + diff --git a/node_modules/bluebird/js/release/props.js b/node_modules/bluebird/js/release/props.js new file mode 100644 index 0000000..6a34aaf --- /dev/null +++ b/node_modules/bluebird/js/release/props.js @@ -0,0 +1,118 @@ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = require("./util"); +var isObject = util.isObject; +var es5 = require("./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, isMap ? -6 : -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); +}; +}; diff --git a/node_modules/bluebird/js/release/queue.js b/node_modules/bluebird/js/release/queue.js new file mode 100644 index 0000000..ffd36fd --- /dev/null +++ b/node_modules/bluebird/js/release/queue.js @@ -0,0 +1,73 @@ +"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.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; diff --git a/node_modules/bluebird/js/release/race.js b/node_modules/bluebird/js/release/race.js new file mode 100644 index 0000000..b862f46 --- /dev/null +++ b/node_modules/bluebird/js/release/race.js @@ -0,0 +1,49 @@ +"use strict"; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = require("./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); +}; + +}; diff --git a/node_modules/bluebird/js/release/reduce.js b/node_modules/bluebird/js/release/reduce.js new file mode 100644 index 0000000..26e2b1a --- /dev/null +++ b/node_modules/bluebird/js/release/reduce.js @@ -0,0 +1,172 @@ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL, + debug) { +var getDomain = Promise._getDomain; +var util = require("./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; +} +}; diff --git a/node_modules/bluebird/js/release/schedule.js b/node_modules/bluebird/js/release/schedule.js new file mode 100644 index 0000000..f70df9f --- /dev/null +++ b/node_modules/bluebird/js/release/schedule.js @@ -0,0 +1,61 @@ +"use strict"; +var util = require("./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; diff --git a/node_modules/bluebird/js/release/settle.js b/node_modules/bluebird/js/release/settle.js new file mode 100644 index 0000000..fade3a1 --- /dev/null +++ b/node_modules/bluebird/js/release/settle.js @@ -0,0 +1,43 @@ +"use strict"; +module.exports = + function(Promise, PromiseArray, debug) { +var PromiseInspection = Promise.PromiseInspection; +var util = require("./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); +}; +}; diff --git a/node_modules/bluebird/js/release/some.js b/node_modules/bluebird/js/release/some.js new file mode 100644 index 0000000..400d852 --- /dev/null +++ b/node_modules/bluebird/js/release/some.js @@ -0,0 +1,148 @@ +"use strict"; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = require("./util"); +var RangeError = require("./errors").RangeError; +var AggregateError = require("./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; +}; diff --git a/node_modules/bluebird/js/release/synchronous_inspection.js b/node_modules/bluebird/js/release/synchronous_inspection.js new file mode 100644 index 0000000..9c49d2e --- /dev/null +++ b/node_modules/bluebird/js/release/synchronous_inspection.js @@ -0,0 +1,103 @@ +"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; +}; diff --git a/node_modules/bluebird/js/release/thenables.js b/node_modules/bluebird/js/release/thenables.js new file mode 100644 index 0000000..d6ab9aa --- /dev/null +++ b/node_modules/bluebird/js/release/thenables.js @@ -0,0 +1,86 @@ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = require("./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; +}; diff --git a/node_modules/bluebird/js/release/timers.js b/node_modules/bluebird/js/release/timers.js new file mode 100644 index 0000000..cb8f1f4 --- /dev/null +++ b/node_modules/bluebird/js/release/timers.js @@ -0,0 +1,93 @@ +"use strict"; +module.exports = function(Promise, INTERNAL, debug) { +var util = require("./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; +}; + +}; diff --git a/node_modules/bluebird/js/release/using.js b/node_modules/bluebird/js/release/using.js new file mode 100644 index 0000000..65de531 --- /dev/null +++ b/node_modules/bluebird/js/release/using.js @@ -0,0 +1,226 @@ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext, INTERNAL, debug) { + var util = require("./util"); + var TypeError = require("./errors").TypeError; + var inherits = require("./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(); + }; + +}; diff --git a/node_modules/bluebird/js/release/util.js b/node_modules/bluebird/js/release/util.js new file mode 100644 index 0000000..7ac0e2f --- /dev/null +++ b/node_modules/bluebird/js/release/util.js @@ -0,0 +1,380 @@ +"use strict"; +var es5 = require("./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 instanceof Error || + (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]"; + +var hasEnvVariables = typeof process !== "undefined" && + typeof process.env !== "undefined"; + +function env(key) { + return hasEnvVariables ? process.env[key] : undefined; +} + +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, + hasEnvVariables: hasEnvVariables, + 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; diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json new file mode 100644 index 0000000..782d74d --- /dev/null +++ b/node_modules/bluebird/package.json @@ -0,0 +1,101 @@ +{ + "_from": "bluebird@^3.4.6", + "_id": "bluebird@3.5.1", + "_inBundle": false, + "_integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", + "_location": "/bluebird", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bluebird@^3.4.6", + "name": "bluebird", + "escapedName": "bluebird", + "rawSpec": "^3.4.6", + "saveSpec": null, + "fetchSpec": "^3.4.6" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", + "_shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", + "_spec": "bluebird@^3.4.6", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", + "author": { + "name": "Petka Antonov", + "email": "petka_antonov@hotmail.com", + "url": "http://github.com/petkaantonov/" + }, + "browser": "./js/browser/bluebird.js", + "bugs": { + "url": "http://github.com/petkaantonov/bluebird/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Full featured Promises/A+ implementation with exceptionally good performance", + "devDependencies": { + "acorn": "~0.6.0", + "baconjs": "^0.7.43", + "bluebird": "^2.9.2", + "body-parser": "^1.10.2", + "browserify": "^8.1.1", + "cli-table": "~0.3.1", + "co": "^4.2.0", + "cross-spawn": "^0.2.3", + "glob": "^4.3.2", + "grunt-saucelabs": "~8.4.1", + "highland": "^2.3.0", + "istanbul": "^0.3.5", + "jshint": "^2.6.0", + "jshint-stylish": "~0.2.0", + "kefir": "^2.4.1", + "mkdirp": "~0.5.0", + "mocha": "~2.1", + "open": "~0.0.5", + "optimist": "~0.6.1", + "rimraf": "~2.2.6", + "rx": "^2.3.25", + "serve-static": "^1.7.1", + "sinon": "~1.7.3", + "uglify-js": "~2.4.16" + }, + "files": [ + "js/browser", + "js/release", + "LICENSE" + ], + "homepage": "https://github.com/petkaantonov/bluebird", + "keywords": [ + "promise", + "performance", + "promises", + "promises-a", + "promises-aplus", + "async", + "await", + "deferred", + "deferreds", + "future", + "flow control", + "dsl", + "fluent interface" + ], + "license": "MIT", + "main": "./js/release/bluebird.js", + "name": "bluebird", + "repository": { + "type": "git", + "url": "git://github.com/petkaantonov/bluebird.git" + }, + "scripts": { + "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", + "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", + "istanbul": "istanbul", + "lint": "node scripts/jshint.js", + "prepublish": "npm run generate-browser-core && npm run generate-browser-full", + "test": "node tools/test.js" + }, + "version": "3.5.1", + "webpack": "./js/release/bluebird.js" +} diff --git a/node_modules/buffer-more-ints/.npmignore b/node_modules/buffer-more-ints/.npmignore new file mode 100644 index 0000000..abd60f7 --- /dev/null +++ b/node_modules/buffer-more-ints/.npmignore @@ -0,0 +1,2 @@ +/node_modules +*~ diff --git a/node_modules/buffer-more-ints/LICENSE b/node_modules/buffer-more-ints/LICENSE new file mode 100644 index 0000000..e0d6370 --- /dev/null +++ b/node_modules/buffer-more-ints/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 David Wragg. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/buffer-more-ints/README.md b/node_modules/buffer-more-ints/README.md new file mode 100644 index 0000000..2fe7e91 --- /dev/null +++ b/node_modules/buffer-more-ints/README.md @@ -0,0 +1,68 @@ +# buffer-more-ints: Add support for more integer widths to Buffer + +Node's Buffer only supports reading and writing integers of a limited +range of widths. This module provides support for more widths, so +that integers from 1 to 8 bytes (64 bits) can be accessed. The +support takes two forms. Firstly, as stand-alone functions similar to +the integer reading/writing methods of Buffer: + + $ node + > var moreints = require('buffer-more-ints') + undefined + > moreints.readInt64BE(new Buffer("0000deadbeef0000", "hex"), 0).toString(16) + 'deadbeef0000' + +Read and write functions for the regular widths (8, 16, 32) are also +present in this module, for consistency. + +The second form is methods patched into `Buffer.prototype`, installed +by requiring `'buffer-more-ints/polyfill'`: + + $ node + > require('buffer-more-ints/polyfill') + {} + > new Buffer("0000deadbeef0000", "hex").readInt64BE(0).toString(16) + 'deadbeef0000' + + +buffer-more-ints/polyfill also adds methods `readIntBE`, `writeIntBE`, +and their LE and UInt counterparts, which take an initial argument +giving the width of the integer in bytes: + + > var b = new Buffer(3); + > b.writeIntLE(3, -123456, 0); + > b.toString('hex') + 'c01dfe' + > b.readIntLE(3, 0); + -123456 + +The functions added by buffer-more-ints are all implemented in terms +of the core Buffer functions. Part way through writing the code, I +discovered that node.js currently implements those in JavaScript, so +this doesn't lead to performance benefits. But should node ever +switch to implementing its Buffer operations natively, this +module should get a speed boost. + +## Limitations + +As JavaScript uses IEEE754 doubles for numbers, the contiguous range +of integers it can represent is [-2^53 - 1, 2^53 - 1]. So only +integer widths up to 6 bytes or 48 bits can be read exactly. Reads of +7 or 8 bytes (56 or 64 bits) will return the closest value that can be +represented as a JavaScript number. + +In certain situations it might be important to check that a JavaScript +number was read exactly. The `isContiguousInt` or +`Buffer.isContiguousInt` (polyfill) function will determine this: + + > Buffer.isContiguousInt(0x1fffffffffffff); + true + > Buffer.isContiguousInt(0x20000000000000); + false + +And `assertContiguousInt` asserts that a number is so: + + > Buffer.assertContiguousInt(0x1fffffffffffff); + undefined + > Buffer.assertContiguousInt(0x20000000000000); + AssertionError: number cannot be represented as a contiguous integer diff --git a/node_modules/buffer-more-ints/buffer-more-ints-tests.js b/node_modules/buffer-more-ints/buffer-more-ints-tests.js new file mode 100644 index 0000000..25bd848 --- /dev/null +++ b/node_modules/buffer-more-ints/buffer-more-ints-tests.js @@ -0,0 +1,207 @@ +'use strict'; + +require('./polyfill'); + +// A simple abbreviation to obtain a buffer from a hex string +function h2b(str) { + return new Buffer(str, "hex"); +} + +// Reverse a buffer +function reverse(buf) { + var res = new Buffer(buf.length); + for (var i = 0, j = buf.length - 1; j >= 0; i++, j--) { + res[i] = buf[j]; + } + return res; +} + +// Fill a buffer with distinctive data +function scrub(buf) { + var pos = 0; + var written; + while ((written = buf.write("deadbeef", pos, 4, "hex")) == 4) { + pos += written; + } + return buf; +} + +function xint_case(xint) { + return function (assert, hex, val, inexact) { + var readBE = "read" + xint + "BE"; + var writeBE = "write" + xint + "BE"; + var readLE = "read" + xint + "LE"; + var writeLE = "write" + xint + "LE"; + + var len = hex.length / 2; + + // Straightforward read cases + assert.equal(h2b(hex)[readBE](len, 0), val); + assert.equal(reverse(h2b(hex))[readLE](len, 0), val); + + // Test straightforward writes and noAssert writes off the ends of + // the buffer + var buf = scrub(new Buffer(len)); + buf[writeBE](len, val, 0); + if (!inexact) { + assert.equal(buf.toString("hex"), hex); + } else { + assert.equal(buf[readBE](len, 0), val); + } + + var buf2 = scrub(new Buffer(len)); + buf2[writeBE](len, val, -1, true); + assert.equal(buf2.slice(0, len-1).toString("hex"), + buf.slice(1, len).toString("hex")); + scrub(buf2); + buf2[writeBE](len, val, 1, true); + assert.equal(buf2.slice(1, len).toString("hex"), + buf.slice(0, len-1).toString("hex")); + + scrub(buf); + buf[writeLE](len, val, 0); + if (!inexact) { + assert.equal(reverse(buf).toString("hex"), hex); + } else { + assert.equal(buf[readLE](len, 0), val); + } + + scrub(buf2); + buf2[writeLE](len, val, -1, true); + assert.equal(buf2.slice(0, len-1).toString("hex"), + buf.slice(1, len).toString("hex")); + scrub(buf2); + buf2[writeLE](len, val, 1, true); + assert.equal(buf2.slice(1, len).toString("hex"), + buf.slice(0, len-1).toString("hex")); + + // Accessess off the end of the buffer should throw. Node + // doesn't catch negative offsets. + assert.throws(function () { h2b(hex)[readBE](len, 1); }) + assert.throws(function () { reverse(h2b(hex))[readLE](len, 1); }) + assert.throws(function () { buf[writeBE](len, val, 1); }); + assert.throws(function () { buf[writeLE](len, val, 1); }); + + // Test noAssert reads that stray off the ends of the buffer. + var expect = h2b("00"+hex)[readBE](len, 0); + assert.equal(h2b(hex)[readBE](len, -1, true), expect); + assert.equals(reverse(h2b(hex))[readLE](len, 1, true), expect); + + expect = h2b(hex+"00")[readBE](len, 1); + assert.equal(h2b(hex)[readBE](len, 1, true), expect); + assert.equal(reverse(h2b(hex))[readLE](len, -1, true), expect); + }; +} + +var uint_case = xint_case("UInt"); +var int_case = xint_case("Int"); + +module.exports.uint = function (assert) { + uint_case(assert, "00", 0x00); + uint_case(assert, "01", 0x01); + uint_case(assert, "ff", 0xff); + + uint_case(assert, "0000", 0x0000); + uint_case(assert, "0102", 0x0102); + uint_case(assert, "ffff", 0xffff); + + uint_case(assert, "000000", 0x000000); + uint_case(assert, "010203", 0x010203); + uint_case(assert, "ffffff", 0xffffff); + + uint_case(assert, "00000000", 0x00000000); + uint_case(assert, "01020304", 0x01020304); + uint_case(assert, "ffffffff", 0xffffffff); + + uint_case(assert, "0000000000", 0x0000000000); + uint_case(assert, "0102030405", 0x0102030405); + uint_case(assert, "ffffffffff", 0xffffffffff); + + uint_case(assert, "000000000000", 0x000000000000); + uint_case(assert, "010203040506", 0x010203040506); + uint_case(assert, "ffffffffffff", 0xffffffffffff); + + uint_case(assert, "00000000000000", 0x00000000000000); + uint_case(assert, "01020304050607", 0x01020304050607); + uint_case(assert, "ffffffffffffff", 0xffffffffffffff); + + uint_case(assert, "0000000000000000", 0x0000000000000000); + uint_case(assert, "0102030405060708", 0x0102030405060708, true); + uint_case(assert, "ffffffffffffffff", 0xffffffffffffffff); + + assert.done(); +}; + +module.exports.int = function (assert) { + int_case(assert, "00", 0x00); + int_case(assert, "01", 0x01); + int_case(assert, "7f", 0x7f); + int_case(assert, "80", -0x80); + int_case(assert, "ff", -0x01); + + int_case(assert, "0000", 0x0000); + int_case(assert, "0102", 0x0102); + int_case(assert, "7fff", 0x7fff); + int_case(assert, "8000", -0x8000); + int_case(assert, "ffff", -0x0001); + + int_case(assert, "000000", 0x000000); + int_case(assert, "010203", 0x010203); + int_case(assert, "7fffff", 0x7fffff); + int_case(assert, "800000", -0x800000); + int_case(assert, "ffffff", -0x000001); + + int_case(assert, "00000000", 0x00000000); + int_case(assert, "01020304", 0x01020304); + int_case(assert, "7fffffff", 0x7fffffff); + int_case(assert, "80000000", -0x80000000); + int_case(assert, "ffffffff", -0x00000001); + + int_case(assert, "0000000000", 0x0000000000); + int_case(assert, "0102030405", 0x0102030405); + int_case(assert, "7fffffffff", 0x7fffffffff); + int_case(assert, "8000000000", -0x8000000000); + int_case(assert, "ffffffffff", -0x0000000001); + + int_case(assert, "000000000000", 0x000000000000); + int_case(assert, "010203040506", 0x010203040506); + int_case(assert, "7fffffffffff", 0x7fffffffffff); + int_case(assert, "800000000000", -0x800000000000); + int_case(assert, "ffffffffffff", -0x000000000001); + + int_case(assert, "00000000000000", 0x00000000000000); + int_case(assert, "01020304050607", 0x01020304050607); + int_case(assert, "7fffffffffffff", 0x7fffffffffffff); + int_case(assert, "80000000000000", -0x80000000000000); + int_case(assert, "ffffffffffffff", -0x00000000000001); + + int_case(assert, "0000000000000000", 0x0000000000000000); + int_case(assert, "0102030405060708", 0x0102030405060708, true); + int_case(assert, "7fffffffffffffff", 0x7fffffffffffffff); + int_case(assert, "8000000000000000", -0x8000000000000000); + int_case(assert, "ffffffffffffffff", -0x0000000000000001); + + assert.done(); +}; + +module.exports.isContiguousInt = function (assert) { + assert.equal(Buffer.isContiguousInt(0x1fffffffffffff), true); + assert.equal(Buffer.isContiguousInt(0x20000000000000), false); + assert.equal(Buffer.isContiguousInt(-0x1fffffffffffff), true); + assert.equal(Buffer.isContiguousInt(-0x20000000000000), false); + + assert.doesNotThrow(function () { + Buffer.assertContiguousInt(0x1fffffffffffff); + }); + assert.throws(function () { + Buffer.assertContiguousInt(0x20000000000000); + }); + assert.doesNotThrow(function () { + Buffer.assertContiguousInt(-0x1fffffffffffff); + }); + assert.throws(function () { + Buffer.assertContiguousInt(-0x20000000000000); + }); + + assert.done(); +}; diff --git a/node_modules/buffer-more-ints/buffer-more-ints.js b/node_modules/buffer-more-ints/buffer-more-ints.js new file mode 100644 index 0000000..b0ae27d --- /dev/null +++ b/node_modules/buffer-more-ints/buffer-more-ints.js @@ -0,0 +1,472 @@ +'use strict'; + +var assert = require("assert"); + +// JavaScript is numerically challenged +var SHIFT_LEFT_32 = (1 << 16) * (1 << 16); +var SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; + +// The maximum contiguous integer that can be held in a IEEE754 double +var MAX_INT = 0x1fffffffffffff; + +function isContiguousInt(val) { + return val <= MAX_INT && val >= -MAX_INT; +} + +function assertContiguousInt(val) { + assert(isContiguousInt(val), "number cannot be represented as a contiguous integer"); +} + +module.exports.isContiguousInt = isContiguousInt; +module.exports.assertContiguousInt = assertContiguousInt; + +// Fill in the regular procedures +['UInt', 'Int'].forEach(function (sign) { + var suffix = sign + '8'; + module.exports['read' + suffix] = + Buffer.prototype['read' + suffix].call; + module.exports['write' + suffix] = + Buffer.prototype['write' + suffix].call; + + ['16', '32'].forEach(function (size) { + ['LE', 'BE'].forEach(function (endian) { + var suffix = sign + size + endian; + var read = Buffer.prototype['read' + suffix]; + module.exports['read' + suffix] = + function (buf, offset, noAssert) { + return read.call(buf, offset, noAssert); + }; + var write = Buffer.prototype['write' + suffix]; + module.exports['write' + suffix] = + function (buf, val, offset, noAssert) { + return write.call(buf, val, offset, noAssert); + }; + }); + }); +}); + +// Check that a value is an integer within the given range +function check_int(val, min, max) { + assert.ok(typeof(val) == 'number' && val >= min && val <= max && Math.floor(val) === val, "not a number in the required range"); +} + +function readUInt24BE(buf, offset, noAssert) { + return buf.readUInt8(offset, noAssert) << 16 | buf.readUInt16BE(offset + 1, noAssert); +} +module.exports.readUInt24BE = readUInt24BE; + +function writeUInt24BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffff); + assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeUInt8(val >>> 16, offset, noAssert); + buf.writeUInt16BE(val & 0xffff, offset + 1, noAssert); +} +module.exports.writeUInt24BE = writeUInt24BE; + +function readUInt40BE(buf, offset, noAssert) { + return (buf.readUInt8(offset, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1, noAssert); +} +module.exports.readUInt40BE = readUInt40BE; + +function writeUInt40BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffff); + assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 1, noAssert); +} +module.exports.writeUInt40BE = writeUInt40BE; + +function readUInt48BE(buf, offset, noAssert) { + return buf.readUInt16BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2, noAssert); +} +module.exports.readUInt48BE = readUInt48BE; + +function writeUInt48BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffff); + assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeUInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 2, noAssert); +} +module.exports.writeUInt48BE = writeUInt48BE; + +function readUInt56BE(buf, offset, noAssert) { + return ((buf.readUInt8(offset, noAssert) || 0) << 16 | buf.readUInt16BE(offset + 1, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3, noAssert); +} +module.exports.readUInt56BE = readUInt56BE; + +function writeUInt56BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffffff); + assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x100000000000000) { + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt8(hi >>> 16, offset, noAssert); + buf.writeUInt16BE(hi & 0xffff, offset + 1, noAssert); + buf.writeInt32BE(val & -1, offset + 3, noAssert); + } else { + // Special case because 2^56-1 gets rounded up to 2^56 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeUInt56BE = writeUInt56BE; + +function readUInt64BE(buf, offset, noAssert) { + return buf.readUInt32BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4, noAssert); +} +module.exports.readUInt64BE = readUInt64BE; + +function writeUInt64BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffffffff); + assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x10000000000000000) { + buf.writeUInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 4, noAssert); + } else { + // Special case because 2^64-1 gets rounded up to 2^64 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeUInt64BE = writeUInt64BE; + +function readUInt24LE(buf, offset, noAssert) { + return buf.readUInt8(offset + 2, noAssert) << 16 | buf.readUInt16LE(offset, noAssert); +} +module.exports.readUInt24LE = readUInt24LE; + +function writeUInt24LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffff); + assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeUInt16LE(val & 0xffff, offset, noAssert); + buf.writeUInt8(val >>> 16, offset + 2, noAssert); +} +module.exports.writeUInt24LE = writeUInt24LE; + +function readUInt40LE(buf, offset, noAssert) { + return (buf.readUInt8(offset + 4, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readUInt40LE = readUInt40LE; + +function writeUInt40LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffff); + assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); +} +module.exports.writeUInt40LE = writeUInt40LE; + +function readUInt48LE(buf, offset, noAssert) { + return buf.readUInt16LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readUInt48LE = readUInt48LE; + +function writeUInt48LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffff); + assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeUInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); +} +module.exports.writeUInt48LE = writeUInt48LE; + +function readUInt56LE(buf, offset, noAssert) { + return ((buf.readUInt8(offset + 6, noAssert) || 0) << 16 | buf.readUInt16LE(offset + 4, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readUInt56LE = readUInt56LE; + +function writeUInt56LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffffff); + assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x100000000000000) { + buf.writeInt32LE(val & -1, offset, noAssert); + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt16LE(hi & 0xffff, offset + 4, noAssert); + buf.writeUInt8(hi >>> 16, offset + 6, noAssert); + } else { + // Special case because 2^56-1 gets rounded up to 2^56 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeUInt56LE = writeUInt56LE; + +function readUInt64LE(buf, offset, noAssert) { + return buf.readUInt32LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readUInt64LE = readUInt64LE; + +function writeUInt64LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, 0, 0xffffffffffffffff); + assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x10000000000000000) { + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeUInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); + } else { + // Special case because 2^64-1 gets rounded up to 2^64 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeUInt64LE = writeUInt64LE; + + +function readInt24BE(buf, offset, noAssert) { + return (buf.readInt8(offset, noAssert) << 16) + buf.readUInt16BE(offset + 1, noAssert); +} +module.exports.readInt24BE = readInt24BE; + +function writeInt24BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000, 0x7fffff); + assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt8(val >> 16, offset, noAssert); + buf.writeUInt16BE(val & 0xffff, offset + 1, noAssert); +} +module.exports.writeInt24BE = writeInt24BE; + +function readInt40BE(buf, offset, noAssert) { + return (buf.readInt8(offset, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1, noAssert); +} +module.exports.readInt40BE = readInt40BE; + +function writeInt40BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x8000000000, 0x7fffffffff); + assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 1, noAssert); +} +module.exports.writeInt40BE = writeInt40BE; + +function readInt48BE(buf, offset, noAssert) { + return buf.readInt16BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2, noAssert); +} +module.exports.readInt48BE = readInt48BE; + +function writeInt48BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000000000, 0x7fffffffffff); + assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 2, noAssert); +} +module.exports.writeInt48BE = writeInt48BE; + +function readInt56BE(buf, offset, noAssert) { + return (((buf.readInt8(offset, noAssert) || 0) << 16) + buf.readUInt16BE(offset + 1, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3, noAssert); +} +module.exports.readInt56BE = readInt56BE; + +function writeInt56BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000000000000, 0x7fffffffffffff); + assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x80000000000000) { + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeInt8(hi >> 16, offset, noAssert); + buf.writeUInt16BE(hi & 0xffff, offset + 1, noAssert); + buf.writeInt32BE(val & -1, offset + 3, noAssert); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0x7f; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + } +} +module.exports.writeInt56BE = writeInt56BE; + +function readInt64BE(buf, offset, noAssert) { + return buf.readInt32BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4, noAssert); +} +module.exports.readInt64BE = readInt64BE; + +function writeInt64BE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000000000000000, 0x7fffffffffffffff); + assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x8000000000000000) { + buf.writeInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); + buf.writeInt32BE(val & -1, offset + 4, noAssert); + } else { + // Special case because 2^63-1 gets rounded up to 2^63 + buf[offset] = 0x7f; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0xff; + } +} +module.exports.writeInt64BE = writeInt64BE; + +function readInt24LE(buf, offset, noAssert) { + return (buf.readInt8(offset + 2, noAssert) << 16) + buf.readUInt16LE(offset, noAssert); +} +module.exports.readInt24LE = readInt24LE; + +function writeInt24LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000, 0x7fffff); + assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeUInt16LE(val & 0xffff, offset, noAssert); + buf.writeInt8(val >> 16, offset + 2, noAssert); +} +module.exports.writeInt24LE = writeInt24LE; + +function readInt40LE(buf, offset, noAssert) { + return (buf.readInt8(offset + 4, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readInt40LE = readInt40LE; + +function writeInt40LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x8000000000, 0x7fffffffff); + assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); +} +module.exports.writeInt40LE = writeInt40LE; + +function readInt48LE(buf, offset, noAssert) { + return buf.readInt16LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readInt48LE = readInt48LE; + +function writeInt48LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x800000000000, 0x7fffffffffff); + assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); + } + + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); +} +module.exports.writeInt48LE = writeInt48LE; + +function readInt56LE(buf, offset, noAssert) { + return (((buf.readInt8(offset + 6, noAssert) || 0) << 16) + buf.readUInt16LE(offset + 4, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readInt56LE = readInt56LE; + +function writeInt56LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x80000000000000, 0x7fffffffffffff); + assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x80000000000000) { + buf.writeInt32LE(val & -1, offset, noAssert); + var hi = Math.floor(val * SHIFT_RIGHT_32); + buf.writeUInt16LE(hi & 0xffff, offset + 4, noAssert); + buf.writeInt8(hi >> 16, offset + 6, noAssert); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0x7f; + } +} +module.exports.writeInt56LE = writeInt56LE; + +function readInt64LE(buf, offset, noAssert) { + return buf.readInt32LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); +} +module.exports.readInt64LE = readInt64LE; + +function writeInt64LE(buf, val, offset, noAssert) { + if (!noAssert) { + check_int(val, -0x8000000000000000, 0x7fffffffffffffff); + assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); + } + + if (val < 0x8000000000000000) { + buf.writeInt32LE(val & -1, offset, noAssert); + buf.writeInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); + } else { + // Special case because 2^55-1 gets rounded up to 2^55 + buf[offset] = 0xff; + buf[offset+1] = 0xff; + buf[offset+2] = 0xff; + buf[offset+3] = 0xff; + buf[offset+4] = 0xff; + buf[offset+5] = 0xff; + buf[offset+6] = 0xff; + buf[offset+7] = 0x7f; + } +} +module.exports.writeInt64LE = writeInt64LE; diff --git a/node_modules/buffer-more-ints/package.json b/node_modules/buffer-more-ints/package.json new file mode 100644 index 0000000..11998f2 --- /dev/null +++ b/node_modules/buffer-more-ints/package.json @@ -0,0 +1,50 @@ +{ + "_from": "buffer-more-ints@0.0.2", + "_id": "buffer-more-ints@0.0.2", + "_inBundle": false, + "_integrity": "sha1-JrOIXRD6E9t/wBquOquHAZngEkw=", + "_location": "/buffer-more-ints", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "buffer-more-ints@0.0.2", + "name": "buffer-more-ints", + "escapedName": "buffer-more-ints", + "rawSpec": "0.0.2", + "saveSpec": null, + "fetchSpec": "0.0.2" + }, + "_requiredBy": [ + "/amqplib", + "/bitsyntax" + ], + "_resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-0.0.2.tgz", + "_shasum": "26b3885d10fa13db7fc01aae3aab870199e0124c", + "_spec": "buffer-more-ints@0.0.2", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", + "author": { + "name": "David Wragg", + "email": "david@wragg.org" + }, + "bugs": { + "url": "https://github.com/dpw/node-buffer-more-ints/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Add support for more integer widths to Buffer", + "devDependencies": { + "nodeunit": "" + }, + "homepage": "https://github.com/dpw/node-buffer-more-ints", + "main": "buffer-more-ints.js", + "name": "buffer-more-ints", + "repository": { + "type": "git", + "url": "git+https://github.com/dpw/node-buffer-more-ints.git" + }, + "scripts": { + "test": "node ./node_modules/nodeunit/bin/nodeunit buffer-more-ints-tests.js" + }, + "version": "0.0.2" +} diff --git a/node_modules/buffer-more-ints/polyfill.js b/node_modules/buffer-more-ints/polyfill.js new file mode 100644 index 0000000..762fd98 --- /dev/null +++ b/node_modules/buffer-more-ints/polyfill.js @@ -0,0 +1,71 @@ +'use strict'; + +var bmi = require('./buffer-more-ints'); + +Buffer.isContiguousInt = bmi.isContiguousInt; +Buffer.assertContiguousInt = bmi.assertContiguousInt; + +['UInt', 'Int'].forEach(function (signed) { + ['24', '40', '48', '56', '64'].forEach(function (size) { + ['BE', 'LE'].forEach(function (endian) { + var read = 'read' + signed + size + endian; + var reader = bmi[read]; + Buffer.prototype[read] = function(offset, noAssert) { + return reader(this, offset, noAssert); + }; + var write = 'write' + signed + size + endian; + var writer = bmi[write]; + Buffer.prototype[write] = function(val, offset, noAssert) { + writer(this, val, offset, noAssert); + }; + }); + }); +}); + +// Buffer.prototype.read{UInt,Int}8 returns undefined if the offset is +// outside of the buffer, unlike for other widths. These functions +// make it consistent with the others. +var consistent_readX8 = { + readUInt8: function (offset, noAssert) { + return this.readUInt8(offset, noAssert) || 0; + }, + readInt8: function (offset, noAssert) { + return this.readInt8(offset, noAssert) || 0; + } +}; + +function make_accessor(read, prefix, suffix) { + var accessors = [false, + (read ? consistent_readX8 : Buffer.prototype)[prefix + 8]]; + + for (var i = 16; i <= 64; i += 8) { + accessors.push(Buffer.prototype[prefix + i + suffix]); + } + + if (read) { + Buffer.prototype[prefix + suffix] = function (len, offset, noAssert) { + var reader = accessors[len]; + if (reader) { + return reader.call(this, offset, noAssert); + } else { + throw new Error("Cannot read integer of length " + len); + } + }; + } else { + Buffer.prototype[prefix + suffix] = function (len, val, offset, noAssert) { + var writer = accessors[len]; + if (writer) { + return writer.call(this, val, offset, noAssert); + } else { + throw new Error("Cannot write integer of length " + len); + } + } + } +} + +['UInt', 'Int'].forEach(function (t) { + ['BE', 'LE'].forEach(function (e) { + make_accessor(true, "read" + t, e); + make_accessor(false, "write" + t, e); + }); +}); diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return 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'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json new file mode 100644 index 0000000..4c7ab94 --- /dev/null +++ b/node_modules/core-util-is/package.json @@ -0,0 +1,62 @@ +{ + "_from": "core-util-is@~1.0.0", + "_id": "core-util-is@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "_location": "/core-util-is", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "core-util-is@~1.0.0", + "name": "core-util-is", + "escapedName": "core-util-is", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", + "_spec": "core-util-is@~1.0.0", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The `util.is*` functions introduced in Node v0.12.", + "devDependencies": { + "tap": "^2.3.0" + }, + "homepage": "https://github.com/isaacs/core-util-is#readme", + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "license": "MIT", + "main": "lib/util.js", + "name": "core-util-is", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "scripts": { + "test": "tap test.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..3b94763 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..aeeee23 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@~2.0.1", + "_id": "inherits@2.0.3", + "_inBundle": false, + "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@~2.0.1", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "~2.0.1", + "saveSpec": null, + "fetchSpec": "~2.0.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "_shasum": "633c2c83e3da42a502f52466022480f4208261de", + "_spec": "inherits@~2.0.1", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "node test" + }, + "version": "2.0.3" +} diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/isarray/build/build.js b/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/node_modules/isarray/component.json b/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/isarray/index.js b/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json new file mode 100644 index 0000000..c1d302c --- /dev/null +++ b/node_modules/isarray/package.json @@ -0,0 +1,57 @@ +{ + "_from": "isarray@0.0.1", + "_id": "isarray@0.0.1", + "_inBundle": false, + "_integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "_location": "/isarray", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "isarray@0.0.1", + "name": "isarray", + "escapedName": "isarray", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_spec": "isarray@0.0.1", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Array#isArray for older browsers", + "devDependencies": { + "tap": "*" + }, + "homepage": "https://github.com/juliangruber/isarray", + "keywords": [ + "browser", + "isarray", + "array" + ], + "license": "MIT", + "main": "index.js", + "name": "isarray", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "0.0.1" +} diff --git a/node_modules/readable-stream/.npmignore b/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..e3d4e69 --- /dev/null +++ b/node_modules/readable-stream/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md new file mode 100644 index 0000000..e46b823 --- /dev/null +++ b/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png&months=6&height=3)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/node_modules/readable-stream/duplex.js b/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/readable-stream/float.patch b/node_modules/readable-stream/float.patch new file mode 100644 index 0000000..b984607 --- /dev/null +++ b/node_modules/readable-stream/float.patch @@ -0,0 +1,923 @@ +diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js +index c5a741c..a2e0d8e 100644 +--- a/lib/_stream_duplex.js ++++ b/lib/_stream_duplex.js +@@ -26,8 +26,8 @@ + + module.exports = Duplex; + var util = require('util'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('./_stream_readable'); ++var Writable = require('./_stream_writable'); + + util.inherits(Duplex, Readable); + +diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js +index a5e9864..330c247 100644 +--- a/lib/_stream_passthrough.js ++++ b/lib/_stream_passthrough.js +@@ -25,7 +25,7 @@ + + module.exports = PassThrough; + +-var Transform = require('_stream_transform'); ++var Transform = require('./_stream_transform'); + var util = require('util'); + util.inherits(PassThrough, Transform); + +diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js +index 0c3fe3e..90a8298 100644 +--- a/lib/_stream_readable.js ++++ b/lib/_stream_readable.js +@@ -23,10 +23,34 @@ module.exports = Readable; + Readable.ReadableState = ReadableState; + + var EE = require('events').EventEmitter; ++if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { ++ return emitter.listeners(type).length; ++}; ++ ++if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { ++ return setTimeout(fn, 0); ++}; ++if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { ++ return clearTimeout(i); ++}; ++ + var Stream = require('stream'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var StringDecoder; +-var debug = util.debuglog('stream'); ++var debug; ++if (util.debuglog) ++ debug = util.debuglog('stream'); ++else try { ++ debug = require('debuglog')('stream'); ++} catch (er) { ++ debug = function() {}; ++} + + util.inherits(Readable, Stream); + +@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) { + + + function onEofChunk(stream, state) { +- if (state.decoder && !state.ended) { ++ if (state.decoder && !state.ended && state.decoder.end) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); +diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js +index b1f9fcc..b0caf57 100644 +--- a/lib/_stream_transform.js ++++ b/lib/_stream_transform.js +@@ -64,8 +64,14 @@ + + module.exports = Transform; + +-var Duplex = require('_stream_duplex'); ++var Duplex = require('./_stream_duplex'); + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + util.inherits(Transform, Duplex); + + +diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js +index ba2e920..f49288b 100644 +--- a/lib/_stream_writable.js ++++ b/lib/_stream_writable.js +@@ -27,6 +27,12 @@ module.exports = Writable; + Writable.WritableState = WritableState; + + var util = require('util'); ++if (!util.isUndefined) { ++ var utilIs = require('core-util-is'); ++ for (var f in utilIs) { ++ util[f] = utilIs[f]; ++ } ++} + var Stream = require('stream'); + + util.inherits(Writable, Stream); +@@ -119,7 +125,7 @@ function WritableState(options, stream) { + function Writable(options) { + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. +- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) ++ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) + return new Writable(options); + + this._writableState = new WritableState(options, this); +diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js +index e3787e4..8cd2127 100644 +--- a/test/simple/test-stream-big-push.js ++++ b/test/simple/test-stream-big-push.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var str = 'asdfasdfasdfasdfasdf'; + + var r = new stream.Readable({ +diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js +index bb73777..d40efc7 100644 +--- a/test/simple/test-stream-end-paused.js ++++ b/test/simple/test-stream-end-paused.js +@@ -25,7 +25,7 @@ var gotEnd = false; + + // Make sure we don't miss the end event for paused 0-length streams + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var stream = new Readable(); + var calledRead = false; + stream._read = function() { +diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js +index b46ee90..0be8366 100644 +--- a/test/simple/test-stream-pipe-after-end.js ++++ b/test/simple/test-stream-pipe-after-end.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var util = require('util'); + + util.inherits(TestReadable, Readable); +diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js +deleted file mode 100644 +index f689358..0000000 +--- a/test/simple/test-stream-pipe-cleanup.js ++++ /dev/null +@@ -1,122 +0,0 @@ +-// Copyright Joyent, Inc. and other Node contributors. +-// +-// Permission is hereby granted, free of charge, to any person obtaining a +-// copy of this software and associated documentation files (the +-// "Software"), to deal in the Software without restriction, including +-// without limitation the rights to use, copy, modify, merge, publish, +-// distribute, sublicense, and/or sell copies of the Software, and to permit +-// persons to whom the Software is furnished to do so, subject to the +-// following conditions: +-// +-// The above copyright notice and this permission notice shall be included +-// in all copies or substantial portions of the Software. +-// +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +-// USE OR OTHER DEALINGS IN THE SOFTWARE. +- +-// This test asserts that Stream.prototype.pipe does not leave listeners +-// hanging on the source or dest. +- +-var common = require('../common'); +-var stream = require('stream'); +-var assert = require('assert'); +-var util = require('util'); +- +-function Writable() { +- this.writable = true; +- this.endCalls = 0; +- stream.Stream.call(this); +-} +-util.inherits(Writable, stream.Stream); +-Writable.prototype.end = function() { +- this.endCalls++; +-}; +- +-Writable.prototype.destroy = function() { +- this.endCalls++; +-}; +- +-function Readable() { +- this.readable = true; +- stream.Stream.call(this); +-} +-util.inherits(Readable, stream.Stream); +- +-function Duplex() { +- this.readable = true; +- Writable.call(this); +-} +-util.inherits(Duplex, Writable); +- +-var i = 0; +-var limit = 100; +- +-var w = new Writable(); +- +-var r; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('end'); +-} +-assert.equal(0, r.listeners('end').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-for (i = 0; i < limit; i++) { +- r = new Readable(); +- r.pipe(w); +- r.emit('close'); +-} +-assert.equal(0, r.listeners('close').length); +-assert.equal(limit, w.endCalls); +- +-w.endCalls = 0; +- +-r = new Readable(); +- +-for (i = 0; i < limit; i++) { +- w = new Writable(); +- r.pipe(w); +- w.emit('close'); +-} +-assert.equal(0, w.listeners('close').length); +- +-r = new Readable(); +-w = new Writable(); +-var d = new Duplex(); +-r.pipe(d); // pipeline A +-d.pipe(w); // pipeline B +-assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup +-assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-r.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 0); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup +-assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 1); // B.cleanup +- +-d.emit('end'); +-assert.equal(d.endCalls, 1); +-assert.equal(w.endCalls, 1); +-assert.equal(r.listeners('end').length, 0); +-assert.equal(r.listeners('close').length, 0); +-assert.equal(d.listeners('end').length, 0); +-assert.equal(d.listeners('close').length, 0); +-assert.equal(w.listeners('end').length, 0); +-assert.equal(w.listeners('close').length, 0); +diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js +index c5d724b..c7d6b7d 100644 +--- a/test/simple/test-stream-pipe-error-handling.js ++++ b/test/simple/test-stream-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Stream = require('stream').Stream; ++var Stream = require('../../').Stream; + + (function testErrorListenerCatches() { + var source = new Stream(); +diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js +index cb9d5fe..56f8d61 100644 +--- a/test/simple/test-stream-pipe-event.js ++++ b/test/simple/test-stream-pipe-event.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common'); +-var stream = require('stream'); ++var stream = require('../../'); + var assert = require('assert'); + var util = require('util'); + +diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js +index f2e6ec2..a5c9bf9 100644 +--- a/test/simple/test-stream-push-order.js ++++ b/test/simple/test-stream-push-order.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var assert = require('assert'); + + var s = new Readable({ +diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js +index 06f43dc..1701a9a 100644 +--- a/test/simple/test-stream-push-strings.js ++++ b/test/simple/test-stream-push-strings.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var util = require('util'); + + util.inherits(MyStream, Readable); +diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js +index ba6a577..a8e6f7b 100644 +--- a/test/simple/test-stream-readable-event.js ++++ b/test/simple/test-stream-readable-event.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + (function first() { + // First test, not reading when the readable is added. +diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js +index 2891ad6..11689ba 100644 +--- a/test/simple/test-stream-readable-flow-recursion.js ++++ b/test/simple/test-stream-readable-flow-recursion.js +@@ -27,7 +27,7 @@ var assert = require('assert'); + // more data continuously, but without triggering a nextTick + // warning or RangeError. + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + // throw an error if we trigger a nextTick warning. + process.throwDeprecation = true; +diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js +index 0c96476..7827538 100644 +--- a/test/simple/test-stream-unshift-empty-chunk.js ++++ b/test/simple/test-stream-unshift-empty-chunk.js +@@ -24,7 +24,7 @@ var assert = require('assert'); + + // This test verifies that stream.unshift(Buffer(0)) or + // stream.unshift('') does not set state.reading=false. +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + var r = new Readable(); + var nChunks = 10; +diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js +index 83fd9fa..17c18aa 100644 +--- a/test/simple/test-stream-unshift-read-race.js ++++ b/test/simple/test-stream-unshift-read-race.js +@@ -29,7 +29,7 @@ var assert = require('assert'); + // 3. push() after the EOF signaling null is an error. + // 4. _read() is not called after pushing the EOF null chunk. + +-var stream = require('stream'); ++var stream = require('../../'); + var hwm = 10; + var r = stream.Readable({ highWaterMark: hwm }); + var chunks = 10; +@@ -51,7 +51,14 @@ r._read = function(n) { + + function push(fast) { + assert(!pushedNull, 'push() after null push'); +- var c = pos >= data.length ? null : data.slice(pos, pos + n); ++ var c; ++ if (pos >= data.length) ++ c = null; ++ else { ++ if (n + pos > data.length) ++ n = data.length - pos; ++ c = data.slice(pos, pos + n); ++ } + pushedNull = c === null; + if (fast) { + pos += n; +diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js +index 5b49e6e..b5321f3 100644 +--- a/test/simple/test-stream-writev.js ++++ b/test/simple/test-stream-writev.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + + var queue = []; + for (var decode = 0; decode < 2; decode++) { +diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js +index 3814bf0..248c1be 100644 +--- a/test/simple/test-stream2-basic.js ++++ b/test/simple/test-stream2-basic.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js +index 6cdd4e9..f0fa84b 100644 +--- a/test/simple/test-stream2-compatibility.js ++++ b/test/simple/test-stream2-compatibility.js +@@ -21,7 +21,7 @@ + + + var common = require('../common.js'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js +index 39b274f..006a19b 100644 +--- a/test/simple/test-stream2-finish-pipe.js ++++ b/test/simple/test-stream2-finish-pipe.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Buffer = require('buffer').Buffer; + + var r = new stream.Readable(); +diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js +deleted file mode 100644 +index e162406..0000000 +--- a/test/simple/test-stream2-fs.js ++++ /dev/null +@@ -1,72 +0,0 @@ +-// Copyright Joyent, Inc. and other Node contributors. +-// +-// Permission is hereby granted, free of charge, to any person obtaining a +-// copy of this software and associated documentation files (the +-// "Software"), to deal in the Software without restriction, including +-// without limitation the rights to use, copy, modify, merge, publish, +-// distribute, sublicense, and/or sell copies of the Software, and to permit +-// persons to whom the Software is furnished to do so, subject to the +-// following conditions: +-// +-// The above copyright notice and this permission notice shall be included +-// in all copies or substantial portions of the Software. +-// +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +-// USE OR OTHER DEALINGS IN THE SOFTWARE. +- +- +-var common = require('../common.js'); +-var R = require('_stream_readable'); +-var assert = require('assert'); +- +-var fs = require('fs'); +-var FSReadable = fs.ReadStream; +- +-var path = require('path'); +-var file = path.resolve(common.fixturesDir, 'x1024.txt'); +- +-var size = fs.statSync(file).size; +- +-var expectLengths = [1024]; +- +-var util = require('util'); +-var Stream = require('stream'); +- +-util.inherits(TestWriter, Stream); +- +-function TestWriter() { +- Stream.apply(this); +- this.buffer = []; +- this.length = 0; +-} +- +-TestWriter.prototype.write = function(c) { +- this.buffer.push(c.toString()); +- this.length += c.length; +- return true; +-}; +- +-TestWriter.prototype.end = function(c) { +- if (c) this.buffer.push(c.toString()); +- this.emit('results', this.buffer); +-} +- +-var r = new FSReadable(file); +-var w = new TestWriter(); +- +-w.on('results', function(res) { +- console.error(res, w.length); +- assert.equal(w.length, size); +- var l = 0; +- assert.deepEqual(res.map(function (c) { +- return c.length; +- }), expectLengths); +- console.log('ok'); +-}); +- +-r.pipe(w); +diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js +deleted file mode 100644 +index 15cffc2..0000000 +--- a/test/simple/test-stream2-httpclient-response-end.js ++++ /dev/null +@@ -1,52 +0,0 @@ +-// Copyright Joyent, Inc. and other Node contributors. +-// +-// Permission is hereby granted, free of charge, to any person obtaining a +-// copy of this software and associated documentation files (the +-// "Software"), to deal in the Software without restriction, including +-// without limitation the rights to use, copy, modify, merge, publish, +-// distribute, sublicense, and/or sell copies of the Software, and to permit +-// persons to whom the Software is furnished to do so, subject to the +-// following conditions: +-// +-// The above copyright notice and this permission notice shall be included +-// in all copies or substantial portions of the Software. +-// +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +-// USE OR OTHER DEALINGS IN THE SOFTWARE. +- +-var common = require('../common.js'); +-var assert = require('assert'); +-var http = require('http'); +-var msg = 'Hello'; +-var readable_event = false; +-var end_event = false; +-var server = http.createServer(function(req, res) { +- res.writeHead(200, {'Content-Type': 'text/plain'}); +- res.end(msg); +-}).listen(common.PORT, function() { +- http.get({port: common.PORT}, function(res) { +- var data = ''; +- res.on('readable', function() { +- console.log('readable event'); +- readable_event = true; +- data += res.read(); +- }); +- res.on('end', function() { +- console.log('end event'); +- end_event = true; +- assert.strictEqual(msg, data); +- server.close(); +- }); +- }); +-}); +- +-process.on('exit', function() { +- assert(readable_event); +- assert(end_event); +-}); +- +diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js +index 2fbfbca..667985b 100644 +--- a/test/simple/test-stream2-large-read-stall.js ++++ b/test/simple/test-stream2-large-read-stall.js +@@ -30,7 +30,7 @@ var PUSHSIZE = 20; + var PUSHCOUNT = 1000; + var HWM = 50; + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable({ + highWaterMark: HWM + }); +@@ -39,23 +39,23 @@ var rs = r._readableState; + r._read = push; + + r.on('readable', function() { +- console.error('>> readable'); ++ //console.error('>> readable'); + do { +- console.error(' > read(%d)', READSIZE); ++ //console.error(' > read(%d)', READSIZE); + var ret = r.read(READSIZE); +- console.error(' < %j (%d remain)', ret && ret.length, rs.length); ++ //console.error(' < %j (%d remain)', ret && ret.length, rs.length); + } while (ret && ret.length === READSIZE); + +- console.error('<< after read()', +- ret && ret.length, +- rs.needReadable, +- rs.length); ++ //console.error('<< after read()', ++ // ret && ret.length, ++ // rs.needReadable, ++ // rs.length); + }); + + var endEmitted = false; + r.on('end', function() { + endEmitted = true; +- console.error('end'); ++ //console.error('end'); + }); + + var pushes = 0; +@@ -64,11 +64,11 @@ function push() { + return; + + if (pushes++ === PUSHCOUNT) { +- console.error(' push(EOF)'); ++ //console.error(' push(EOF)'); + return r.push(null); + } + +- console.error(' push #%d', pushes); ++ //console.error(' push #%d', pushes); + if (r.push(new Buffer(PUSHSIZE))) + setTimeout(push); + } +diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js +index 3e6931d..ff47d89 100644 +--- a/test/simple/test-stream2-objects.js ++++ b/test/simple/test-stream2-objects.js +@@ -21,8 +21,8 @@ + + + var common = require('../common.js'); +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var assert = require('assert'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js +index cf7531c..e3f3e4e 100644 +--- a/test/simple/test-stream2-pipe-error-handling.js ++++ b/test/simple/test-stream2-pipe-error-handling.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + (function testErrorListenerCatches() { + var count = 1000; +diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js +index 5e8e3cb..53b2616 100755 +--- a/test/simple/test-stream2-pipe-error-once-listener.js ++++ b/test/simple/test-stream2-pipe-error-once-listener.js +@@ -24,7 +24,7 @@ var common = require('../common.js'); + var assert = require('assert'); + + var util = require('util'); +-var stream = require('stream'); ++var stream = require('../../'); + + + var Read = function() { +diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js +index b63edc3..eb2b0e9 100644 +--- a/test/simple/test-stream2-push.js ++++ b/test/simple/test-stream2-push.js +@@ -20,7 +20,7 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + var assert = require('assert'); +diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js +index e8a7305..9740a47 100644 +--- a/test/simple/test-stream2-read-sync-stack.js ++++ b/test/simple/test-stream2-read-sync-stack.js +@@ -21,7 +21,7 @@ + + var common = require('../common'); + var assert = require('assert'); +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + var r = new Readable(); + var N = 256 * 1024; + +diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +index cd30178..4b1659d 100644 +--- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js ++++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js +@@ -22,10 +22,9 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('stream').Readable; ++var Readable = require('../../').Readable; + + test1(); +-test2(); + + function test1() { + var r = new Readable(); +@@ -88,31 +87,3 @@ function test1() { + console.log('ok'); + }); + } +- +-function test2() { +- var r = new Readable({ encoding: 'base64' }); +- var reads = 5; +- r._read = function(n) { +- if (!reads--) +- return r.push(null); // EOF +- else +- return r.push(new Buffer('x')); +- }; +- +- var results = []; +- function flow() { +- var chunk; +- while (null !== (chunk = r.read())) +- results.push(chunk + ''); +- } +- r.on('readable', flow); +- r.on('end', function() { +- results.push('EOF'); +- }); +- flow(); +- +- process.on('exit', function() { +- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); +- console.log('ok'); +- }); +-} +diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js +index 7c96ffe..04a96f5 100644 +--- a/test/simple/test-stream2-readable-from-list.js ++++ b/test/simple/test-stream2-readable-from-list.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var fromList = require('_stream_readable')._fromList; ++var fromList = require('../../lib/_stream_readable')._fromList; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js +index 675da8e..51fd3d5 100644 +--- a/test/simple/test-stream2-readable-legacy-drain.js ++++ b/test/simple/test-stream2-readable-legacy-drain.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Stream = require('stream'); ++var Stream = require('../../'); + var Readable = Stream.Readable; + + var r = new Readable(); +diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js +index 7314ae7..c971898 100644 +--- a/test/simple/test-stream2-readable-non-empty-end.js ++++ b/test/simple/test-stream2-readable-non-empty-end.js +@@ -21,7 +21,7 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + + var len = 0; + var chunks = new Array(10); +diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js +index 2e5cf25..fd8a3dc 100644 +--- a/test/simple/test-stream2-readable-wrap-empty.js ++++ b/test/simple/test-stream2-readable-wrap-empty.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); ++var Readable = require('../../lib/_stream_readable'); + var EE = require('events').EventEmitter; + + var oldStream = new EE(); +diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js +index 90eea01..6b177f7 100644 +--- a/test/simple/test-stream2-readable-wrap.js ++++ b/test/simple/test-stream2-readable-wrap.js +@@ -22,8 +22,8 @@ + var common = require('../common'); + var assert = require('assert'); + +-var Readable = require('_stream_readable'); +-var Writable = require('_stream_writable'); ++var Readable = require('../../lib/_stream_readable'); ++var Writable = require('../../lib/_stream_writable'); + var EE = require('events').EventEmitter; + + var testRuns = 0, completedRuns = 0; +diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js +index 5d2c32a..685531b 100644 +--- a/test/simple/test-stream2-set-encoding.js ++++ b/test/simple/test-stream2-set-encoding.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var R = require('_stream_readable'); ++var R = require('../../lib/_stream_readable'); + var util = require('util'); + + // tiny node-tap lookalike. +diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js +index 9c9ddd8..a0cacc6 100644 +--- a/test/simple/test-stream2-transform.js ++++ b/test/simple/test-stream2-transform.js +@@ -21,8 +21,8 @@ + + var assert = require('assert'); + var common = require('../common.js'); +-var PassThrough = require('_stream_passthrough'); +-var Transform = require('_stream_transform'); ++var PassThrough = require('../../').PassThrough; ++var Transform = require('../../').Transform; + + // tiny node-tap lookalike. + var tests = []; +diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js +index d66dc3c..365b327 100644 +--- a/test/simple/test-stream2-unpipe-drain.js ++++ b/test/simple/test-stream2-unpipe-drain.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + var crypto = require('crypto'); + + var util = require('util'); +diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js +index 99f8746..17c92ae 100644 +--- a/test/simple/test-stream2-unpipe-leak.js ++++ b/test/simple/test-stream2-unpipe-leak.js +@@ -22,7 +22,7 @@ + + var common = require('../common.js'); + var assert = require('assert'); +-var stream = require('stream'); ++var stream = require('../../'); + + var chunk = new Buffer('hallo'); + +diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js +index 704100c..209c3a6 100644 +--- a/test/simple/test-stream2-writable.js ++++ b/test/simple/test-stream2-writable.js +@@ -20,8 +20,8 @@ + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var common = require('../common.js'); +-var W = require('_stream_writable'); +-var D = require('_stream_duplex'); ++var W = require('../../').Writable; ++var D = require('../../').Duplex; + var assert = require('assert'); + + var util = require('util'); +diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js +index b91bde3..2f72c15 100644 +--- a/test/simple/test-stream3-pause-then-read.js ++++ b/test/simple/test-stream3-pause-then-read.js +@@ -22,7 +22,7 @@ + var common = require('../common'); + var assert = require('assert'); + +-var stream = require('stream'); ++var stream = require('../../'); + var Readable = stream.Readable; + var Writable = stream.Writable; + diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json new file mode 100644 index 0000000..048bab6 --- /dev/null +++ b/node_modules/readable-stream/package.json @@ -0,0 +1,65 @@ +{ + "_from": "readable-stream@1.x >=1.1.9", + "_id": "readable-stream@1.1.14", + "_inBundle": false, + "_integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "_location": "/readable-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "readable-stream@1.x >=1.1.9", + "name": "readable-stream", + "escapedName": "readable-stream", + "rawSpec": "1.x >=1.1.9", + "saveSpec": null, + "fetchSpec": "1.x >=1.1.9" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "_shasum": "7cf4c54ef648e3813084c636dd2079e166c081d9", + "_spec": "readable-stream@1.x >=1.1.9", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "browser": { + "util": false + }, + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "bundleDependencies": false, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + }, + "deprecated": false, + "description": "Streams3, a user-land copy of the stream library from Node.js v0.11.x", + "devDependencies": { + "tap": "~0.2.6" + }, + "homepage": "https://github.com/isaacs/readable-stream#readme", + "keywords": [ + "readable", + "stream", + "pipe" + ], + "license": "MIT", + "main": "readable.js", + "name": "readable-stream", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "version": "1.1.14" +} diff --git a/node_modules/readable-stream/passthrough.js b/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..2a8b5c6 --- /dev/null +++ b/node_modules/readable-stream/readable.js @@ -0,0 +1,10 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = require('stream'); +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +if (!process.browser && process.env.READABLE_STREAM === 'disable') { + module.exports = require('stream'); +} diff --git a/node_modules/readable-stream/transform.js b/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/readable-stream/writable.js b/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/safe-buffer/.travis.yml b/node_modules/safe-buffer/.travis.yml new file mode 100644 index 0000000..7b20f28 --- /dev/null +++ b/node_modules/safe-buffer/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 'node' + - '5' + - '4' + - '0.12' + - '0.10' diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..e9a81af --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..22438da --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..8d9d93d --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,62 @@ +{ + "_from": "safe-buffer@^5.0.1", + "_id": "safe-buffer@5.1.1", + "_inBundle": false, + "_integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@^5.0.1", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "^5.0.1", + "saveSpec": null, + "fetchSpec": "^5.0.1" + }, + "_requiredBy": [ + "/amqplib" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "_shasum": "893312af69b2123def71f57889001671eeb2c853", + "_spec": "safe-buffer@^5.0.1", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0", + "zuul": "^3.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "5.1.1" +} diff --git a/node_modules/safe-buffer/test.js b/node_modules/safe-buffer/test.js new file mode 100644 index 0000000..4925059 --- /dev/null +++ b/node_modules/safe-buffer/test.js @@ -0,0 +1,101 @@ +/* eslint-disable node/no-deprecated-api */ + +var test = require('tape') +var SafeBuffer = require('./').Buffer + +test('new SafeBuffer(value) works just like Buffer', function (t) { + t.deepEqual(new SafeBuffer('hey'), new Buffer('hey')) + t.deepEqual(new SafeBuffer('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(new SafeBuffer('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(new SafeBuffer([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(new SafeBuffer(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.equal(typeof SafeBuffer.isBuffer, 'function') + t.equal(SafeBuffer.isBuffer(new SafeBuffer('hey')), true) + t.equal(Buffer.isBuffer(new SafeBuffer('hey')), true) + t.notOk(SafeBuffer.isBuffer({})) + + t.end() +}) + +test('SafeBuffer.from(value) converts to a Buffer', function (t) { + t.deepEqual(SafeBuffer.from('hey'), new Buffer('hey')) + t.deepEqual(SafeBuffer.from('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(SafeBuffer.from('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(SafeBuffer.from([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(SafeBuffer.from(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.end() +}) + +test('SafeBuffer.alloc(number) returns zeroed-out memory', function (t) { + for (var i = 0; i < 10; i++) { + var expected1 = new Buffer(1000) + expected1.fill(0) + t.deepEqual(SafeBuffer.alloc(1000), expected1) + + var expected2 = new Buffer(1000 * 1000) + expected2.fill(0) + t.deepEqual(SafeBuffer.alloc(1000 * 1000), expected2) + } + t.end() +}) + +test('SafeBuffer.allocUnsafe(number)', function (t) { + var buf = SafeBuffer.allocUnsafe(100) // unitialized memory + t.equal(buf.length, 100) + t.equal(SafeBuffer.isBuffer(buf), true) + t.equal(Buffer.isBuffer(buf), true) + t.end() +}) + +test('SafeBuffer.from() throws with number types', function (t) { + t.plan(5) + t.throws(function () { + SafeBuffer.from(0) + }) + t.throws(function () { + SafeBuffer.from(-1) + }) + t.throws(function () { + SafeBuffer.from(NaN) + }) + t.throws(function () { + SafeBuffer.from(Infinity) + }) + t.throws(function () { + SafeBuffer.from(99) + }) +}) + +test('SafeBuffer.allocUnsafe() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.allocUnsafe('hey') + }) + t.throws(function () { + SafeBuffer.allocUnsafe('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.allocUnsafe([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.allocUnsafe({}) + }) +}) + +test('SafeBuffer.alloc() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.alloc('hey') + }) + t.throws(function () { + SafeBuffer.alloc('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.alloc([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.alloc({}) + }) +}) diff --git a/node_modules/string_decoder/.npmignore b/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/string_decoder/index.js b/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var 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 true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + 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; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +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; +} diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000..b923280 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,53 @@ +{ + "_from": "string_decoder@~0.10.x", + "_id": "string_decoder@0.10.31", + "_inBundle": false, + "_integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "_location": "/string_decoder", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string_decoder@~0.10.x", + "name": "string_decoder", + "escapedName": "string_decoder", + "rawSpec": "~0.10.x", + "saveSpec": null, + "fetchSpec": "~0.10.x" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_spec": "string_decoder@~0.10.x", + "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "The string_decoder module from Node core", + "devDependencies": { + "tap": "~0.4.8" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "main": "index.js", + "name": "string_decoder", + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "version": "0.10.31" +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c9e45b6 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,72 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "amqplib": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.5.2.tgz", + "integrity": "sha512-l9mCs6LbydtHqRniRwYkKdqxVa6XMz3Vw1fh+2gJaaVgTM6Jk3o8RccAKWKtlhT1US5sWrFh+KKxsVUALURSIA==", + "requires": { + "bitsyntax": "0.0.4", + "bluebird": "3.5.1", + "buffer-more-ints": "0.0.2", + "readable-stream": "1.1.14", + "safe-buffer": "5.1.1" + } + }, + "bitsyntax": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.0.4.tgz", + "integrity": "sha1-6xDMb4K4xJDj6FaY8H6D1G4MuoI=", + "requires": { + "buffer-more-ints": "0.0.2" + } + }, + "bluebird": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", + "integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==" + }, + "buffer-more-ints": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-0.0.2.tgz", + "integrity": "sha1-JrOIXRD6E9t/wBquOquHAZngEkw=" + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=" + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" + }, + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=" + }, + "readable-stream": { + "version": "1.1.14", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", + "requires": { + "core-util-is": "1.0.2", + "inherits": "2.0.3", + "isarray": "0.0.1", + "string_decoder": "0.10.31" + } + }, + "safe-buffer": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==" + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=" + } + } +} From 9dd4c900aed4edc704e35b1cef18b91e5e3fdf2c Mon Sep 17 00:00:00 2001 From: Wilson Mar Date: Tue, 23 Jan 2018 15:37:10 -0500 Subject: [PATCH 98/98] add rabbitmq calls --- node_modules/amqplib/CHANGELOG.md | 234 - node_modules/amqplib/LICENSE | 6 - node_modules/amqplib/LICENSE-MIT | 21 - node_modules/amqplib/Makefile | 46 - node_modules/amqplib/README.md | 157 - node_modules/amqplib/callback_api.js | 22 - node_modules/amqplib/channel_api.js | 16 - node_modules/amqplib/examples/headers.js | 42 - .../amqplib/examples/receive_generator.js | 39 - .../amqplib/examples/send_generators.js | 42 - node_modules/amqplib/examples/ssl.js | 64 - .../amqplib/examples/tutorials/README.md | 93 - .../tutorials/callback_api/emit_log.js | 28 - .../tutorials/callback_api/emit_log_direct.js | 30 - .../tutorials/callback_api/emit_log_topic.js | 27 - .../tutorials/callback_api/new_task.js | 27 - .../tutorials/callback_api/receive.js | 30 - .../tutorials/callback_api/receive_logs.js | 36 - .../callback_api/receive_logs_direct.js | 56 - .../callback_api/receive_logs_topic.js | 55 - .../tutorials/callback_api/rpc_client.js | 49 - .../tutorials/callback_api/rpc_server.js | 45 - .../examples/tutorials/callback_api/send.js | 29 - .../examples/tutorials/callback_api/worker.js | 35 - .../amqplib/examples/tutorials/emit_log.js | 19 - .../examples/tutorials/emit_log_direct.js | 20 - .../examples/tutorials/emit_log_topic.js | 19 - .../amqplib/examples/tutorials/new_task.js | 18 - .../amqplib/examples/tutorials/package.json | 16 - .../amqplib/examples/tutorials/receive.js | 21 - .../examples/tutorials/receive_logs.js | 28 - .../examples/tutorials/receive_logs_direct.js | 45 - .../examples/tutorials/receive_logs_topic.js | 44 - .../amqplib/examples/tutorials/rpc_client.js | 53 - .../amqplib/examples/tutorials/rpc_server.js | 39 - .../amqplib/examples/tutorials/send.js | 23 - .../amqplib/examples/tutorials/worker.js | 28 - .../amqplib/examples/waitForConfirms.js | 22 - node_modules/amqplib/package.json | 70 - node_modules/amqplib/test/bitset.js | 68 - node_modules/amqplib/test/callback_api.js | 313 - node_modules/amqplib/test/channel.js | 612 -- node_modules/amqplib/test/channel_api.js | 584 -- node_modules/amqplib/test/codec.js | 238 - node_modules/amqplib/test/connect.js | 127 - node_modules/amqplib/test/connection.js | 391 -- node_modules/amqplib/test/data.js | 255 - node_modules/amqplib/test/frame.js | 199 - node_modules/amqplib/test/mux.js | 166 - node_modules/amqplib/test/util.js | 220 - node_modules/bitsyntax/.npmignore | 3 - node_modules/bitsyntax/.travis.yml | 7 - node_modules/bitsyntax/Makefile | 15 - node_modules/bitsyntax/README.md | 306 - node_modules/bitsyntax/index.js | 10 - node_modules/bitsyntax/package.json | 57 - node_modules/bitsyntax/test/consing.js | 45 - node_modules/bitsyntax/test/matching.js | 187 - node_modules/bluebird/LICENSE | 21 - node_modules/bluebird/README.md | 52 - node_modules/bluebird/changelog.md | 1 - .../bluebird/js/browser/bluebird.core.js | 3781 ----------- .../bluebird/js/browser/bluebird.core.min.js | 31 - node_modules/bluebird/js/browser/bluebird.js | 5623 ----------------- .../bluebird/js/browser/bluebird.min.js | 31 - node_modules/bluebird/js/release/any.js | 21 - node_modules/bluebird/js/release/assert.js | 55 - node_modules/bluebird/js/release/async.js | 161 - node_modules/bluebird/js/release/bind.js | 67 - node_modules/bluebird/js/release/bluebird.js | 11 - node_modules/bluebird/js/release/call_get.js | 123 - node_modules/bluebird/js/release/cancel.js | 129 - .../bluebird/js/release/catch_filter.js | 42 - node_modules/bluebird/js/release/context.js | 69 - .../bluebird/js/release/debuggability.js | 919 --- .../bluebird/js/release/direct_resolve.js | 46 - node_modules/bluebird/js/release/each.js | 30 - node_modules/bluebird/js/release/errors.js | 116 - node_modules/bluebird/js/release/es5.js | 80 - node_modules/bluebird/js/release/filter.js | 12 - node_modules/bluebird/js/release/finally.js | 146 - .../bluebird/js/release/generators.js | 223 - node_modules/bluebird/js/release/join.js | 168 - node_modules/bluebird/js/release/map.js | 168 - node_modules/bluebird/js/release/method.js | 55 - node_modules/bluebird/js/release/nodeback.js | 51 - node_modules/bluebird/js/release/nodeify.js | 58 - node_modules/bluebird/js/release/promise.js | 775 --- .../bluebird/js/release/promise_array.js | 185 - node_modules/bluebird/js/release/promisify.js | 314 - node_modules/bluebird/js/release/props.js | 118 - node_modules/bluebird/js/release/queue.js | 73 - node_modules/bluebird/js/release/race.js | 49 - node_modules/bluebird/js/release/reduce.js | 172 - node_modules/bluebird/js/release/schedule.js | 61 - node_modules/bluebird/js/release/settle.js | 43 - node_modules/bluebird/js/release/some.js | 148 - .../js/release/synchronous_inspection.js | 103 - node_modules/bluebird/js/release/thenables.js | 86 - node_modules/bluebird/js/release/timers.js | 93 - node_modules/bluebird/js/release/using.js | 226 - node_modules/bluebird/js/release/util.js | 380 -- node_modules/bluebird/package.json | 101 - node_modules/buffer-more-ints/.npmignore | 2 - node_modules/buffer-more-ints/LICENSE | 19 - node_modules/buffer-more-ints/README.md | 68 - .../buffer-more-ints-tests.js | 207 - .../buffer-more-ints/buffer-more-ints.js | 472 -- node_modules/buffer-more-ints/package.json | 50 - node_modules/buffer-more-ints/polyfill.js | 71 - node_modules/core-util-is/LICENSE | 19 - node_modules/core-util-is/README.md | 3 - node_modules/core-util-is/float.patch | 604 -- node_modules/core-util-is/package.json | 62 - node_modules/core-util-is/test.js | 68 - node_modules/inherits/LICENSE | 16 - node_modules/inherits/README.md | 42 - node_modules/inherits/inherits.js | 7 - node_modules/inherits/inherits_browser.js | 23 - node_modules/inherits/package.json | 61 - node_modules/isarray/README.md | 54 - node_modules/isarray/build/build.js | 209 - node_modules/isarray/component.json | 19 - node_modules/isarray/index.js | 3 - node_modules/isarray/package.json | 57 - node_modules/readable-stream/.npmignore | 5 - node_modules/readable-stream/LICENSE | 18 - node_modules/readable-stream/README.md | 15 - node_modules/readable-stream/duplex.js | 1 - node_modules/readable-stream/float.patch | 923 --- node_modules/readable-stream/package.json | 65 - node_modules/readable-stream/passthrough.js | 1 - node_modules/readable-stream/readable.js | 10 - node_modules/readable-stream/transform.js | 1 - node_modules/readable-stream/writable.js | 1 - node_modules/safe-buffer/.travis.yml | 7 - node_modules/safe-buffer/LICENSE | 21 - node_modules/safe-buffer/README.md | 584 -- node_modules/safe-buffer/index.js | 62 - node_modules/safe-buffer/package.json | 62 - node_modules/safe-buffer/test.js | 101 - node_modules/string_decoder/.npmignore | 2 - node_modules/string_decoder/LICENSE | 20 - node_modules/string_decoder/README.md | 7 - node_modules/string_decoder/index.js | 221 - node_modules/string_decoder/package.json | 53 - 146 files changed, 25030 deletions(-) delete mode 100644 node_modules/amqplib/CHANGELOG.md delete mode 100644 node_modules/amqplib/LICENSE delete mode 100644 node_modules/amqplib/LICENSE-MIT delete mode 100644 node_modules/amqplib/Makefile delete mode 100644 node_modules/amqplib/README.md delete mode 100644 node_modules/amqplib/callback_api.js delete mode 100644 node_modules/amqplib/channel_api.js delete mode 100755 node_modules/amqplib/examples/headers.js delete mode 100644 node_modules/amqplib/examples/receive_generator.js delete mode 100755 node_modules/amqplib/examples/send_generators.js delete mode 100644 node_modules/amqplib/examples/ssl.js delete mode 100644 node_modules/amqplib/examples/tutorials/README.md delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/new_task.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/send.js delete mode 100755 node_modules/amqplib/examples/tutorials/callback_api/worker.js delete mode 100755 node_modules/amqplib/examples/tutorials/emit_log.js delete mode 100755 node_modules/amqplib/examples/tutorials/emit_log_direct.js delete mode 100755 node_modules/amqplib/examples/tutorials/emit_log_topic.js delete mode 100755 node_modules/amqplib/examples/tutorials/new_task.js delete mode 100644 node_modules/amqplib/examples/tutorials/package.json delete mode 100755 node_modules/amqplib/examples/tutorials/receive.js delete mode 100755 node_modules/amqplib/examples/tutorials/receive_logs.js delete mode 100755 node_modules/amqplib/examples/tutorials/receive_logs_direct.js delete mode 100755 node_modules/amqplib/examples/tutorials/receive_logs_topic.js delete mode 100755 node_modules/amqplib/examples/tutorials/rpc_client.js delete mode 100755 node_modules/amqplib/examples/tutorials/rpc_server.js delete mode 100755 node_modules/amqplib/examples/tutorials/send.js delete mode 100755 node_modules/amqplib/examples/tutorials/worker.js delete mode 100644 node_modules/amqplib/examples/waitForConfirms.js delete mode 100644 node_modules/amqplib/package.json delete mode 100644 node_modules/amqplib/test/bitset.js delete mode 100644 node_modules/amqplib/test/callback_api.js delete mode 100644 node_modules/amqplib/test/channel.js delete mode 100644 node_modules/amqplib/test/channel_api.js delete mode 100644 node_modules/amqplib/test/codec.js delete mode 100644 node_modules/amqplib/test/connect.js delete mode 100644 node_modules/amqplib/test/connection.js delete mode 100644 node_modules/amqplib/test/data.js delete mode 100644 node_modules/amqplib/test/frame.js delete mode 100644 node_modules/amqplib/test/mux.js delete mode 100644 node_modules/amqplib/test/util.js delete mode 100644 node_modules/bitsyntax/.npmignore delete mode 100644 node_modules/bitsyntax/.travis.yml delete mode 100644 node_modules/bitsyntax/Makefile delete mode 100644 node_modules/bitsyntax/README.md delete mode 100644 node_modules/bitsyntax/index.js delete mode 100644 node_modules/bitsyntax/package.json delete mode 100644 node_modules/bitsyntax/test/consing.js delete mode 100644 node_modules/bitsyntax/test/matching.js delete mode 100644 node_modules/bluebird/LICENSE delete mode 100644 node_modules/bluebird/README.md delete mode 100644 node_modules/bluebird/changelog.md delete mode 100644 node_modules/bluebird/js/browser/bluebird.core.js delete mode 100644 node_modules/bluebird/js/browser/bluebird.core.min.js delete mode 100644 node_modules/bluebird/js/browser/bluebird.js delete mode 100644 node_modules/bluebird/js/browser/bluebird.min.js delete mode 100644 node_modules/bluebird/js/release/any.js delete mode 100644 node_modules/bluebird/js/release/assert.js delete mode 100644 node_modules/bluebird/js/release/async.js delete mode 100644 node_modules/bluebird/js/release/bind.js delete mode 100644 node_modules/bluebird/js/release/bluebird.js delete mode 100644 node_modules/bluebird/js/release/call_get.js delete mode 100644 node_modules/bluebird/js/release/cancel.js delete mode 100644 node_modules/bluebird/js/release/catch_filter.js delete mode 100644 node_modules/bluebird/js/release/context.js delete mode 100644 node_modules/bluebird/js/release/debuggability.js delete mode 100644 node_modules/bluebird/js/release/direct_resolve.js delete mode 100644 node_modules/bluebird/js/release/each.js delete mode 100644 node_modules/bluebird/js/release/errors.js delete mode 100644 node_modules/bluebird/js/release/es5.js delete mode 100644 node_modules/bluebird/js/release/filter.js delete mode 100644 node_modules/bluebird/js/release/finally.js delete mode 100644 node_modules/bluebird/js/release/generators.js delete mode 100644 node_modules/bluebird/js/release/join.js delete mode 100644 node_modules/bluebird/js/release/map.js delete mode 100644 node_modules/bluebird/js/release/method.js delete mode 100644 node_modules/bluebird/js/release/nodeback.js delete mode 100644 node_modules/bluebird/js/release/nodeify.js delete mode 100644 node_modules/bluebird/js/release/promise.js delete mode 100644 node_modules/bluebird/js/release/promise_array.js delete mode 100644 node_modules/bluebird/js/release/promisify.js delete mode 100644 node_modules/bluebird/js/release/props.js delete mode 100644 node_modules/bluebird/js/release/queue.js delete mode 100644 node_modules/bluebird/js/release/race.js delete mode 100644 node_modules/bluebird/js/release/reduce.js delete mode 100644 node_modules/bluebird/js/release/schedule.js delete mode 100644 node_modules/bluebird/js/release/settle.js delete mode 100644 node_modules/bluebird/js/release/some.js delete mode 100644 node_modules/bluebird/js/release/synchronous_inspection.js delete mode 100644 node_modules/bluebird/js/release/thenables.js delete mode 100644 node_modules/bluebird/js/release/timers.js delete mode 100644 node_modules/bluebird/js/release/using.js delete mode 100644 node_modules/bluebird/js/release/util.js delete mode 100644 node_modules/bluebird/package.json delete mode 100644 node_modules/buffer-more-ints/.npmignore delete mode 100644 node_modules/buffer-more-ints/LICENSE delete mode 100644 node_modules/buffer-more-ints/README.md delete mode 100644 node_modules/buffer-more-ints/buffer-more-ints-tests.js delete mode 100644 node_modules/buffer-more-ints/buffer-more-ints.js delete mode 100644 node_modules/buffer-more-ints/package.json delete mode 100644 node_modules/buffer-more-ints/polyfill.js delete mode 100644 node_modules/core-util-is/LICENSE delete mode 100644 node_modules/core-util-is/README.md delete mode 100644 node_modules/core-util-is/float.patch delete mode 100644 node_modules/core-util-is/package.json delete mode 100644 node_modules/core-util-is/test.js delete mode 100644 node_modules/inherits/LICENSE delete mode 100644 node_modules/inherits/README.md delete mode 100644 node_modules/inherits/inherits.js delete mode 100644 node_modules/inherits/inherits_browser.js delete mode 100644 node_modules/inherits/package.json delete mode 100644 node_modules/isarray/README.md delete mode 100644 node_modules/isarray/build/build.js delete mode 100644 node_modules/isarray/component.json delete mode 100644 node_modules/isarray/index.js delete mode 100644 node_modules/isarray/package.json delete mode 100644 node_modules/readable-stream/.npmignore delete mode 100644 node_modules/readable-stream/LICENSE delete mode 100644 node_modules/readable-stream/README.md delete mode 100644 node_modules/readable-stream/duplex.js delete mode 100644 node_modules/readable-stream/float.patch delete mode 100644 node_modules/readable-stream/package.json delete mode 100644 node_modules/readable-stream/passthrough.js delete mode 100644 node_modules/readable-stream/readable.js delete mode 100644 node_modules/readable-stream/transform.js delete mode 100644 node_modules/readable-stream/writable.js delete mode 100644 node_modules/safe-buffer/.travis.yml delete mode 100644 node_modules/safe-buffer/LICENSE delete mode 100644 node_modules/safe-buffer/README.md delete mode 100644 node_modules/safe-buffer/index.js delete mode 100644 node_modules/safe-buffer/package.json delete mode 100644 node_modules/safe-buffer/test.js delete mode 100644 node_modules/string_decoder/.npmignore delete mode 100644 node_modules/string_decoder/LICENSE delete mode 100644 node_modules/string_decoder/README.md delete mode 100644 node_modules/string_decoder/index.js delete mode 100644 node_modules/string_decoder/package.json diff --git a/node_modules/amqplib/CHANGELOG.md b/node_modules/amqplib/CHANGELOG.md deleted file mode 100644 index 2f4c973..0000000 --- a/node_modules/amqplib/CHANGELOG.md +++ /dev/null @@ -1,234 +0,0 @@ -# Change log for amqplib - -## Changes in v0.5.2 - - git log v0.5.1..v0.5.2 - - * Increase encoding buffer to accommodate large header values - ([PR 367](https://github.com/squaremo/amqp.node/pull/367)) - * Bring code up to date with new Buffer interface - ([PR 350](https://github.com/squaremo/amqp.node/pull/350)) - * Fix dangling connection problem - ([PR 340](https://github.com/squaremo/amqp.node/pull/340)) - * Clear up URL credentials parsing - ([PR 330](https://github.com/squaremo/amqp.node/pull/330)) - * Allow connection params to be suppied in object - ([PR 304](https://github.com/squaremo/amqp.node/pull/304)) - * Support explicit numeric types in field tables (e.g., headers) - ([PR 389](https://github.com/squaremo/amqp.node/pull/389), from a - suggestion in - [issue 358](https://github.com/squaremo/amqp.node/issues/358)) - -Thank you to all contributors, of PRs, issues and comments. - -## Changes in v0.5.1 - - git log v0.5.0..v0.5.1 - - * Fix mistake in closeBecause - ([PR 298](https://github.com/squaremo/amqp.node/pull/298); thanks - to @lholznagel and others who reported the issue, and to @nfantone - for the rapid fix) - -## Changes in v0.5.0 - - git log v0.4.2..v0.5.0 - - * Port to use bluebird rather than when.js - ([PR 295](https://github.com/squaremo/amqp.node/pull/295); thanks - to @nfantone, and special mention to @myndzi for #158) - * Fixed a problem with using `channel.get` in the callback model - ([PR 283](https://github.com/squaremo/amqp.node/pull/283); good - catch, @shanksauce) - * Added an example that uses generators (thanks @rudijs) - * Fixed a link in the comments relating to heartbeats (thanks - @tapickell) - -## Changes in v0.4.2 - - git log v0.4.1..v0.4.2 - - * Better documentation and examples - * Replace uses of ES6 keyword 'await' - -## Changes in v0.4.1 - - git log v0.4.0..v0.4.1 - - * Tested in Node.JS 0.8 through 4.2 and 5.5 - * Emit an error with the 'close' event if server-initiated - -## Changes in v0.4.0 - - git log v0.3.2..v0.4.0 - - * Tested on Node.JS 0.8 through 4.0 (and intervening io.js releases) - * Change meaning of 'b' fields in tables to match RabbitMQ (and AMQP - specification) - * Can now pass an object in place of connection URL - ([PR 159](https://github.com/squaremo/amqp.node/pull/159); thanks - to @ben-page) - * Operator-initiated connection close no longer results in 'error' - event - ([issue 110](https://github.com/squaremo/amqp.node/issues/110)) - * Channel and Connection errors have now a `.code` field with the - AMQP reply-code, which may help distinguish error cases - ([PR 150](https://github.com/squaremo/amqp.node/pull/150); thanks - to @hippich) - * Connection.close will resolve to an error if the connection is - already closed - ([issue 181](https://github.com/squaremo/amqp.node/issues/181)) - * Connection establishment will resolve with an error if the - TCP-level connection or the handshake times out - ([PR 169](https://github.com/squaremo/amqp.node/pull/169); thanks - to @zweifisch and @RoCat, who both submitted fixes) - * Add the `maxPriority` option as an alias for the `'x-max-priority'` - queue argument - ([PR 180](https://github.com/squaremo/amqp.node/pull/180); thanks - to @ebardes) - -## Changes in v0.3.2 (since v0.3.1) - - git log v0.3.1..v0.3.2 - - * Make the engine specification more flexible to admit io.js releases - -## Changes in v0.3.1 (since v0.3.0) - - git log v0.3.0..v0.3.1 - -### Fixes - - * Fail in the right way when a channel cannot be allocated [issue - 129](https://github.com/squaremo/amqp.node/issues/129) - * Make `waitForConfirms` work properly in callback API [PR - 116](https://github.com/squaremo/amqp.node/pull/116) - -### Enhancements - - * Two new options while connecting: - [timeout](https://github.com/squaremo/amqp.node/pull/118) and [keep - alive](https://github.com/squaremo/amqp.node/pull/125) (thanks to - @rexxars and @jcrugzz respectively) - -## Changes in v0.3.0 (since v0.2.1) - - git log v0.2.1..v0.3.0 - -### Enhancements - - * Allow additional client properties to be set for a connection - [Issue 98](https://github.com/squaremo/amqp.node/issues/98) and - [PR 80](https://github.com/squaremo/amqp.node/pull/80) - * New method in channel API to wait for all unconfirmed messages - [Issue 89](https://github.com/squaremo/amqp.node/issues/89) - * Now supports RabbitMQ's `EXTERNAL` authentication plugin - [Issue 105](https://github.com/squaremo/amqp.node/issues/105) - -## Changes in v0.2.1 (since v0.2.0) - -### Fixes - - * Do tuning negotation properly [PR - 84](https://github.com/squaremo/amqp.node/pull/84) - -## Changes in v0.2.0 (since v0.1.3) - - git log v0.1.3..v0.2.0 - -### Fixes - - * Correctly deal with missing fields (issue 48) - -### Enhancements - - * Added a callback-oriented API, parallel to the existing, - promise-oriented API. - * The response to assertExchange now contains the exchange name, - analagous to assertQueue (issue 49) - * The channel method `prefetch` now has a global flag, to be - [compatible with newer RabbitMQ][rabbitmq-prefetch-global]. - -## Changes in v0.1.3 (since v0.1.2) - - git log v0.1.2..v0.1.3 - -### Enhancements - - * Add support in the API for using Basic.Reject rather than - Basic.Nack, the latter of which is a RabbitMQ extension and not in - older versions of RabbitMQ. - -## Changes in v0.1.2 (since v0.1.1) - - git log v0.1.1..v0.1.2 - -### Fixes - - * Restore support for publishing zero-length messages - -### Enhancements - - * Recognise [authentication failures][rabbitmq-auth-failure] - * An option to set TCP_NODELAY on connection sockets - -## Changes in v0.1.1 (since v0.1.0) - - git log v0.1.0..v0.1.1 - -### Fixes - - * Safer frame construction, no longer relies on allocating a large, - fixed-size buffer and hoping it's big enough - * The ports of RabbitMQ tutorials now avoid a race between publishing - and closing the connection - -### Enhancements - - * Support for RabbitMQ's consumer priority extension - * Support for RabbitMQ's connnection.blocked extension - * Better write speed from batching frames for small messages - * Other minor efficiency gains in method encoding and decoding - * Channel and connection state errors (e.g., trying to write when - closed) include a stack trace from when they moved to that state - * The `arguments` table, passed as an option to some methods, can - include fields in its prototype chain - * Provide the more accurately named `persistent` as a near equivalent - of `deliveryMode` - -## Changes in v0.1.0 (since v0.0.2) - - git log v0.0.2..v0.1.0 - -### Breaking changes - - * Consumer callbacks are invoked with `null` if the consumer is - cancelled (see - [RabbitMQ's consumer cancel notification][rabbitmq-consumer-cancel]) - * In confirm channels, instead of `#publish` and `#sendToQueue` - returning promises, they return a boolean as for normal channels, - and take a Node.JS-style `function (err, ok)` callback for the - server ack or nack - -### Fixes - - * Overlapping channel and connection close frames are dealt with - gracefully - * Exceptions thrown in consumer callbacks are raised as `'error'` - events - * Zero-size messages are handled - * Avoid monkey-patching `Buffer`, and eschew - `require('util')._extend` - -### Enhancements - - * Channels now behave like `Writable` streams with regard to `#publish` - and `#sendToQueue`, returning a boolean from those methods and - emitting `'drain'` - * Connections now multiplex frames from channels fairly - * Low-level channel machinery is now fully callback-based - - -[rabbitmq-consumer-cancel]: http://www.rabbitmq.com/consumer-cancel.html -[rabbitmq-auth-failure]: http://www.rabbitmq.com/auth-notification.html -[rabbitmq-prefetch-global]: http://www.rabbitmq.com/consumer-prefetch.html diff --git a/node_modules/amqplib/LICENSE b/node_modules/amqplib/LICENSE deleted file mode 100644 index 62c710d..0000000 --- a/node_modules/amqplib/LICENSE +++ /dev/null @@ -1,6 +0,0 @@ -amqplib copyright (c) 2013, 2014 - Michael Bridgen - -This package, "amqplib", is licensed under the MIT License. A copy may -be found in the file LICENSE-MIT in this directory, or downloaded from -http://opensource.org/licenses/MIT. diff --git a/node_modules/amqplib/LICENSE-MIT b/node_modules/amqplib/LICENSE-MIT deleted file mode 100644 index d04bc01..0000000 --- a/node_modules/amqplib/LICENSE-MIT +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013, 2014 Michael Bridgen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/amqplib/Makefile b/node_modules/amqplib/Makefile deleted file mode 100644 index 89a50e9..0000000 --- a/node_modules/amqplib/Makefile +++ /dev/null @@ -1,46 +0,0 @@ -RABBITMQ_SRC_VERSION=rabbitmq_v3_2_1 -JSON=amqp-rabbitmq-0.9.1.json -RABBITMQ_CODEGEN=https://raw.githubusercontent.com/rabbitmq/rabbitmq-codegen -AMQP_JSON=$(RABBITMQ_CODEGEN)/$(RABBITMQ_SRC_VERSION)/$(JSON) -NODEJS_VERSIONS='0.8' '0.9' '0.10' '0.11' '0.12' '1.6' '2.5' '3.3' '4.2' '5.5' '6.2' '8.9' '9.1' - -MOCHA=./node_modules/.bin/mocha -_MOCHA=./node_modules/.bin/_mocha -UGLIFY=./node_modules/.bin/uglifyjs -ISTANBUL=./node_modules/.bin/istanbul - -.PHONY: test test-all-nodejs all clean coverage - -all: lib/defs.js - -clean: - rm lib/defs.js bin/amqp-rabbitmq-0.9.1.json - rm -rf ./coverage - -lib/defs.js: $(UGLIFY) bin/generate-defs.js bin/amqp-rabbitmq-0.9.1.json - (cd bin; node ./generate-defs.js > ../lib/defs.js) - $(UGLIFY) ./lib/defs.js -o ./lib/defs.js \ - -c 'sequences=false' --comments \ - -b 'indent-level=2' 2>&1 | (grep -v 'WARN' || true) - -test: lib/defs.js - $(MOCHA) --check-leaks -u tdd test/ - -test-all-nodejs: lib/defs.js - for v in $(NODEJS_VERSIONS); \ - do nave use $$v $(MOCHA) -u tdd -R progress test; \ - done - -coverage: $(ISTANBUL) lib/defs.js - $(ISTANBUL) cover $(_MOCHA) -- -u tdd -R progress test/ - $(ISTANBUL) report - @echo "HTML report at file://$$(pwd)/coverage/lcov-report/index.html" - -bin/amqp-rabbitmq-0.9.1.json: - curl -L $(AMQP_JSON) > $@ - -$(ISTANBUL): - npm install - -$(UGLIFY): - npm install diff --git a/node_modules/amqplib/README.md b/node_modules/amqplib/README.md deleted file mode 100644 index 9567c8f..0000000 --- a/node_modules/amqplib/README.md +++ /dev/null @@ -1,157 +0,0 @@ -# AMQP 0-9-1 library and client for Node.JS - -[![Build Status](https://travis-ci.org/squaremo/amqp.node.png)](https://travis-ci.org/squaremo/amqp.node) - - npm install amqplib - - * [Change log][changelog] - * [GitHub pages][gh-pages] - * [API reference][gh-pages-apiref] - * [Examples from RabbitMQ tutorials][tutes] - -A library for making AMQP 0-9-1 clients for Node.JS, and an AMQP 0-9-1 -client for Node.JS v0.8-0.12, v4-v9, and the intervening io.js -releases. - -This library does not implement [AMQP -1.0](https://github.com/squaremo/amqp.node/issues/63) or [AMQP -0-10](https://github.com/squaremo/amqp.node/issues/94). - -Project status: - - - Expected to work - - Complete high-level and low-level APIs (i.e., all bits of the protocol) - - Stable APIs - - A fair few tests - - Measured test coverage - - Ports of the [RabbitMQ tutorials][rabbitmq-tutes] as [examples][tutes] - - Used in production - -Still working on: - - - Getting to 100% (or very close to 100%) test coverage - -## Callback API example - -```javascript -var q = 'tasks'; - -function bail(err) { - console.error(err); - process.exit(1); -} - -// Publisher -function publisher(conn) { - conn.createChannel(on_open); - function on_open(err, ch) { - if (err != null) bail(err); - ch.assertQueue(q); - ch.sendToQueue(q, new Buffer('something to do')); - } -} - -// Consumer -function consumer(conn) { - var ok = conn.createChannel(on_open); - function on_open(err, ch) { - if (err != null) bail(err); - ch.assertQueue(q); - ch.consume(q, function(msg) { - if (msg !== null) { - console.log(msg.content.toString()); - ch.ack(msg); - } - }); - } -} - -require('amqplib/callback_api') - .connect('amqp://localhost', function(err, conn) { - if (err != null) bail(err); - consumer(conn); - publisher(conn); - }); -``` - -## Promise API example - -```javascript -var q = 'tasks'; - -var open = require('amqplib').connect('amqp://localhost'); - -// Publisher -open.then(function(conn) { - return conn.createChannel(); -}).then(function(ch) { - return ch.assertQueue(q).then(function(ok) { - return ch.sendToQueue(q, new Buffer('something to do')); - }); -}).catch(console.warn); - -// Consumer -open.then(function(conn) { - return conn.createChannel(); -}).then(function(ch) { - return ch.assertQueue(q).then(function(ok) { - return ch.consume(q, function(msg) { - if (msg !== null) { - console.log(msg.content.toString()); - ch.ack(msg); - } - }); - }); -}).catch(console.warn); -``` - -## Running tests - - npm test - -To run the tests RabbitMQ is required. Either install it with your package -manager, or use [docker][] to run a RabbitMQ instance. - - docker run -d --name amqp.test -p 5672:5672 rabbitmq - -If prefer not to run RabbitMQ locally it is also possible to use a -instance of RabbitMQ hosted elsewhere. Use the `URL` environment -variable to configure a different amqp host to connect to. You may -also need to do this if docker is not on localhost; e.g., if it's -running in docker-machine. - -One public host is dev.rabbitmq.com: - - URL=amqp://dev.rabbitmq.com npm test - -**NB** You may experience test failures due to timeouts if using the -dev.rabbitmq.com instance. - -You can run it under different versions of Node.JS using [nave][]: - - nave use 0.8 npm test - -or run the tests on all supported versions of Node.JS in one go: - - make test-all-nodejs - -(which also needs `nave` installed, of course). - -Lastly, setting the environment variable `LOG_ERRORS` will cause the -tests to output error messages encountered, to the console; this is -really only useful for checking the kind and formatting of the errors. - - LOG_ERRORS=true npm test - -## Test coverage - - make coverage - open file://`pwd`/coverage/lcov-report/index.html - -[gh-pages]: http://squaremo.github.com/amqp.node/ -[gh-pages-apiref]: http://squaremo.github.com/amqp.node/channel_api.html -[nave]: https://github.com/isaacs/nave -[tutes]: https://github.com/squaremo/amqp.node/tree/master/examples/tutorials -[rabbitmq-tutes]: http://www.rabbitmq.com/getstarted.html -[changelog]: https://github.com/squaremo/amqp.node/blob/master/CHANGELOG.md -[docker]: https://www.docker.com/ diff --git a/node_modules/amqplib/callback_api.js b/node_modules/amqplib/callback_api.js deleted file mode 100644 index 1955312..0000000 --- a/node_modules/amqplib/callback_api.js +++ /dev/null @@ -1,22 +0,0 @@ -var raw_connect = require('./lib/connect').connect; -var CallbackModel = require('./lib/callback_model').CallbackModel; - -// Supports three shapes: -// connect(url, options, callback) -// connect(url, callback) -// connect(callback) -function connect(url, options, cb) { - if (typeof url === 'function') - cb = url, url = false, options = false; - else if (typeof options === 'function') - cb = options, options = false; - - raw_connect(url, options, function(err, c) { - if (err === null) cb(null, new CallbackModel(c)); - else cb(err); - }); -}; - -module.exports.connect = connect; -module.exports.credentials = require('./lib/credentials'); -module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/channel_api.js b/node_modules/amqplib/channel_api.js deleted file mode 100644 index 6c8c4dd..0000000 --- a/node_modules/amqplib/channel_api.js +++ /dev/null @@ -1,16 +0,0 @@ -var raw_connect = require('./lib/connect').connect; -var ChannelModel = require('./lib/channel_model').ChannelModel; -var Promise = require('bluebird'); - -function connect(url, connOptions) { - return Promise.fromCallback(function(cb) { - return raw_connect(url, connOptions, cb); - }) - .then(function(conn) { - return new ChannelModel(conn); - }); -}; - -module.exports.connect = connect; -module.exports.credentials = require('./lib/credentials'); -module.exports.IllegalOperationError = require('./lib/error').IllegalOperationError; diff --git a/node_modules/amqplib/examples/headers.js b/node_modules/amqplib/examples/headers.js deleted file mode 100755 index e4f7bcc..0000000 --- a/node_modules/amqplib/examples/headers.js +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env node - -// Example of using a headers exchange - -var amqp = require('../') - -amqp.connect().then(function(conn) { - return conn.createChannel().then(withChannel); -}, console.error); - -function withChannel(ch) { - // NB the type of the exchange is 'headers' - ch.assertExchange('matching exchange', 'headers').then(function(ex) { - ch.assertQueue().then(function(q) { - bindAndConsume(ch, ex, q).then(function() { - send(ch, ex); - }); - }); - }); -} - -function bindAndConsume(ch, ex, q) { - // When using a headers exchange, the headers to be matched go in - // the binding arguments. The routing key is ignore, so best left - // empty. - - // 'x-match' is 'all' or 'any', meaning "all fields must match" or - // "at least one field must match", respectively. The values to be - // matched go in subsequent fields. - ch.bindQueue(q.queue, ex.exchange, '', {'x-match': 'any', - 'foo': 'bar', - 'baz': 'boo'}); - return ch.consume(q.queue, function(msg) { - console.log(msg.content.toString()); - }, {noAck: true}); -} - -function send(ch, ex) { - // The headers for a message are given as an option to `publish`: - ch.publish(ex.exchange, '', Buffer.from('hello'), {headers: {baz: 'boo'}}); - ch.publish(ex.exchange, '', Buffer.from('world'), {headers: {foo: 'bar'}}); -} diff --git a/node_modules/amqplib/examples/receive_generator.js b/node_modules/amqplib/examples/receive_generator.js deleted file mode 100644 index 8146de0..0000000 --- a/node_modules/amqplib/examples/receive_generator.js +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env node - -'use strict'; -const co = require('co'); -const amqp = require('amqplib'); -const readline = require('readline'); - -co(function* () { - const myConsumer = (msg) => { - if (msg !== null) { - console.log('consuming message %s in generator', JSON.stringify(msg.content.toString())); - } - }; - const conn = yield amqp.connect('amqp://localhost'); - try { - // create a message to consume - const q = 'hello'; - const msg = 'Hello World!'; - const channel = yield conn.createChannel(); - yield channel.assertQueue(q); - channel.sendToQueue(q, Buffer.from(msg)); - console.log(" [x] Sent '%s'", msg); - // consume the message - yield channel.consume(q, myConsumer, { noAck: true }); - } - catch (e) { - throw e; - } -}).catch(err => { - console.warn('Error:', err); -}); - -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -// pend until message is consumed -rl.question('newline to exit', () => process.exit()); \ No newline at end of file diff --git a/node_modules/amqplib/examples/send_generators.js b/node_modules/amqplib/examples/send_generators.js deleted file mode 100755 index 171778e..0000000 --- a/node_modules/amqplib/examples/send_generators.js +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env node - -'use strict'; - -// NB this requires the module 'co': -// npm install co -const co = require('co'); -const amqp = require('amqplib'); - -co(function* () { - // connection errors are handled in the co .catch handler - const conn = yield amqp.connect('amqp://localhost'); - - // try catch will throw any errors from the yielding the following promises to the co .catch handler - try { - const q = 'hello'; - const msg = 'Hello World!'; - - // use a confirm channel so we can check the message is sent OK. - const channel = yield conn.createConfirmChannel(); - - yield channel.assertQueue(q); - - channel.sendToQueue(q, Buffer.from(msg)); - - // if message has been nacked, this will result in an error (rejected promise); - yield channel.waitForConfirms(); - - console.log(" [x] Sent '%s'", msg); - - channel.close(); - } - catch (e) { - throw e; - } - finally { - conn.close(); - } - -}).catch(err => { - console.warn('Error:', err); -}); diff --git a/node_modules/amqplib/examples/ssl.js b/node_modules/amqplib/examples/ssl.js deleted file mode 100644 index 07f1ae1..0000000 --- a/node_modules/amqplib/examples/ssl.js +++ /dev/null @@ -1,64 +0,0 @@ -// Example of using a TLS/SSL connection. Note that the server must be -// configured to accept SSL connections; see, for example, -// http://www.rabbitmq.com/ssl.html. -// -// When trying this out, I followed the RabbitMQ SSL guide above, -// almost verbatim. I set the CN of the server certificate to -// 'localhost' rather than $(hostname) (since on my MBP hostname ends -// up being ".local", which is just weird). My client -// certificates etc., are in `../etc/client/`. My testca certificate -// is in `../etc/testca` and server certs etc., in `../etc/server`, -// and I've made a `rabbitmq.config` file, with which I start -// RabbitMQ: -// -// RABBITMQ_CONFIG_FILE=`pwd`/../etc/server/rabbitmq \ -// /usr/local/sbin/rabbitmq-server & -// -// A way to check RabbitMQ's running with SSL OK is to use -// -// openssl s_client -connect localhost:5671 - -var amqp = require('../'); -var fs = require('fs'); - -// Assemble the SSL options; for verification we need at least -// * a certificate to present to the server ('cert', in PEM format) -// * the private key for the certificate ('key', in PEM format) -// * (possibly) a passphrase for the private key -// -// The first two may be replaced with a PKCS12 file ('pfx', in pkcs12 -// format) - -// We will also want to list the CA certificates that we will trust, -// since we're using a self-signed certificate. It is NOT recommended -// to use `rejectUnauthorized: false`. - -// Options for full client and server verification: -var opts = { - cert: fs.readFileSync('../etc/client/cert.pem'), - key: fs.readFileSync('../etc/client/key.pem'), - // cert and key or - // pfx: fs.readFileSync('../etc/client/keycert.p12'), - passphrase: 'MySecretPassword', - ca: [fs.readFileSync('../etc/testca/cacert.pem')] -}; - -// Options for just confidentiality. This requires RabbitMQ's SSL -// configuration to include the items -// -// {verify, verify_none}, -// {fail_if_no_peer_cert,false} -// -// var opts = { ca: [fs.readFileSync('../etc/testca/cacert.pem')] }; - -// Option to use the SSL client certificate for authentication -// opts.credentials = amqp.credentials.external(); - -var open = amqp.connect('amqps://localhost', opts); - -open.then(function(conn) { - process.on('SIGINT', conn.close.bind(conn)); - return conn.createChannel().then(function(ch) { - ch.sendToQueue('foo', Buffer.from('Hello World!')); - }); -}).then(null, console.warn); diff --git a/node_modules/amqplib/examples/tutorials/README.md b/node_modules/amqplib/examples/tutorials/README.md deleted file mode 100644 index 333fda3..0000000 --- a/node_modules/amqplib/examples/tutorials/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# RabbitMQ tutorials - -This directory contains the [RabbitMQ tutorials][rabbitmq-tutes], -ported to amqplib. The sub-directory `callback_api` has translations -of the tutorial programs to the callback-oriented API. - -## Preparation - -To run the tutorial code, you need amqplib installed. Assuming you are -in a clone of the amqplib repository, from the tutorials directory: - - npm install - -or to use the latest released version, - - npm install amqplib - -Then just run each file as a script, e.g., in bash - - ./send.js - -or - - node send.js - -or - - nave use 0.8 node send.js - -## [Tutorial one: Hello World!][tute-one] - -A "Hello World" example, with one script sending a message to a queue, -and another receiving messages from the same queue. - - * [send.js](send.js) - * [receive.js](receive.js) - -## [Tutorial two: Work queues][tute-two] - -Using RabbitMQ as a work queue; `new_task` creates a task, and -`worker` processes tasks. Multiple `worker` process will share the -tasks among them. Long-running tasks are simulated by supplying a -string with dots, e.g., '...' to `new_task`. Each dot makes the worker -"work" for a second. - - * [new_task.js](new_task.js) - * [worker.js](worker.js) - -## [Tutorial three: Publish/Subscribe][tute-three] - -Using RabbitMQ as a broadcast mechanism. `emit_log` sends a "log" -message to a fanout exchange, and all `receive_logs` processes receive -log messages. - - * [emit_log.js](emit_log.js) - * [receive_logs.js](receive_logs.js) - -## [Tutorial four: Routing][tute-four] - -Using RabbitMQ as a routing ('somecast') mechanism. `emit_log_direct` -sends a log message with a severity, and all `receive_logs_direct` -processes receive log messages for the severities on which they are -listening. - - * [emit_log_direct.js](emit_log_direct.js) - * [receive_logs_direct.js](receive_logs_direct.js) - -## [Tutorial five: Topics][tute-five] - -Extends the previous tutorial to routing with wildcarded patterns. - - * [emit_log_topic.js](emit_log_topic.js) - * [receive_logs_topic.js](receive_logs_topic.js) - -## [Tutorial six: RPC][tute-six] - -Using RabbitMQ as an RPC intermediary, queueing requests for servers -and routing replies back to clients. - - * [rpc_server.js](rpc_server.js) - * [rpc_client.js](rpc_client.js) - -I depart slightly from the original tutorial code, which I think has -some needless object-orientation (in the Python code; you don't get a -choice about needless object-orientation in Java). - -[rabbitmq-tutes]: http://github.com/rabbitmq/rabbitmq-tutorials -[tute-one]: http://www.rabbitmq.com/tutorials/tutorial-one-python.html -[tute-two]: http://www.rabbitmq.com/tutorials/tutorial-two-python.html -[tute-three]: http://www.rabbitmq.com/tutorials/tutorial-three-python.html -[tute-four]: http://www.rabbitmq.com/tutorials/tutorial-four-python.html -[tute-five]: http://www.rabbitmq.com/tutorials/tutorial-five-python.html -[tute-six]: http://www.rabbitmq.com/tutorials/tutorial-six-python.html diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js deleted file mode 100755 index 9ea353d..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/emit_log.js +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - - var ex = 'logs'; - - function on_channel_open(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertExchange(ex, 'fanout', {durable: false}); - var msg = process.argv.slice(2).join(' ') || - 'info: Hello World!'; - ch.publish(ex, '', Buffer.from(msg)); - console.log(" [x] Sent '%s'", msg); - ch.close(function() { conn.close(); }); - } - - conn.createChannel(on_channel_open); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js deleted file mode 100755 index bd4e640..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_direct.js +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -var args = process.argv.slice(2); -var severity = (args.length > 0) ? args[0] : 'info'; -var message = args.slice(1).join(' ') || 'Hello World!'; - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - - var ex = 'direct_logs'; - var exopts = {durable: false}; - - function on_channel_open(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertExchange(ex, 'direct', exopts, function(err, ok) { - ch.publish(ex, severity, Buffer.from(message)); - ch.close(function() { conn.close(); }); - }); - } - conn.createChannel(on_channel_open); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js deleted file mode 100755 index 7601ecf..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/emit_log_topic.js +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -var args = process.argv.slice(2); -var key = (args.length > 0) ? args[0] : 'info'; -var message = args.slice(1).join(' ') || 'Hello World!'; - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - var ex = 'topic_logs', exopts = {durable: false}; - conn.createChannel(function(err, ch) { - ch.assertExchange(ex, 'topic', exopts, function(err, ok) { - if (err !== null) return bail(err, conn); - ch.publish(ex, key, Buffer.from(message)); - console.log(" [x] Sent %s:'%s'", key, message); - ch.close(function() { conn.close(); }); - }); - }); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/new_task.js b/node_modules/amqplib/examples/tutorials/callback_api/new_task.js deleted file mode 100755 index 6122231..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/new_task.js +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - - var q = 'task_queue'; - - conn.createChannel(function(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertQueue(q, {durable: true}, function(err, _ok) { - if (err !== null) return bail(err, conn); - var msg = process.argv.slice(2).join(' ') || "Hello World!"; - ch.sendToQueue(q, Buffer.from(msg), {persistent: true}); - console.log(" [x] Sent '%s'", msg); - ch.close(function() { conn.close(); }); - }); - }); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive.js b/node_modules/amqplib/examples/tutorials/callback_api/receive.js deleted file mode 100755 index c6bb056..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/receive.js +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - process.once('SIGINT', function() { conn.close(); }); - - var q = 'hello'; - - function on_channel_open(err, ch) { - ch.assertQueue(q, {durable: false}, function(err, ok) { - if (err !== null) return bail(err, conn); - ch.consume(q, function(msg) { // message callback - console.log(" [x] Received '%s'", msg.content.toString()); - }, {noAck: true}, function(_consumeOk) { // consume callback - console.log(' [*] Waiting for messages. To exit press CTRL+C'); - }); - }); - } - - conn.createChannel(on_channel_open); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js deleted file mode 100755 index 4d024e4..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs.js +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - process.once('SIGINT', function() { conn.close(); }); - - var ex = 'logs'; - - function on_channel_open(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertQueue('', {exclusive: true}, function(err, ok) { - var q = ok.queue; - ch.bindQueue(q, ex, ''); - ch.consume(q, logMessage, {noAck: true}, function(err, ok) { - if (err !== null) return bail(err, conn); - console.log(" [*] Waiting for logs. To exit press CTRL+C."); - }); - }); - } - - function logMessage(msg) { - if (msg) - console.log(" [x] '%s'", msg.content.toString()); - } - - conn.createChannel(on_channel_open); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js deleted file mode 100755 index 9bb9f98..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_direct.js +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -var basename = require('path').basename; - -var severities = process.argv.slice(2); -if (severities.length < 1) { - console.log('Usage %s [info] [warning] [error]', - basename(process.argv[1])); - process.exit(1); -} - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - process.once('SIGINT', function() { conn.close(); }); - - conn.createChannel(function(err, ch) { - if (err !== null) return bail(err, conn); - var ex = 'direct_logs', exopts = {durable: false}; - - ch.assertExchange(ex, 'direct', exopts); - ch.assertQueue('', {exclusive: true}, function(err, ok) { - if (err !== null) return bail(err, conn); - - var queue = ok.queue, i = 0; - - function sub(err) { - if (err !== null) return bail(err, conn); - else if (i < severities.length) { - ch.bindQueue(queue, ex, severities[i], {}, sub); - i++; - } - } - - ch.consume(queue, logMessage, {noAck: true}, function(err) { - if (err !== null) return bail(err, conn); - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - sub(null); - }); - }); - }); -} - -function logMessage(msg) { - console.log(" [x] %s:'%s'", - msg.fields.routingKey, - msg.content.toString()); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js deleted file mode 100755 index 2c827c2..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/receive_logs_topic.js +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); -var basename = require('path').basename; - -var keys = process.argv.slice(2); -if (keys.length < 1) { - console.log('Usage %s pattern [pattern...]', - basename(process.argv[1])); - process.exit(1); -} - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - process.once('SIGINT', function() { conn.close(); }); - - conn.createChannel(function(err, ch) { - if (err !== null) return bail(err, conn); - var ex = 'topic_logs', exopts = {durable: false}; - - ch.assertExchange(ex, 'topic', exopts); - ch.assertQueue('', {exclusive: true}, function(err, ok) { - if (err !== null) return bail(err, conn); - - var queue = ok.queue, i = 0; - - function sub(err) { - if (err !== null) return bail(err, conn); - else if (i < keys.length) { - ch.bindQueue(queue, ex, keys[i], {}, sub); - i++; - } - } - - ch.consume(queue, logMessage, {noAck: true}, function(err) { - if (err !== null) return bail(err, conn); - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - sub(null); - }); - }); - }); -} - -function logMessage(msg) { - console.log(" [x] %s:'%s'", - msg.fields.routingKey, - msg.content.toString()); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js deleted file mode 100755 index abf22a0..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/rpc_client.js +++ /dev/null @@ -1,49 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); -var basename = require('path').basename; -var uuid = require('node-uuid'); - -var n; -try { - if (process.argv.length < 3) throw Error('Too few args'); - n = parseInt(process.argv[2]); -} -catch (e) { - console.error(e); - console.warn('Usage: %s number', basename(process.argv[1])); - process.exit(1); -} - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - conn.createChannel(function(err, ch) { - if (err !== null) return bail(err, conn); - - var correlationId = uuid(); - function maybeAnswer(msg) { - if (msg.properties.correlationId === correlationId) { - console.log(' [.] Got %d', msg.content.toString()); - } - else return bail(new Error('Unexpected message'), conn); - ch.close(function() { conn.close(); }); - } - - ch.assertQueue('', {exclusive: true}, function(err, ok) { - if (err !== null) return bail(err, conn); - var queue = ok.queue; - ch.consume(queue, maybeAnswer, {noAck:true}); - console.log(' [x] Requesting fib(%d)', n); - ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { - replyTo: queue, correlationId: correlationId - }); - }); - }); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js b/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js deleted file mode 100755 index dae1d9b..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/rpc_server.js +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function fib(n) { - var a = 0, b = 1; - for (var i=0; i < n; i++) { - var c = a + b; - a = b; b = c; - } - return a; -} - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - - process.once('SIGINT', function() { conn.close(); }); - - var q = 'rpc_queue'; - - conn.createChannel(function(err, ch) { - ch.assertQueue(q, {durable: false}); - ch.prefetch(1); - ch.consume(q, reply, {noAck:false}, function(err) { - if (err !== null) return bail(err, conn); - console.log(' [x] Awaiting RPC requests'); - }); - - function reply(msg) { - var n = parseInt(msg.content.toString()); - console.log(' [.] fib(%d)', n); - ch.sendToQueue(msg.properties.replyTo, - Buffer.from(fib(n).toString()), - {correlationId: msg.properties.correlationId}); - ch.ack(msg); - } - }); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/send.js b/node_modules/amqplib/examples/tutorials/callback_api/send.js deleted file mode 100755 index 8ff0e4b..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/send.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - - var q = 'hello'; - var msg = 'Hello World!'; - - function on_channel_open(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertQueue(q, {durable: false}, function(err, ok) { - if (err !== null) return bail(err, conn); - ch.sendToQueue(q, Buffer.from(msg)); - console.log(" [x] Sent '%s'", msg); - ch.close(function() { conn.close(); }); - }); - } - - conn.createChannel(on_channel_open); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/callback_api/worker.js b/node_modules/amqplib/examples/tutorials/callback_api/worker.js deleted file mode 100755 index ad7d076..0000000 --- a/node_modules/amqplib/examples/tutorials/callback_api/worker.js +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib/callback_api'); - -function bail(err, conn) { - console.error(err); - if (conn) conn.close(function() { process.exit(1); }); -} - -function on_connect(err, conn) { - if (err !== null) return bail(err); - process.once('SIGINT', function() { conn.close(); }); - - var q = 'task_queue'; - - conn.createChannel(function(err, ch) { - if (err !== null) return bail(err, conn); - ch.assertQueue(q, {durable: true}, function(err, _ok) { - ch.consume(q, doWork, {noAck: false}); - console.log(" [*] Waiting for messages. To exit press CTRL+C"); - }); - - function doWork(msg) { - var body = msg.content.toString(); - console.log(" [x] Received '%s'", body); - var secs = body.split('.').length - 1; - setTimeout(function() { - console.log(" [x] Done"); - ch.ack(msg); - }, secs * 1000); - } - }); -} - -amqp.connect(on_connect); diff --git a/node_modules/amqplib/examples/tutorials/emit_log.js b/node_modules/amqplib/examples/tutorials/emit_log.js deleted file mode 100755 index 2bf7e14..0000000 --- a/node_modules/amqplib/examples/tutorials/emit_log.js +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - var ex = 'logs'; - var ok = ch.assertExchange(ex, 'fanout', {durable: false}) - - var message = process.argv.slice(2).join(' ') || - 'info: Hello World!'; - - return ok.then(function() { - ch.publish(ex, '', Buffer.from(message)); - console.log(" [x] Sent '%s'", message); - return ch.close(); - }); - }).finally(function() { conn.close(); }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_direct.js b/node_modules/amqplib/examples/tutorials/emit_log_direct.js deleted file mode 100755 index 0846edf..0000000 --- a/node_modules/amqplib/examples/tutorials/emit_log_direct.js +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -var args = process.argv.slice(2); -var severity = (args.length > 0) ? args[0] : 'info'; -var message = args.slice(1).join(' ') || 'Hello World!'; - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - var ex = 'direct_logs'; - var ok = ch.assertExchange(ex, 'direct', {durable: false}); - - return ok.then(function() { - ch.publish(ex, severity, Buffer.from(message)); - console.log(" [x] Sent %s:'%s'", severity, message); - return ch.close(); - }); - }).finally(function() { conn.close(); }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/emit_log_topic.js b/node_modules/amqplib/examples/tutorials/emit_log_topic.js deleted file mode 100755 index 5f643a3..0000000 --- a/node_modules/amqplib/examples/tutorials/emit_log_topic.js +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -var args = process.argv.slice(2); -var key = (args.length > 0) ? args[0] : 'info'; -var message = args.slice(1).join(' ') || 'Hello World!'; - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - var ex = 'topic_logs'; - var ok = ch.assertExchange(ex, 'topic', {durable: false}); - return ok.then(function() { - ch.publish(ex, key, Buffer.from(message)); - console.log(" [x] Sent %s:'%s'", key, message); - return ch.close(); - }); - }).finally(function() { conn.close(); }) -}).catch(console.log); diff --git a/node_modules/amqplib/examples/tutorials/new_task.js b/node_modules/amqplib/examples/tutorials/new_task.js deleted file mode 100755 index c25cfbc..0000000 --- a/node_modules/amqplib/examples/tutorials/new_task.js +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env node -// Post a new task to the work queue - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - var q = 'task_queue'; - var ok = ch.assertQueue(q, {durable: true}); - - return ok.then(function() { - var msg = process.argv.slice(2).join(' ') || "Hello World!"; - ch.sendToQueue(q, Buffer.from(msg), {deliveryMode: true}); - console.log(" [x] Sent '%s'", msg); - return ch.close(); - }); - }).finally(function() { conn.close(); }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/package.json b/node_modules/amqplib/examples/tutorials/package.json deleted file mode 100644 index 71f49af..0000000 --- a/node_modules/amqplib/examples/tutorials/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "amqplib-tutorials", - "version": "0.0.1", - "description": "The RabbitMQ tutorials, ported to amqplib", - "main": "send.js", - "dependencies": { - "amqplib": "../..", - "node-uuid": "*" - }, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": "", - "author": "Michael Bridgen ", - "license": "MPL 2.0" -} diff --git a/node_modules/amqplib/examples/tutorials/receive.js b/node_modules/amqplib/examples/tutorials/receive.js deleted file mode 100755 index b7a7975..0000000 --- a/node_modules/amqplib/examples/tutorials/receive.js +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - - var ok = ch.assertQueue('hello', {durable: false}); - - ok = ok.then(function(_qok) { - return ch.consume('hello', function(msg) { - console.log(" [x] Received '%s'", msg.content.toString()); - }, {noAck: true}); - }); - - return ok.then(function(_consumeOk) { - console.log(' [*] Waiting for messages. To exit press CTRL+C'); - }); - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs.js b/node_modules/amqplib/examples/tutorials/receive_logs.js deleted file mode 100755 index d592af9..0000000 --- a/node_modules/amqplib/examples/tutorials/receive_logs.js +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - var ok = ch.assertExchange('logs', 'fanout', {durable: false}); - ok = ok.then(function() { - return ch.assertQueue('', {exclusive: true}); - }); - ok = ok.then(function(qok) { - return ch.bindQueue(qok.queue, 'logs', '').then(function() { - return qok.queue; - }); - }); - ok = ok.then(function(queue) { - return ch.consume(queue, logMessage, {noAck: true}); - }); - return ok.then(function() { - console.log(' [*] Waiting for logs. To exit press CTRL+C'); - }); - - function logMessage(msg) { - console.log(" [x] '%s'", msg.content.toString()); - } - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_direct.js b/node_modules/amqplib/examples/tutorials/receive_logs_direct.js deleted file mode 100755 index 17fc22d..0000000 --- a/node_modules/amqplib/examples/tutorials/receive_logs_direct.js +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); -var all = require('bluebird').all; -var basename = require('path').basename; - -var severities = process.argv.slice(2); -if (severities.length < 1) { - console.warn('Usage: %s [info] [warning] [error]', - basename(process.argv[1])); - process.exit(1); -} - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - var ex = 'direct_logs'; - - var ok = ch.assertExchange(ex, 'direct', {durable: false}); - - ok = ok.then(function() { - return ch.assertQueue('', {exclusive: true}); - }); - - ok = ok.then(function(qok) { - var queue = qok.queue; - return all(severities.map(function(sev) { - ch.bindQueue(queue, ex, sev); - })).then(function() { return queue; }); - }); - - ok = ok.then(function(queue) { - return ch.consume(queue, logMessage, {noAck: true}); - }); - return ok.then(function() { - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - }); - - function logMessage(msg) { - console.log(" [x] %s:'%s'", - msg.fields.routingKey, - msg.content.toString()); - } - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/receive_logs_topic.js b/node_modules/amqplib/examples/tutorials/receive_logs_topic.js deleted file mode 100755 index 3e8eb6f..0000000 --- a/node_modules/amqplib/examples/tutorials/receive_logs_topic.js +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); -var basename = require('path').basename; -var all = require('bluebird').all; - -var keys = process.argv.slice(2); -if (keys.length < 1) { - console.log('Usage: %s pattern [pattern...]', - basename(process.argv[1])); - process.exit(1); -} - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - var ex = 'topic_logs'; - var ok = ch.assertExchange(ex, 'topic', {durable: false}); - - ok = ok.then(function() { - return ch.assertQueue('', {exclusive: true}); - }); - - ok = ok.then(function(qok) { - var queue = qok.queue; - return all(keys.map(function(rk) { - ch.bindQueue(queue, ex, rk); - })).then(function() { return queue; }); - }); - - ok = ok.then(function(queue) { - return ch.consume(queue, logMessage, {noAck: true}); - }); - return ok.then(function() { - console.log(' [*] Waiting for logs. To exit press CTRL+C.'); - }); - - function logMessage(msg) { - console.log(" [x] %s:'%s'", - msg.fields.routingKey, - msg.content.toString()); - } - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_client.js b/node_modules/amqplib/examples/tutorials/rpc_client.js deleted file mode 100755 index 47566b3..0000000 --- a/node_modules/amqplib/examples/tutorials/rpc_client.js +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); -var basename = require('path').basename; -var Promise = require('bluebird'); -var uuid = require('node-uuid'); - -// I've departed from the form of the original RPC tutorial, which -// needlessly introduces a class definition, and doesn't even -// parameterise the request. - -var n; -try { - if (process.argv.length < 3) throw Error('Too few args'); - n = parseInt(process.argv[2]); -} -catch (e) { - console.error(e); - console.warn('Usage: %s number', basename(process.argv[1])); - process.exit(1); -} - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - return new Promise(function(resolve) { - var corrId = uuid(); - function maybeAnswer(msg) { - if (msg.properties.correlationId === corrId) { - resolve(msg.content.toString()); - } - } - - var ok = ch.assertQueue('', {exclusive: true}) - .then(function(qok) { return qok.queue; }); - - ok = ok.then(function(queue) { - return ch.consume(queue, maybeAnswer, {noAck: true}) - .then(function() { return queue; }); - }); - - ok = ok.then(function(queue) { - console.log(' [x] Requesting fib(%d)', n); - ch.sendToQueue('rpc_queue', Buffer.from(n.toString()), { - correlationId: corrId, replyTo: queue - }); - }); - }); - }) - .then(function(fibN) { - console.log(' [.] Got %d', fibN); - }) - .finally(function() { conn.close(); }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/rpc_server.js b/node_modules/amqplib/examples/tutorials/rpc_server.js deleted file mode 100755 index 84101ce..0000000 --- a/node_modules/amqplib/examples/tutorials/rpc_server.js +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -function fib(n) { - // Do it the ridiculous, but not most ridiculous, way. For better, - // see http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms - var a = 0, b = 1; - for (var i=0; i < n; i++) { - var c = a + b; - a = b; b = c; - } - return a; -} - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - var q = 'rpc_queue'; - var ok = ch.assertQueue(q, {durable: false}); - var ok = ok.then(function() { - ch.prefetch(1); - return ch.consume(q, reply); - }); - return ok.then(function() { - console.log(' [x] Awaiting RPC requests'); - }); - - function reply(msg) { - var n = parseInt(msg.content.toString()); - console.log(' [.] fib(%d)', n); - var response = fib(n); - ch.sendToQueue(msg.properties.replyTo, - Buffer.from(response.toString()), - {correlationId: msg.properties.correlationId}); - ch.ack(msg); - } - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/send.js b/node_modules/amqplib/examples/tutorials/send.js deleted file mode 100755 index 59f846e..0000000 --- a/node_modules/amqplib/examples/tutorials/send.js +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env node - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - return conn.createChannel().then(function(ch) { - var q = 'hello'; - var msg = 'Hello World!'; - - var ok = ch.assertQueue(q, {durable: false}); - - return ok.then(function(_qok) { - // NB: `sentToQueue` and `publish` both return a boolean - // indicating whether it's OK to send again straight away, or - // (when `false`) that you should wait for the event `'drain'` - // to fire before writing again. We're just doing the one write, - // so we'll ignore it. - ch.sendToQueue(q, Buffer.from(msg)); - console.log(" [x] Sent '%s'", msg); - return ch.close(); - }); - }).finally(function() { conn.close(); }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/tutorials/worker.js b/node_modules/amqplib/examples/tutorials/worker.js deleted file mode 100755 index fdb72df..0000000 --- a/node_modules/amqplib/examples/tutorials/worker.js +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env node -// Process tasks from the work queue - -var amqp = require('amqplib'); - -amqp.connect('amqp://localhost').then(function(conn) { - process.once('SIGINT', function() { conn.close(); }); - return conn.createChannel().then(function(ch) { - var ok = ch.assertQueue('task_queue', {durable: true}); - ok = ok.then(function() { ch.prefetch(1); }); - ok = ok.then(function() { - ch.consume('task_queue', doWork, {noAck: false}); - console.log(" [*] Waiting for messages. To exit press CTRL+C"); - }); - return ok; - - function doWork(msg) { - var body = msg.content.toString(); - console.log(" [x] Received '%s'", body); - var secs = body.split('.').length - 1; - //console.log(" [x] Task takes %d seconds", secs); - setTimeout(function() { - console.log(" [x] Done"); - ch.ack(msg); - }, secs * 1000); - } - }); -}).catch(console.warn); diff --git a/node_modules/amqplib/examples/waitForConfirms.js b/node_modules/amqplib/examples/waitForConfirms.js deleted file mode 100644 index d16a1d8..0000000 --- a/node_modules/amqplib/examples/waitForConfirms.js +++ /dev/null @@ -1,22 +0,0 @@ -var amqp = require('../'); - -var NUM_MSGS = 20; - -function mkCallback(i) { - return (i % 2) === 0 ? function(err) { - if (err !== null) { console.error('Message %d failed!', i); } - else { console.log('Message %d confirmed', i); } - } : null; -} - -amqp.connect().then(function(c) { - c.createConfirmChannel().then(function(ch) { - for (var i=0; i < NUM_MSGS; i++) { - ch.publish('amq.topic', 'whatever', Buffer.from('blah'), {}, mkCallback(i)); - } - ch.waitForConfirms().then(function() { - console.log('All messages done'); - c.close(); - }).catch(console.error); - }); -}); diff --git a/node_modules/amqplib/package.json b/node_modules/amqplib/package.json deleted file mode 100644 index 88fad48..0000000 --- a/node_modules/amqplib/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "_from": "amqplib", - "_id": "amqplib@0.5.2", - "_inBundle": false, - "_integrity": "sha512-l9mCs6LbydtHqRniRwYkKdqxVa6XMz3Vw1fh+2gJaaVgTM6Jk3o8RccAKWKtlhT1US5sWrFh+KKxsVUALURSIA==", - "_location": "/amqplib", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "amqplib", - "name": "amqplib", - "escapedName": "amqplib", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.5.2.tgz", - "_shasum": "d2d7313c7ffaa4d10bcf1e6252de4591b6cc7b63", - "_spec": "amqplib", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP", - "author": { - "name": "Michael Bridgen", - "email": "mikeb@squaremobius.net" - }, - "bugs": { - "url": "https://github.com/squaremo/amqp.node/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bitsyntax": "~0.0.4", - "bluebird": "^3.4.6", - "buffer-more-ints": "0.0.2", - "readable-stream": "1.x >=1.1.9", - "safe-buffer": "^5.0.1" - }, - "deprecated": false, - "description": "An AMQP 0-9-1 (e.g., RabbitMQ) library and client.", - "devDependencies": { - "claire": "0.4.1", - "istanbul": "0.1.x", - "mocha": "~1", - "uglify-js": "2.4.x" - }, - "engines": { - "node": ">=0.8 <=9" - }, - "homepage": "http://squaremo.github.io/amqp.node/", - "keywords": [ - "AMQP", - "AMQP 0-9-1", - "RabbitMQ" - ], - "license": "MIT", - "main": "./channel_api.js", - "name": "amqplib", - "repository": { - "type": "git", - "url": "git+https://github.com/squaremo/amqp.node.git" - }, - "scripts": { - "prepublish": "make", - "test": "make test" - }, - "version": "0.5.2" -} diff --git a/node_modules/amqplib/test/bitset.js b/node_modules/amqplib/test/bitset.js deleted file mode 100644 index 35e7656..0000000 --- a/node_modules/amqplib/test/bitset.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -var claire = require('claire'); - -var forAll = claire.forAll, - arb = claire.data, - label = claire.label, - choice = claire.choice, - transform = claire.transform; - -var BitSet = require('../lib/bitset').BitSet; -var PosInt = transform(Math.floor, arb.Positive); - -var EmptyBitSet = label('bitset', transform( - function(size) { - return new BitSet(size); - }, - choice(arb.Nothing, PosInt))); - -suite('BitSet', function() { - -test('get bit', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - return b.get(bit); - }).asTest()); - -test('clear bit', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - b.clear(bit); - return !b.get(bit); - }).asTest()); - -test('next set of empty', forAll(EmptyBitSet) - .satisfy(function(b) { - return b.nextSetBit(0) === -1; - }).asTest()); - -test('next set of one bit', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - return b.nextSetBit(0) === bit; - }).asTest()); - -test('next set same bit', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - return b.nextSetBit(bit) === bit; - }).asTest()); - -test('next set following bit', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - return b.nextSetBit(bit+1) === -1; - }).asTest()); - -test('next clear of empty', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { return b.nextClearBit(bit) === bit; }) - .asTest()); - -test('next clear of one set', forAll(EmptyBitSet, PosInt) - .satisfy(function(b, bit) { - b.set(bit); - return b.nextClearBit(bit) === bit + 1; - }).asTest()); - -}); diff --git a/node_modules/amqplib/test/callback_api.js b/node_modules/amqplib/test/callback_api.js deleted file mode 100644 index 5aea0bf..0000000 --- a/node_modules/amqplib/test/callback_api.js +++ /dev/null @@ -1,313 +0,0 @@ -'use strict'; - -var assert = require('assert'); -var crypto = require('crypto'); -var api = require('../callback_api'); -var util = require('./util'); -var schedule = util.schedule; -var randomString = util.randomString; -var kCallback = util.kCallback; -var domain = require('domain'); -var Buffer = require('safe-buffer').Buffer; - -var URL = process.env.URL || 'amqp://localhost'; - -function connect(cb) { - api.connect(URL, {}, cb); -} - -// Construct a node-style callback from a `done` function -function doneCallback(done) { - return function(err, _) { - if (err == null) done(); - else done(err); - }; -} - -function ignore() {} - -function twice(done) { - var first = function(err) { - if (err == undefined) second = done; - else second = ignore, done(err); - }; - var second = function(err) { - if (err == undefined) first = done; - else first = ignore, done(err); - }; - return {first: function(err) { first(err); }, - second: function(err) { second(err); }}; -} - -// Adapt 'done' to a callback that's expected to fail -function failCallback(done) { - return function(err, _) { - if (err == null) done(new Error('Expected failure, got ' + val)); - else done(); - }; -} - -function waitForMessages(ch, q, k) { - ch.checkQueue(q, function(e, ok) { - if (e != null) return k(e); - else if (ok.messageCount > 0) return k(null, ok); - else schedule(waitForMessages.bind(null, ch, q, k)); - }); -} - - -suite('connect', function() { - -test('at all', function(done) { - connect(doneCallback(done)); -}); - -}); - -function channel_test_fn(method) { - return function(name, chfun) { - test(name, function(done) { - connect(kCallback(function(c) { - c[method](kCallback(function(ch) { - chfun(ch, done); - }, done)); - }, done)); - }); - }; -} -var channel_test = channel_test_fn('createChannel'); -var confirm_channel_test = channel_test_fn('createConfirmChannel'); - -suite('channel open', function() { - -channel_test('at all', function(ch, done) { - done(); -}); - -channel_test('open and close', function(ch, done) { - ch.close(doneCallback(done)); -}); - -}); - -suite('assert, check, delete', function() { - -channel_test('assert, check, delete queue', function(ch, done) { - ch.assertQueue('test.cb.queue', {}, kCallback(function(q) { - ch.checkQueue('test.cb.queue', kCallback(function(ok) { - ch.deleteQueue('test.cb.queue', {}, doneCallback(done)); - }, done)); - }, done)); -}); - -channel_test('assert, check, delete exchange', function(ch, done) { - ch.assertExchange( - 'test.cb.exchange', 'topic', {}, kCallback(function(ex) { - ch.checkExchange('test.cb.exchange', kCallback(function(ok) { - ch.deleteExchange('test.cb.exchange', {}, doneCallback(done)); - }, done)); - }, done)); -}); - -channel_test('fail on check non-queue', function(ch, done) { - var both = twice(done); - ch.on('error', failCallback(both.first)); - ch.checkQueue('test.cb.nothere', failCallback(both.second)); -}); - -channel_test('fail on check non-exchange', function(ch, done) { - var both = twice(done); - ch.on('error', failCallback(both.first)); - ch.checkExchange('test.cb.nothere', failCallback(both.second)); -}); - -}); - -suite('bindings', function() { - -channel_test('bind queue', function(ch, done) { - ch.assertQueue('test.cb.bindq', {}, kCallback(function(q) { - ch.assertExchange( - 'test.cb.bindex', 'fanout', {}, kCallback(function(ex) { - ch.bindQueue(q.queue, ex.exchange, '', {}, - doneCallback(done)); - }, done)); - }, done)); -}); - -channel_test('bind exchange', function(ch, done) { - ch.assertExchange( - 'test.cb.bindex1', 'fanout', {}, kCallback(function(ex1) { - ch.assertExchange( - 'test.cb.bindex2', 'fanout', {}, kCallback(function(ex2) { - ch.bindExchange(ex1.exchange, - ex2.exchange, '', {}, - doneCallback(done)); - }, done)); - }, done)); -}); - -}); - -suite('sending messages', function() { - -channel_test('send to queue and consume noAck', function(ch, done) { - var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { - if (e !== null) return done(e); - ch.consume(q.queue, function(m) { - if (m.content.toString() == msg) done(); - else done(new Error("message content doesn't match:" + - msg + " =/= " + m.content.toString())); - }, {noAck: true, exclusive: true}); - ch.sendToQueue(q.queue, Buffer.from(msg)); - }); -}); - -channel_test('send to queue and consume ack', function(ch, done) { - var msg = randomString(); - ch.assertQueue('', {exclusive: true}, function(e, q) { - if (e !== null) return done(e); - ch.consume(q.queue, function(m) { - if (m.content.toString() == msg) { - ch.ack(m); - done(); - } - else done(new Error("message content doesn't match:" + - msg + " =/= " + m.content.toString())); - }, {noAck: false, exclusive: true}); - ch.sendToQueue(q.queue, Buffer.from(msg)); - }); -}); - -channel_test('send to and get from queue', function(ch, done) { - ch.assertQueue('', {exclusive: true}, function(e, q) { - if (e != null) return done(e); - var msg = randomString(); - ch.sendToQueue(q.queue, Buffer.from(msg)); - waitForMessages(ch, q.queue, function(e, _) { - if (e != null) return done(e); - ch.get(q.queue, {noAck: true}, function(e, m) { - if (e != null) - return done(e); - else if (!m) - return done(new Error('Empty (false) not expected')); - else if (m.content.toString() == msg) - return done(); - else - return done( - new Error('Messages do not match: ' + - msg + ' =/= ' + m.content.toString())); - }); - }); - }); -}); - -}); - -suite('ConfirmChannel', function() { - -confirm_channel_test('Receive confirmation', function(ch, done) { - // An unroutable message, on the basis that you're not allowed a - // queue with an empty name, and you can't make bindings to the - // default exchange. Tricky eh? - ch.publish('', '', Buffer.from('foo'), {}, done); -}); - -confirm_channel_test('Wait for confirms', function(ch, done) { - for (var i=0; i < 1000; i++) { - ch.publish('', '', Buffer.from('foo'), {}); - } - ch.waitForConfirms(done); -}); - -}); - -suite("Error handling", function() { - -/* -I don't like having to do this, but there appears to be something -broken about domains in Node.JS v0.8 and mocha. Apparently it has to -do with how mocha and domains hook into error propogation: -https://github.com/visionmedia/mocha/issues/513 (summary: domains in -Node.JS v0.8 don't prevent uncaughtException from firing, and that's -what mocha uses to detect .. an uncaught exception). - -Using domains with amqplib *does* work in practice in Node.JS v0.8: -that is, it's possible to throw an exception in a callback and deal -with it in the active domain, and thereby avoid it crashing the -program. - */ -if (util.versionGreaterThan(process.versions.node, '0.8')) { - test('Throw error in connection open callback', function(done) { - var dom = domain.createDomain(); - dom.on('error', failCallback(done)); - connect(dom.bind(function(err, conn) { - throw new Error('Spurious connection open callback error'); - })); - }); -} - -// TODO: refactor {error_test, channel_test} -function error_test(name, fun) { - test(name, function(done) { - var dom = domain.createDomain(); - dom.run(function() { - connect(kCallback(function(c) { - // Seems like there were some unironed wrinkles in 0.8's - // implementation of domains; explicitly adding the connection - // to the domain makes sure any exception thrown in the course - // of processing frames is handled by the domain. For other - // versions of Node.JS, this ends up being belt-and-braces. - dom.add(c); - c.createChannel(kCallback(function(ch) { - fun(ch, done, dom); - }, done)); - }, done)); - }); - }); -} - -error_test('Channel open callback throws an error', function(ch, done, dom) { - dom.on('error', failCallback(done)); - throw new Error('Error in open callback'); -}); - -error_test('RPC callback throws error', function(ch, done, dom) { - dom.on('error', failCallback(done)); - ch.prefetch(0, false, function(err, ok) { - throw new Error('Spurious callback error'); - }); -}); - -error_test('Get callback throws error', function(ch, done, dom) { - dom.on('error', failCallback(done)); - ch.assertQueue('test.cb.get-with-error', {}, function(err, ok) { - ch.get('test.cb.get-with-error', {noAck: true}, function() { - throw new Error('Spurious callback error'); - }); - }); -}); - -error_test('Consume callback throws error', function(ch, done, dom) { - dom.on('error', failCallback(done)); - ch.assertQueue('test.cb.consume-with-error', {}, function(err, ok) { - ch.consume('test.cb.consume-with-error', ignore, {noAck: true}, function() { - throw new Error('Spurious callback error'); - }); - }); -}); - -error_test('Get from non-queue invokes error k', function(ch, done, dom) { - var both = twice(failCallback(done)); - dom.on('error', both.first); - ch.get('', {}, both.second); -}); - -error_test('Consume from non-queue invokes error k', function(ch, done, dom) { - var both = twice(failCallback(done)); - dom.on('error', both.first); - ch.consume('', both.second); -}); - -}); diff --git a/node_modules/amqplib/test/channel.js b/node_modules/amqplib/test/channel.js deleted file mode 100644 index a8a5a05..0000000 --- a/node_modules/amqplib/test/channel.js +++ /dev/null @@ -1,612 +0,0 @@ -// Test the channel machinery - -'use strict'; - -var assert = require('assert'); -var Promise = require('bluebird'); -var Channel = require('../lib/channel').Channel; -var Connection = require('../lib/connection').Connection; -var util = require('./util'); -var succeed = util.succeed, fail = util.fail, latch = util.latch; -var completes = util.completes; -var defs = require('../lib/defs'); -var conn_handshake = require('./connection').connection_handshake; -var OPEN_OPTS = require('./connection').OPEN_OPTS; -var Buffer = require('safe-buffer').Buffer; - -var LOG_ERRORS = process.env.LOG_ERRORS; - -function baseChannelTest(client, server) { - return function(done) { - var bothDone = latch(2, done); - var pair = util.socketPair(); - var c = new Connection(pair.client); - - if (LOG_ERRORS) c.on('error', console.warn); - - c.open(OPEN_OPTS, function(err, ok) { - if (err === null) client(c, bothDone); - else fail(bothDone); - }); - - pair.server.read(8); // discard the protocol header - var s = util.runServer(pair.server, function(send, await) { - conn_handshake(send, await) - .then(function() { - server(send, await, bothDone); - }, fail(bothDone)); - }); - }; -} - -function channelTest(client, server) { - return baseChannelTest( - function(conn, done) { - var ch = new Channel(conn); - if (LOG_ERRORS) ch.on('error', console.warn); - client(ch, done, conn); - }, - function(send, await, done) { - channel_handshake(send, await) - .then(function(ch) { - return server(send, await, done, ch); - }).then(null, fail(done)); // so you can return a promise to let - // errors bubble out - } - ); -}; - -function channel_handshake(send, await) { - return await(defs.ChannelOpen)() - .then(function(open) { - assert.notEqual(0, open.channel); - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, open.channel); - return open.channel; - }); -} - -// fields for deliver and publish and get-ok -var DELIVER_FIELDS = { - consumerTag: 'fake', - deliveryTag: 1, - redelivered: false, - exchange: 'foo', - routingKey: 'bar', - replyCode: defs.constants.NO_ROUTE, - replyText: 'derp', -}; - -function open(ch) { - return Promise.try(function() { - ch.allocate(); - return Promise.fromCallback(function(cb) { - ch._rpc(defs.ChannelOpen, {outOfBand: ''}, defs.ChannelOpenOk, cb); - }); - }); -} - -suite("channel open and close", function() { - -test("open", channelTest( - function(ch, done) { - open(ch).then(succeed(done), fail(done)); - }, - function(send, await, done) { - done(); - })); - -test("bad server", baseChannelTest( - function(c, done) { - var ch = new Channel(c); - open(ch).then(fail(done), succeed(done)); - }, - function(send, await, done) { - return await(defs.ChannelOpen)() - .then(function(open) { - send(defs.ChannelCloseOk, {}, open.channel); - }).then(succeed(done), fail(done)); - })); - -test("open, close", channelTest( - function(ch, done) { - open(ch) - .then(function() { - return new Promise(function(resolve) { - ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS, resolve); - }); - }) - .then(succeed(done), fail(done)); - }, - function(send, await, done, ch) { - return await(defs.ChannelClose)() - .then(function(close) { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("server close", channelTest( - function(ch, done) { - ch.on('error', function(error) { - assert.strictEqual(504, error.code); - succeed(done)(); - }); - open(ch); - }, - function(send, await, done, ch) { - send(defs.ChannelClose, { - replyText: 'Forced close', - replyCode: defs.constants.CHANNEL_ERROR, - classId: 0, methodId: 0 - }, ch); - await(defs.ChannelCloseOk)() - .then(succeed(done), fail(done)); - })); - -test("overlapping channel/server close", channelTest( - function(ch, done, conn) { - var both = latch(2, done); - conn.on('error', succeed(both)); - ch.on('close', succeed(both)); - open(ch).then(function() { - ch.closeBecause("Bye", defs.constants.REPLY_SUCCESS); - }, fail(both)); - }, - function(send, await, done, ch) { - await(defs.ChannelClose)() - .then(function() { - send(defs.ConnectionClose, { - replyText: 'Got there first', - replyCode: defs.constants.INTERNAL_ERROR, - classId: 0, methodId: 0 - }, 0); - }) - .then(await(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - -test("double close", channelTest( - function(ch, done) { - open(ch).then(function() { - ch.closeBecause("First close", defs.constants.REPLY_SUCCESS); - // NB no synchronisation, we do this straight away - assert.throws(function() { - ch.closeBecause("Second close", defs.constants.REPLY_SUCCESS); - }); - }).then(succeed(done), fail(done)); - }, - function(send, await, done, ch) { - await(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, { - }, ch); - }) - .then(succeed(done), fail(done)); - })); - -}); //suite - -suite("channel machinery", function() { - -test("RPC", channelTest( - function(ch, done) { - var rpcLatch = latch(3, done); - open(ch).then(function() { - - function wheeboom(err, f) { - if (err !== null) rpcLatch(err); - else rpcLatch(); - } - - var fields = { - prefetchCount: 10, - prefetchSize: 0, - global: false - }; - - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - ch._rpc(defs.BasicQos, fields, defs.BasicQosOk, wheeboom); - }).then(null, fail(rpcLatch)); - }, - function(send, await, done, ch) { - function sendOk(f) { - send(defs.BasicQosOk, {}, ch); - } - - return await(defs.BasicQos)() - .then(sendOk) - .then(await(defs.BasicQos)) - .then(sendOk) - .then(await(defs.BasicQos)) - .then(sendOk) - .then(succeed(done), fail(done)); - })); - -test("Bad RPC", channelTest( - function(ch, done) { - // We want to see the RPC rejected and the channel closed (with an - // error) - var errLatch = latch(2, done); - ch.on('error', function(error) { - assert.strictEqual(505, error.code); - succeed(errLatch)(); - }); - - open(ch) - .then(function() { - ch._rpc(defs.BasicRecover, {requeue: true}, defs.BasicRecoverOk, - function(err) { - if (err !== null) errLatch(); - else errLatch(new Error('Expected RPC failure')); - }); - }, fail(errLatch)); - }, - function(send, await, done, ch) { - return await()() - .then(function() { - send(defs.BasicGetEmpty, {clusterId: ''}, ch); - }) // oh wait! that was wrong! expect a channel close - .then(await(defs.ChannelClose)) - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("RPC on closed channel", channelTest( - function(ch, done) { - open(ch); - - var close = new Promise(function(resolve) { - ch.on('error', function(error) { - assert.strictEqual(504, error.code); - resolve(); - }); - }); - - function failureCb(resolve, reject) { - return function(err) { - if (err !== null) resolve(); - else reject(); - } - } - - var fail1 = new Promise(function(resolve, reject) { - return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, - failureCb(resolve, reject)); - }); - - var fail2 = new Promise(function(resolve, reject) { - return ch._rpc(defs.BasicRecover, {requeue:true}, defs.BasicRecoverOk, - failureCb(resolve, reject)); - }); - - Promise.join(close, fail1, fail2) - .then(succeed(done)) - .catch(fail(done)); - }, - function(send, await, done, ch) { - await(defs.BasicRecover)() - .then(function() { - send(defs.ChannelClose, { - replyText: 'Nuh-uh!', - replyCode: defs.constants.CHANNEL_ERROR, - methodId: 0, classId: 0 - }, ch); - return await(defs.ChannelCloseOk); - }) - .then(succeed(done)) - .catch(fail(done)); - })); - -test("publish all < single chunk threshold", channelTest( - function(ch, done) { - open(ch) - .then(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.from('foobar')); - }) - .then(succeed(done), fail(done)); - }, - function(send, await, done, ch) { - await(defs.BasicPublish)() - .then(await(defs.BasicProperties)) - .then(await(undefined)) // content frame - .then(function(f) { - assert.equal('foobar', f.content.toString()); - }).then(succeed(done), fail(done)); - })); - -test("publish content > single chunk threshold", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(3000)); - }, done); - }, - function(send, await, done, ch) { - await(defs.BasicPublish)() - .then(await(defs.BasicProperties)) - .then(await(undefined)) // content frame - .then(function(f) { - assert.equal(3000, f.content.length); - }).then(succeed(done), fail(done)); - })); - -test("publish method & headers > threshold", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, { - headers: {foo: Buffer.alloc(3000)} - }, Buffer.from('foobar')); - }, done); - }, - function(send, await, done, ch) { - await(defs.BasicPublish)() - .then(await(defs.BasicProperties)) - .then(await(undefined)) // content frame - .then(function(f) { - assert.equal('foobar', f.content.toString()); - }).then(succeed(done), fail(done)); - })); - -test("publish zero-length message", channelTest( - function(ch, done) { - open(ch); - completes(function() { - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(0)); - ch.sendMessage({ - exchange: 'foo', routingKey: 'bar', - mandatory: false, immediate: false, ticket: 0 - }, {}, Buffer.alloc(0)); - }, done); - }, - function(send, await, done, ch) { - await(defs.BasicPublish)() - .then(await(defs.BasicProperties)) - // no content frame for a zero-length message - .then(await(defs.BasicPublish)) - .then(succeed(done), fail(done)); - })); - -test("delivery", channelTest( - function(ch, done) { - open(ch); - ch.on('delivery', function(m) { - completes(function() { - assert.equal('barfoo', m.content.toString()); - }, done); - }); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - }, done); - })); - -test("zero byte msg", channelTest( - function(ch, done) { - open(ch); - ch.on('delivery', function(m) { - completes(function() { - assert.deepEqual(Buffer.alloc(0), m.content); - }, done); - }); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('')); - }, done); - })); - -test("bad delivery", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('error', function(error) { - assert.strictEqual(505, error.code); - succeed(errorAndClose)(); - }); - ch.on('close', succeed(errorAndClose)); - open(ch); - }, - function(send, await, done, ch) { - send(defs.BasicDeliver, DELIVER_FIELDS, ch); - // now send another deliver without having sent the content - send(defs.BasicDeliver, DELIVER_FIELDS, ch); - return await(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("bad content send", channelTest( - function(ch, done) { - completes(function() { - open(ch); - assert.throws(function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {}, null); - }); - }, done); - }, - function(send, await, done, ch) { - done(); - })); - -test("bad properties send", channelTest( - function(ch, done) { - completes(function() { - open(ch); - assert.throws(function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {contentEncoding: 7}, - Buffer.from('foobar')); - }); - }, done); - }, - function(send, await, done, ch) { - done(); - })); - -test("bad consumer", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('delivery', function() { - throw new Error("I am a bad consumer"); - }); - ch.on('error', function(error) { - assert.strictEqual(541, error.code); - succeed(errorAndClose)(); - }); - ch.on('close', succeed(errorAndClose)); - open(ch); - }, - function(send, await, done, ch) { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - return await(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("bad send in consumer", channelTest( - function(ch, done) { - var errorAndClose = latch(2, done); - ch.on('close', succeed(errorAndClose)); - ch.on('error', function(error) { - assert.strictEqual(541, error.code); - succeed(errorAndClose)(); - }); - - ch.on('delivery', function() { - ch.sendMessage({routingKey: 'foo', - exchange: 'amq.direct'}, - {}, null); // can't send null - }); - - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicDeliver, DELIVER_FIELDS, ch, - Buffer.from('barfoo')); - }, done); - return await(defs.ChannelClose)() - .then(function() { - send(defs.ChannelCloseOk, {}, ch); - }).then(succeed(done), fail(done)); - })); - -test("return", channelTest( - function(ch, done) { - ch.on('return', function(m) { - completes(function() { - assert.equal('barfoo', m.content.toString()); - }, done); - }); - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicReturn, DELIVER_FIELDS, ch, Buffer.from('barfoo')); - }, done); - })); - -test("cancel", channelTest( - function(ch, done) { - ch.on('cancel', function(f) { - completes(function() { - assert.equal('product of society', f.consumerTag); - }, done); - }); - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicCancel, { - consumerTag: 'product of society', - nowait: false - }, ch); - }, done); - })); - -function confirmTest(variety, Method) { - return test('confirm ' + variety, channelTest( - function(ch, done) { - ch.on(variety, function(f) { - completes(function() { - assert.equal(1, f.deliveryTag); - }, done); - }); - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(Method, { - deliveryTag: 1, - multiple: false - }, ch); - }, done); - })); -} - -confirmTest("ack", defs.BasicAck); -confirmTest("nack", defs.BasicNack); - -test("out-of-order acks", channelTest( - function(ch, done) { - var allConfirms = latch(3, function() { - completes(function() { - assert.equal(0, ch.unconfirmed.length); - assert.equal(4, ch.lwm); - }, done); - }); - ch.pushConfirmCallback(allConfirms); - ch.pushConfirmCallback(allConfirms); - ch.pushConfirmCallback(allConfirms); - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 3, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); - }, done); - })); - -test("not all out-of-order acks", channelTest( - function(ch, done) { - var allConfirms = latch(2, function() { - completes(function() { - assert.equal(1, ch.unconfirmed.length); - assert.equal(3, ch.lwm); - }, done); - }); - ch.pushConfirmCallback(allConfirms); // tag = 1 - ch.pushConfirmCallback(allConfirms); // tag = 2 - ch.pushConfirmCallback(function() { - done(new Error('Confirm callback should not be called')); - }); - open(ch); - }, - function(send, await, done, ch) { - completes(function() { - send(defs.BasicAck, {deliveryTag: 2, multiple: false}, ch); - send(defs.BasicAck, {deliveryTag: 1, multiple: false}, ch); - }, done); - })); - -}); diff --git a/node_modules/amqplib/test/channel_api.js b/node_modules/amqplib/test/channel_api.js deleted file mode 100644 index 99c9f9c..0000000 --- a/node_modules/amqplib/test/channel_api.js +++ /dev/null @@ -1,584 +0,0 @@ -'use strict'; - -var assert = require('assert'); -var api = require('../channel_api'); -var util = require('./util'); -var succeed = util.succeed, fail = util.fail; -var schedule = util.schedule; -var randomString = util.randomString; -var Promise = require('bluebird'); -var Buffer = require('safe-buffer').Buffer; - -var URL = process.env.URL || 'amqp://localhost'; - -function connect() { - return api.connect(URL); -} - -// Expect this promise to fail, and flip the results accordingly. -function expectFail(promise) { - return new Promise(function(resolve, reject) { - return promise.then(reject).catch(resolve); - }); -} - -// I'll rely on operations being rejected, rather than the channel -// close error, to detect failure. -function ignore () {} -function ignoreErrors(c) { - c.on('error', ignore); return c; -} -function logErrors(c) { - c.on('error', console.warn); return c; -} - -// Run a test with `name`, given a function that takes an open -// channel, and returns a promise that is resolved on test success or -// rejected on test failure. -function channel_test(chmethod, name, chfun) { - test(name, function(done) { - connect(URL).then(logErrors).then(function(c) { - c[chmethod]().then(ignoreErrors).then(chfun) - .then(succeed(done), fail(done)) - // close the connection regardless of what happens with the test - .finally(function() {c.close();}); - }); - }); -} - -var chtest = channel_test.bind(null, 'createChannel'); - -suite("connect", function() { - -test("at all", function(done) { - connect(URL).then(function(c) { - return c.close() - ;}).then(succeed(done), fail(done)); -}); - -chtest("create channel", ignore); // i.e., just don't bork - -}); - -var QUEUE_OPTS = {durable: false}; -var EX_OPTS = {durable: false}; - -suite("assert, check, delete", function() { - -chtest("assert and check queue", function(ch) { - return ch.assertQueue('test.check-queue', QUEUE_OPTS) - .then(function(qok) { - return ch.checkQueue('test.check-queue'); - }); -}); - -chtest("assert and check exchange", function(ch) { - return ch.assertExchange('test.check-exchange', 'direct', EX_OPTS) - .then(function(eok) { - assert.equal('test.check-exchange', eok.exchange); - return ch.checkExchange('test.check-exchange'); - }); -}); - -chtest("fail on reasserting queue with different options", - function(ch) { - var q = 'test.reassert-queue'; - return ch.assertQueue( - q, {durable: false, autoDelete: true}) - .then(function() { - return expectFail( - ch.assertQueue(q, {durable: false, - autoDelete: false})); - }); - }); - -chtest("fail on checking a queue that's not there", function(ch) { - return expectFail(ch.checkQueue('test.random-' + randomString())); -}); - -chtest("fail on checking an exchange that's not there", function(ch) { - return expectFail(ch.checkExchange('test.random-' + randomString())); -}); - -chtest("fail on reasserting exchange with different type", - function(ch) { - var ex = 'test.reassert-ex'; - return ch.assertExchange(ex, 'fanout', EX_OPTS) - .then(function() { - return expectFail( - ch.assertExchange(ex, 'direct', EX_OPTS)); - }); - }); - -chtest("channel break on publishing to non-exchange", function(ch) { - return new Promise(function(resolve) { - ch.on('error', resolve); - ch.publish(randomString(), '', Buffer.from('foobar')); - }); -}); - -chtest("delete queue", function(ch) { - var q = 'test.delete-queue'; - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), - ch.checkQueue(q)) - .then(function() { - return ch.deleteQueue(q);}) - .then(function() { - return expectFail(ch.checkQueue(q));}); -}); - -chtest("delete exchange", function(ch) { - var ex = 'test.delete-exchange'; - return Promise.join( - ch.assertExchange(ex, 'fanout', EX_OPTS), - ch.checkExchange(ex)) - .then(function() { - return ch.deleteExchange(ex);}) - .then(function() { - return expectFail(ch.checkExchange(ex));}); -}); - -}); - -// Wait for the queue to meet the condition; useful for waiting for -// messages to arrive, for example. -function waitForQueue(q, condition) { - return connect(URL).then(function(c) { - return c.createChannel() - .then(function(ch) { - return ch.checkQueue(q).then(function(qok) { - function check() { - return ch.checkQueue(q).then(function(qok) { - if (condition(qok)) { - c.close(); - return qok; - } - else schedule(check); - }); - } - return check(); - }); - }); - }); -} - -// Return a promise that resolves when the queue has at least `num` -// messages. If num is not supplied its assumed to be 1. -function waitForMessages(q, num) { - var min = (num === undefined) ? 1 : num; - return waitForQueue(q, function(qok) { - return qok.messageCount >= min; - }); -} - -suite("sendMessage", function() { - -// publish different size messages -chtest("send to queue and get from queue", function(ch) { - var q = 'test.send-to-q'; - var msg = randomString(); - return Promise.join(ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) - .then(function() { - ch.sendToQueue(q, Buffer.from(msg)); - return waitForMessages(q); - }) - .then(function() { - return ch.get(q, {noAck: true}); - }) - .then(function(m) { - assert(m); - assert.equal(msg, m.content.toString()); - }); -}); - -chtest("send (and get) zero content to queue", function(ch) { - var q = 'test.send-to-q'; - var msg = Buffer.alloc(0); - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q)) - .then(function() { - ch.sendToQueue(q, msg); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: true});}) - .then(function(m) { - assert(m); - assert.deepEqual(msg, m.content); - }); -}); - -}); - -suite("binding, consuming", function() { - -// bind, publish, get -chtest("route message", function(ch) { - var ex = 'test.route-message'; - var q = 'test.route-message-q'; - var msg = randomString(); - - return Promise.join( - ch.assertExchange(ex, 'fanout', EX_OPTS), - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - ch.bindQueue(q, ex, '', {})) - .then(function() { - ch.publish(ex, '', Buffer.from(msg)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: true});}) - .then(function(m) { - assert(m); - assert.equal(msg, m.content.toString()); - }); -}); - -// send to queue, purge, get-empty -chtest("purge queue", function(ch) { - var q = 'test.purge-queue'; - return ch.assertQueue(q, {durable: false}) - .then(function() { - ch.sendToQueue(q, Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { - ch.purgeQueue(q); - return ch.get(q, {noAck: true});}) - .then(function(m) { - assert(!m); // get-empty - }); -}); - -// bind again, unbind, publish, get-empty -chtest("unbind queue", function(ch) { - var ex = 'test.unbind-queue-ex'; - var q = 'test.unbind-queue'; - var viabinding = randomString(); - var direct = randomString(); - - return Promise.join( - ch.assertExchange(ex, 'fanout', EX_OPTS), - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - ch.bindQueue(q, ex, '', {})) - .then(function() { - ch.publish(ex, '', Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { // message got through! - return ch.get(q, {noAck:true}) - .then(function(m) {assert(m);});}) - .then(function() { - return ch.unbindQueue(q, ex, '', {});}) - .then(function() { - // via the no-longer-existing binding - ch.publish(ex, '', Buffer.from(viabinding)); - // direct to the queue - ch.sendToQueue(q, Buffer.from(direct)); - return waitForMessages(q);}) - .then(function() {return ch.get(q)}) - .then(function(m) { - // the direct to queue message got through, the via-binding - // message (sent first) did not - assert.equal(direct, m.content.toString()); - }); -}); - -// To some extent this is now just testing semantics of the server, -// but we can at least try out a few settings, and consume. -chtest("consume via exchange-exchange binding", function(ch) { - var ex1 = 'test.ex-ex-binding1', ex2 = 'test.ex-ex-binding2'; - var q = 'test.ex-ex-binding-q'; - var rk = 'test.routing.key', msg = randomString(); - return Promise.join( - ch.assertExchange(ex1, 'direct', EX_OPTS), - ch.assertExchange(ex2, 'fanout', - {durable: false, internal: true}), - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - ch.bindExchange(ex2, ex1, rk, {}), - ch.bindQueue(q, ex2, '', {})) - .then(function() { - return new Promise(function(resolve, reject) { - function delivery(m) { - if (m.content.toString() === msg) resolve(); - else reject(new Error("Wrong message")); - } - ch.consume(q, delivery, {noAck: true}) - .then(function() { - ch.publish(ex1, rk, Buffer.from(msg)); - }); - }); - }); -}); - -// bind again, unbind, publish, get-empty -chtest("unbind exchange", function(ch) { - var source = 'test.unbind-ex-source'; - var dest = 'test.unbind-ex-dest'; - var q = 'test.unbind-ex-queue'; - var viabinding = randomString(); - var direct = randomString(); - - return Promise.join( - ch.assertExchange(source, 'fanout', EX_OPTS), - ch.assertExchange(dest, 'fanout', EX_OPTS), - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - ch.bindExchange(dest, source, '', {}), - ch.bindQueue(q, dest, '', {})) - .then(function() { - ch.publish(source, '', Buffer.from('foobar')); - return waitForMessages(q);}) - .then(function() { // message got through! - return ch.get(q, {noAck:true}) - .then(function(m) {assert(m);});}) - .then(function() { - return ch.unbindExchange(dest, source, '', {});}) - .then(function() { - // via the no-longer-existing binding - ch.publish(source, '', Buffer.from(viabinding)); - // direct to the queue - ch.sendToQueue(q, Buffer.from(direct)); - return waitForMessages(q);}) - .then(function() {return ch.get(q)}) - .then(function(m) { - // the direct to queue message got through, the via-binding - // message (sent first) did not - assert.equal(direct, m.content.toString()); - }); -}); - -// This is a bit convoluted. Sorry. -chtest("cancel consumer", function(ch) { - var q = 'test.consumer-cancel'; - var ctag; - var recv1 = new Promise(function (resolve, reject) { - Promise.join( - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q), - // My callback is 'resolve the promise in `arrived`' - ch.consume(q, resolve, {noAck:true}) - .then(function(ok) { - ctag = ok.consumerTag; - ch.sendToQueue(q, Buffer.from('foo')); - })); - }); - - // A message should arrive because of the consume - return recv1.then(function() { - var recv2 = Promise.join( - ch.cancel(ctag).then(function() { - return ch.sendToQueue(q, Buffer.from('bar')); - }), - // but check a message did arrive in the queue - waitForMessages(q)) - .then(function() { - return ch.get(q, {noAck:true}); - }) - .then(function(m) { - // I'm going to reject it, because I flip succeed/fail - // just below - if (m.content.toString() === 'bar') { - throw new Error(); - } - }); - - return expectFail(recv2); - }); -}); - -chtest("cancelled consumer", function(ch) { - var q = 'test.cancelled-consumer'; - return new Promise(function(resolve, reject) { - return Promise.join( - ch.assertQueue(q), - ch.purgeQueue(q), - ch.consume(q, function(msg) { - if (msg === null) resolve(); - else reject(new Error('Message not expected')); - })) - .then(function() { - return ch.deleteQueue(q); - }); - }); -}); - -// ack, by default, removes a single message from the queue -chtest("ack", function(ch) { - var q = 'test.ack'; - var msg1 = randomString(), msg2 = randomString(); - - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), - ch.purgeQueue(q)) - .then(function() { - ch.sendToQueue(q, Buffer.from(msg1)); - ch.sendToQueue(q, Buffer.from(msg2)); - return waitForMessages(q, 2); - }) - .then(function() { - return ch.get(q, {noAck: false}) - }) - .then(function(m) { - assert.equal(msg1, m.content.toString()); - ch.ack(m); - // %%% is there a race here? may depend on - // rabbitmq-sepcific semantics - return ch.get(q); - }) - .then(function(m) { - assert(m); - assert.equal(msg2, m.content.toString()); - }); -}); - -// Nack, by default, puts a message back on the queue (where in the -// queue is up to the server) -chtest("nack", function(ch) { - var q = 'test.nack'; - var msg1 = randomString(); - - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) - .then(function() { - ch.sendToQueue(q, Buffer.from(msg1)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: false})}) - .then(function(m) { - assert.equal(msg1, m.content.toString()); - ch.nack(m); - return waitForMessages(q);}) - .then(function() { - return ch.get(q);}) - .then(function(m) { - assert(m); - assert.equal(msg1, m.content.toString()); - }); -}); - -// reject is a near-synonym for nack, the latter of which is not -// available in earlier RabbitMQ (or in AMQP proper). -chtest("reject", function(ch) { - var q = 'test.reject'; - var msg1 = randomString(); - - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) - .then(function() { - ch.sendToQueue(q, Buffer.from(msg1)); - return waitForMessages(q);}) - .then(function() { - return ch.get(q, {noAck: false})}) - .then(function(m) { - assert.equal(msg1, m.content.toString()); - ch.reject(m); - return waitForMessages(q);}) - .then(function() { - return ch.get(q);}) - .then(function(m) { - assert(m); - assert.equal(msg1, m.content.toString()); - }); -}); - -chtest("prefetch", function(ch) { - var q = 'test.prefetch'; - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q), - ch.prefetch(1)) - .then(function() { - ch.sendToQueue(q, Buffer.from('foobar')); - ch.sendToQueue(q, Buffer.from('foobar')); - return waitForMessages(q, 2); - }) - .then(function() { - return new Promise(function(resolve) { - var messageCount = 0; - function receive(msg) { - ch.ack(msg); - if (++messageCount > 1) { - resolve(messageCount); - } - } - return ch.consume(q, receive, {noAck: false}) - }); - }) - .then(function(c) { - return assert.equal(2, c); - }); -}); - -chtest('close', function(ch) { - // Resolving promise guarantees - // channel is closed - return ch.close(); -}); - -}); - -var confirmtest = channel_test.bind(null, 'createConfirmChannel'); - -suite("confirms", function() { - -confirmtest('message is confirmed', function(ch) { - var q = 'test.confirm-message'; - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) - .then(function() { - return ch.sendToQueue(q, Buffer.from('bleep')); - }); -}); - -// Usually one can provoke the server into confirming more than one -// message in an ack by simply sending a few messages in quick -// succession; a bit unscientific I know. Luckily we can eavesdrop on -// the acknowledgements coming through to see if we really did get a -// multi-ack. -confirmtest('multiple confirms', function(ch) { - var q = 'test.multiple-confirms'; - return Promise.join( - ch.assertQueue(q, QUEUE_OPTS), ch.purgeQueue(q)) - .then(function() { - var multipleRainbows = false; - ch.on('ack', function(a) { - if (a.multiple) multipleRainbows = true; - }); - - function prod(num) { - var cs = []; - - function sendAndPushPromise() { - var conf = Promise.fromCallback(function(cb) { - return ch.sendToQueue(q, Buffer.from('bleep'), {}, cb); - }); - cs.push(conf); - } - - for (var i=0; i < num; i++) sendAndPushPromise(); - - return Promise.all(cs).then(function() { - if (multipleRainbows) return true; - else if (num > 500) throw new Error( - "Couldn't provoke the server" + - " into multi-acking with " + num + - " messages; giving up"); - else { - //console.warn("Failed with " + num + "; trying " + num * 2); - return prod(num * 2); - } - }); - } - return prod(5); - }); -}); - -confirmtest('wait for confirms', function(ch) { - for (var i=0; i < 1000; i++) { - ch.publish('', '', Buffer.from('foobar'), {}); - } - return ch.waitForConfirms(); -}) - -}); diff --git a/node_modules/amqplib/test/codec.js b/node_modules/amqplib/test/codec.js deleted file mode 100644 index 55a326f..0000000 --- a/node_modules/amqplib/test/codec.js +++ /dev/null @@ -1,238 +0,0 @@ -'use strict'; - -var codec = require('../lib/codec'); -var defs = require('../lib/defs'); -var assert = require('assert'); -var ints = require('buffer-more-ints'); -var Buffer = require('safe-buffer').Buffer -var C = require('claire'); -var forAll = C.forAll; - -// These just test known encodings; to generate the answers I used -// RabbitMQ's binary generator module. - -var testCases = [ - // integers - ['byte', {byte: 112}, [4,98,121,116,101,98,112]], - ['byte max value', {byte: 127}, [4,98,121,116,101,98,127]], - ['byte min value', {byte: -128}, [4,98,121,116,101,98,128]], - ['< -128 promoted to signed short', {short: -129}, [5,115,104,111,114,116,115,255,127]], - ['> 127 promoted to short', {short: 128}, [5,115,104,111,114,116,115,0,128]], - ['< 2^15 still a short', {short: 0x7fff}, [5,115,104,111,114,116,115,127,255]], - ['-2^15 still a short', {short: -0x8000}, [5,115,104,111,114,116,115,128,0]], - ['>= 2^15 promoted to int', {int: 0x8000}, [3,105,110,116,73,0,0,128,0]], - ['< -2^15 promoted to int', {int: -0x8001}, [3,105,110,116,73,255,255,127,255]], - ['< 2^31 still an int', {int: 0x7fffffff}, [3,105,110,116,73,127,255,255,255]], - ['>= -2^31 still an int', {int: -0x80000000}, [3,105,110,116,73,128,0,0,0]], - ['>= 2^31 promoted to long', {long: 0x80000000}, [4,108,111,110,103,108,0,0,0,0,128,0,0,0]], - ['< -2^31 promoted to long', {long: -0x80000001}, [4,108,111,110,103,108,255,255,255,255,127,255,255,255]], - - // floating point - ['float value', {double: 0.5}, [6,100,111,117,98,108,101,100,63,224,0,0,0,0,0,0]], - ['negative float value', {double: -0.5}, [6,100,111,117,98,108,101,100,191,224,0,0,0,0,0,0]], - // %% test some boundaries of precision? - - // string - ['string', {string: "boop"}, [6,115,116,114,105,110,103,83,0,0,0,4,98,111,111,112]], - - // buffer -> byte array - ['byte array from buffer', {bytes: Buffer.from([1,2,3,4])}, - [5,98,121,116,101,115,120,0,0,0,4,1,2,3,4]], - - // boolean, void - ['true', {bool: true}, [4,98,111,111,108,116,1]], - ['false', {bool: false}, [4,98,111,111,108,116,0]], - ['null', {'void': null}, [4,118,111,105,100,86]], - - // array, object - ['array', {array: [6, true, "foo"]}, - [5,97,114,114,97,121,65,0,0,0,12,98,6,116,1,83,0,0,0,3,102,111,111]], - ['object', {object: {foo: "bar", baz: 12}}, - [6,111,98,106,101,99,116,70,0,0,0,18,3,102,111,111,83,0, - 0,0,3,98,97,114,3,98,97,122,98,12]], - - // exotic types - ['timestamp', {timestamp: {'!': 'timestamp', value: 1357212277527}}, - [9,116,105,109,101,115,116,97,109,112,84,0,0,1,60,0,39,219,23]], - ['decimal', {decimal: {'!': 'decimal', value: {digits: 2345, places: 2}}}, - [7,100,101,99,105,109,97,108,68,2,0,0,9,41]], - ['float', {float: {'!': 'float', value: 0.1}}, - [5,102,108,111,97,116,102,61,204,204,205]], -]; - -function bufferToArray(b) { - return Array.prototype.slice.call(b); -} - -suite("Implicit encodings", function() { - - testCases.forEach(function(tc) { - var name = tc[0], val = tc[1], expect = tc[2]; - test(name, function() { - var buffer = Buffer.alloc(1000); - var size = codec.encodeTable(buffer, val, 0); - var result = buffer.slice(4, size); - assert.deepEqual(expect, bufferToArray(result)); - }); - }); -}); - -// Whole frames - -var amqp = require('./data'); - -function roundtrip_table(t) { - var buf = Buffer.alloc(4096); - var size = codec.encodeTable(buf, t, 0); - var decoded = codec.decodeFields(buf.slice(4, size)); // ignore the length-prefix - try { - assert.deepEqual(removeExplicitTypes(t), decoded); - } - catch (e) { return false; } - return true; -} - -function roundtrips(T) { - return forAll(T).satisfy(function(v) { return roundtrip_table({value: v}); }); -} - -suite("Roundtrip values", function() { - [ - amqp.Octet, - amqp.ShortStr, - amqp.LongStr, - amqp.UShort, - amqp.ULong, - amqp.ULongLong, - amqp.UShort, - amqp.Short, - amqp.Long, - amqp.Bit, - amqp.Decimal, - amqp.Timestamp, - amqp.Double, - amqp.Float, - amqp.FieldArray, - amqp.FieldTable - ].forEach(function(T) { - test(T.toString() + ' roundtrip', roundtrips(T).asTest()); - }); -}); - -// When encoding, you can supply explicitly-typed fields like `{'!': -// int32, 50}`. Most of these do not appear in the decoded values, so -// to compare like-to-like we have to remove them from the input. -function removeExplicitTypes(input) { - switch (typeof input) { - case 'object': - if (input == null) { - return null; - } - if (Array.isArray(input)) { - var newArr = []; - for (var i = 0; i < input.length; i++) { - newArr[i] = removeExplicitTypes(input[i]); - } - return newArr; - } - if (Buffer.isBuffer(input)) { - return input; - } - switch (input['!']) { - case 'timestamp': - case 'decimal': - case 'float': - return input; - case undefined: - var newObj = {} - for (var k in input) { - newObj[k] = removeExplicitTypes(input[k]); - } - return newObj; - default: - return input.value; - } - - default: - return input; - } -} - -// Asserts that the decoded fields are equal to the original fields, -// or equal to a default where absent in the original. The defaults -// depend on the type of method or properties. -// -// This works slightly different for methods and properties: for -// methods, each field must have a value, so the default is -// substituted for undefined values when encoding; for properties, -// fields may be absent in the encoded value, so a default is -// substituted for missing fields when decoding. The effect is the -// same so far as these tests are concerned. -function assertEqualModuloDefaults(original, decodedFields) { - var args = defs.info(original.id).args; - for (var i=0; i < args.length; i++) { - var arg = args[i]; - var originalValue = original.fields[arg.name]; - var decodedValue = decodedFields[arg.name]; - try { - if (originalValue === undefined) { - // longstr gets special treatment here, since the defaults are - // given as strings rather than buffers, but the decoded values - // will be buffers. - assert.deepEqual((arg.type === 'longstr') ? - Buffer.from(arg.default) : arg.default, - decodedValue); - } - else { - assert.deepEqual(removeExplicitTypes(originalValue), decodedValue); - } - } - catch (assertionErr) { - var methodOrProps = defs.info(original.id).name; - assertionErr.message += ' (frame ' + methodOrProps + - ' field ' + arg.name + ')'; - throw assertionErr; - } - } - // %%% TODO make sure there's no surplus fields - return true; -} - -// This is handy for elsewhere -module.exports.assertEqualModuloDefaults = assertEqualModuloDefaults; - -function roundtripMethod(Method) { - return forAll(Method).satisfy(function(method) { - var buf = defs.encodeMethod(method.id, 0, method.fields); - // FIXME depends on framing, ugh - var fs1 = defs.decode(method.id, buf.slice(11, buf.length)); - assertEqualModuloDefaults(method, fs1); - return true; - }); -} - -function roundtripProperties(Properties) { - return forAll(Properties).satisfy(function(properties) { - var buf = defs.encodeProperties(properties.id, 0, properties.size, - properties.fields); - // FIXME depends on framing, ugh - var fs1 = defs.decode(properties.id, buf.slice(19, buf.length)); - assert.equal(properties.size, ints.readUInt64BE(buf, 11)); - assertEqualModuloDefaults(properties, fs1); - return true; - }); -} - -suite("Roundtrip methods", function() { - amqp.methods.forEach(function(Method) { - test(Method.toString() + ' roundtrip', - roundtripMethod(Method).asTest()); - }); -}); - -suite("Roundtrip properties", function() { - amqp.properties.forEach(function(Properties) { - test(Properties.toString() + ' roundtrip', - roundtripProperties(Properties).asTest()); - }); -}); diff --git a/node_modules/amqplib/test/connect.js b/node_modules/amqplib/test/connect.js deleted file mode 100644 index 277c364..0000000 --- a/node_modules/amqplib/test/connect.js +++ /dev/null @@ -1,127 +0,0 @@ -'use strict'; - -var connect = require('../lib/connect').connect; -var Buffer = require('safe-buffer').Buffer -var credentialsFromUrl = require('../lib/connect').credentialsFromUrl; -var assert = require('assert'); -var util = require('./util'); -var net = require('net'); -var fail = util.fail, succeed = util.succeed, - kCallback = util.kCallback, - succeedIfAttributeEquals = util.succeedIfAttributeEquals; -var format = require('util').format; - -var URL = process.env.URL || 'amqp://localhost'; - -suite("Credentials", function() { - - function checkCreds(creds, user, pass, done) { - if (creds.mechanism != 'PLAIN') { - return done('expected mechanism PLAIN'); - } - if (creds.username != user || creds.password != pass) { - return done(format("expected '%s', '%s'; got '%s', '%s'", - user, pass, creds.username, creds.password)); - } - done(); - } - - test("no creds", function(done) { - var parts = {auth: ''}; - var creds = credentialsFromUrl(parts); - checkCreds(creds, 'guest', 'guest', done); - }); - test("usual user:pass", function(done) { - var parts = {auth: 'user:pass'}; - var creds = credentialsFromUrl(parts); - checkCreds(creds, 'user', 'pass', done); - }); - test("missing user", function(done) { - var parts = {auth: ':password'}; - var creds = credentialsFromUrl(parts); - checkCreds(creds, '', 'password', done); - }); - test("missing password", function(done) { - var parts = {auth: 'username'}; - var creds = credentialsFromUrl(parts); - checkCreds(creds, 'username', '', done); - }); - test("colon in password", function(done) { - var parts = {auth: 'username:pass:word'}; - var creds = credentialsFromUrl(parts); - checkCreds(creds, 'username', 'pass:word', done); - }); -}); - -suite("Connect API", function() { - - test("Connection refused", function(done) { - connect('amqp://localhost:23450', {}, - kCallback(fail(done), succeed(done))); - }); - - // %% this ought to fail the promise, rather than throwing an error - test("bad URL", function() { - assert.throws(function() { - connect('blurble'); - }); - }); - - test("wrongly typed open option", function(done) { - var url = require('url'); - var parts = url.parse(URL, true); - var q = parts.query || {}; - q.frameMax = 'NOT A NUMBER'; - parts.query = q; - var u = url.format(parts); - connect(u, {}, kCallback(fail(done), succeed(done))); - }); - - test("using custom heartbeat option", function(done) { - var url = require('url'); - var parts = url.parse(URL, true); - var config = parts.query || {}; - config.heartbeat = 20; - connect(config, {}, kCallback(succeedIfAttributeEquals('heartbeat', 20, done), fail(done))); - }); - - test("wrongly typed heartbeat option", function(done) { - var url = require('url'); - var parts = url.parse(URL, true); - var config = parts.query || {}; - config.heartbeat = 'NOT A NUMBER'; - connect(config, {}, kCallback(fail(done), succeed(done))); - }); - - test("using plain credentials", function(done) { - var url = require('url'); - var parts = url.parse(URL, true); - var u = 'guest', p = 'guest'; - if (parts.auth) { - var auth = parts.auth.split(":"); - u = auth[0], p = auth[1]; - } - connect(URL, {credentials: require('../lib/credentials').plain(u, p)}, - kCallback(succeed(done), fail(done))); - }); - - test("using unsupported mechanism", function(done) { - var creds = { - mechanism: 'UNSUPPORTED', - response: function() { return Buffer.from(''); } - }; - connect(URL, {credentials: creds}, - kCallback(fail(done), succeed(done))); - }); - - test("with a given connection timeout", function(done) { - var timeoutServer = net.createServer(function() {}).listen(31991); - - connect('amqp://localhost:31991', {timeout: 50}, function(err, val) { - timeoutServer.close(); - if (val) done(new Error('Expected connection timeout, did not')); - else done(); - }); - }); - -}); diff --git a/node_modules/amqplib/test/connection.js b/node_modules/amqplib/test/connection.js deleted file mode 100644 index cec3c3d..0000000 --- a/node_modules/amqplib/test/connection.js +++ /dev/null @@ -1,391 +0,0 @@ -'use strict'; - -var assert = require('assert'); -var defs = require('../lib/defs'); -var Buffer = require('safe-buffer').Buffer; -var Connection = require('../lib/connection').Connection; -var HEARTBEAT = require('../lib/frame').HEARTBEAT; -var HB_BUF = require('../lib/frame').HEARTBEAT_BUF; -var util = require('./util'); -var succeed = util.succeed, fail = util.fail, latch = util.latch; -var completes = util.completes; -var kCallback = util.kCallback; - -var LOG_ERRORS = process.env.LOG_ERRORS; - -var OPEN_OPTS = { - // start-ok - 'clientProperties': {}, - 'mechanism': 'PLAIN', - 'response': Buffer.from(['', 'guest', 'guest'].join(String.fromCharCode(0))), - 'locale': 'en_US', - - // tune-ok - 'channelMax': 0, - 'frameMax': 0, - 'heartbeat': 0, - - // open - 'virtualHost': '/', - 'capabilities': '', - 'insist': 0 -}; -module.exports.OPEN_OPTS = OPEN_OPTS; - -function happy_open(send, await) { - // kick it off - send(defs.ConnectionStart, - {versionMajor: 0, - versionMinor: 9, - serverProperties: {}, - mechanisms: Buffer.from('PLAIN'), - locales: Buffer.from('en_US')}); - return await(defs.ConnectionStartOk)() - .then(function(f) { - send(defs.ConnectionTune, - {channelMax: 0, - heartbeat: 0, - frameMax: 0}); - }) - .then(await(defs.ConnectionTuneOk)) - .then(await(defs.ConnectionOpen)) - .then(function(f) { - send(defs.ConnectionOpenOk, - {knownHosts: ''}); - }); -} -module.exports.connection_handshake = happy_open; - -function connectionTest(client, server) { - return function(done) { - var bothDone = latch(2, done); - var pair = util.socketPair(); - var c = new Connection(pair.client); - if (LOG_ERRORS) c.on('error', console.warn); - client(c, bothDone); - - // NB only not a race here because the writes are synchronous - var protocolHeader = pair.server.read(8); - assert.deepEqual(Buffer.from("AMQP" + String.fromCharCode(0,0,9,1)), - protocolHeader); - - var s = util.runServer(pair.server, function(send, await) { - server(send, await, bothDone, pair.server); - }); - }; -} - -suite("Connection errors", function() { - - test("socket close during open", function(done) { - // RabbitMQ itself will take at least 3 seconds to close the socket - // in the event of a handshake problem. Instead of using a live - // connection, I'm just going to pretend. - var pair = util.socketPair(); - var conn = new Connection(pair.client); - pair.server.on('readable', function() { - pair.server.end(); - }); - conn.open({}, kCallback(fail(done), succeed(done))); - }); - - test("bad frame during open", function(done) { - var ss = util.socketPair(); - var conn = new (require('../lib/connection').Connection)(ss.client); - ss.server.on('readable', function() { - ss.server.write(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); - }); - conn.open({}, kCallback(fail(done), succeed(done))); - }); - -}); - -suite("Connection open", function() { - -test("happy", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(succeed(done), fail(done))); - }, - function(send, await, done) { - happy_open(send, await).then(succeed(done), fail(done)); - })); - -test("wrong first frame", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); - }, - function(send, await, done) { - // bad server! bad! whatever were you thinking? - completes(function() { - send(defs.ConnectionTune, - {channelMax: 0, - heartbeat: 0, - frameMax: 0}); - }, done); - })); - -test("unexpected socket close", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(fail(done), succeed(done))); - }, - function(send, await, done, socket) { - send(defs.ConnectionStart, - {versionMajor: 0, - versionMinor: 9, - serverProperties: {}, - mechanisms: Buffer.from('PLAIN'), - locales: Buffer.from('en_US')}); - return await(defs.ConnectionStartOk)() - .then(function() { - socket.end(); - }) - .then(succeed(done), fail(done)); - })); - -}); - -suite("Connection running", function() { - -test("wrong frame on channel 0", connectionTest( - function(c, done) { - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done) { - happy_open(send, await) - .then(function() { - // there's actually nothing that would plausibly be sent to a - // just opened connection, so this is violating more than one - // rule. Nonetheless. - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 0); - }) - .then(await(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}, 0); - }).then(succeed(done), fail(done)); - })); - -test("unopened channel", connectionTest( - function(c, done) { - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done) { - happy_open(send, await) - .then(function() { - // there's actually nothing that would plausibly be sent to a - // just opened connection, so this is violating more than one - // rule. Nonetheless. - send(defs.ChannelOpenOk, {channelId: Buffer.from('')}, 3); - }) - .then(await(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}, 0); - }).then(succeed(done), fail(done)); - })); - -test("unexpected socket close", connectionTest( - function(c, done) { - var errorAndClosed = latch(2, done); - c.on('error', succeed(errorAndClosed)); - c.on('close', succeed(errorAndClosed)); - c.open(OPEN_OPTS, kCallback(function() { - c.sendHeartbeat(); - }, fail(errorAndClosed))); - }, - function(send, await, done, socket) { - happy_open(send, await) - .then(await()) - .then(function() { - socket.end(); - }).then(succeed(done)); - })); - -test("connection.blocked", connectionTest( - function(c, done) { - c.on('blocked', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done, socket) { - happy_open(send, await) - .then(function() { - send(defs.ConnectionBlocked, {reason: 'felt like it'}, 0); - }) - .then(succeed(done)); - })); - -test("connection.unblocked", connectionTest( - function(c, done) { - c.on('unblocked', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done, socket) { - happy_open(send, await) - .then(function() { - send(defs.ConnectionUnblocked, {}, 0); - }) - .then(succeed(done)); - })); - - -}); - -suite("Connection close", function() { - -test("happy", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', done); - c.open(OPEN_OPTS, kCallback(function(_ok) { - c.close(kCallback(succeed(done), fail(done))); - }, function() {})); - }, - function(send, await, done) { - happy_open(send, await) - .then(await(defs.ConnectionClose)) - .then(function(close) { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - -test("interleaved close frames", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', done); - c.open(OPEN_OPTS, kCallback(function(_ok) { - c.close(kCallback(succeed(done), fail(done))); - }, done)); - }, - function(send, await, done) { - happy_open(send, await) - .then(await(defs.ConnectionClose)) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Ha!", - replyCode: defs.constants.REPLY_SUCCESS, - methodId: 0, classId: 0 - }); - }) - .then(await(defs.ConnectionCloseOk)) - .then(function(f) { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - -test("server error close", connectionTest( - function(c, done0) { - var done = latch(2, done0); - c.on('close', succeed(done)); - c.on('error', succeed(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done) { - happy_open(send, await) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Begone", - replyCode: defs.constants.INTERNAL_ERROR, - methodId: 0, classId: 0 - }); - }) - .then(await(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - -test("operator-intiated close", connectionTest( - function(c, done) { - c.on('close', succeed(done)); - c.on('error', fail(done)); - c.open(OPEN_OPTS); - }, - function(send, await, done) { - happy_open(send, await) - .then(function(f) { - send(defs.ConnectionClose, { - replyText: "Begone", - replyCode: defs.constants.CONNECTION_FORCED, - methodId: 0, classId: 0 - }); - }) - .then(await(defs.ConnectionCloseOk)) - .then(succeed(done), fail(done)); - })); - - -test("double close", connectionTest( - function(c, done) { - c.open(OPEN_OPTS, kCallback(function() { - c.close(); - // NB no synchronisation, we do this straight away - assert.throws(function() { - c.close(); - }); - done(); - }, done)); - }, - function(send, await, done) { - happy_open(send, await) - .then(await(defs.ConnectionClose)) - .then(function() { - send(defs.ConnectionCloseOk, {}); - }) - .then(succeed(done), fail(done)); - })); - -}); - -suite("heartbeats", function() { - -var heartbeat = require('../lib/heartbeat'); - -setup(function() { - heartbeat.UNITS_TO_MS = 20; -}); - -teardown(function() { - heartbeat.UNITS_TO_MS = 1000; -}); - -test("send heartbeat after open", connectionTest( - function(c, done) { - completes(function() { - var opts = Object.create(OPEN_OPTS); - opts.heartbeat = 1; - // Don't leave the error waiting to happen for the next test, this - // confuses mocha awfully - c.on('error', function() {}); - c.open(opts); - }, done); - }, - function(send, await, done, socket) { - var timer; - happy_open(send, await) - .then(function() { - timer = setInterval(function() { - socket.write(HB_BUF); - }, heartbeat.UNITS_TO_MS); - }) - .then(await()) - .then(function(hb) { - if (hb === HEARTBEAT) done(); - else done("Next frame after silence not a heartbeat"); - clearInterval(timer); - }); - })); - -test("detect lack of heartbeats", connectionTest( - function(c, done) { - var opts = Object.create(OPEN_OPTS); - opts.heartbeat = 1; - c.on('error', succeed(done)); - c.open(opts); - }, - function(send, await, done, socket) { - happy_open(send, await) - .then(succeed(done), fail(done)); - // conspicuously not sending anything ... - })); - -}); diff --git a/node_modules/amqplib/test/data.js b/node_modules/amqplib/test/data.js deleted file mode 100644 index 2fa9bf0..0000000 --- a/node_modules/amqplib/test/data.js +++ /dev/null @@ -1,255 +0,0 @@ -// Property-based testing representations of various things in AMQP - -'use strict'; - -var C = require('claire'); -var Buffer = require('safe-buffer').Buffer; -var forAll = C.forAll; -var arb = C.data; -var transform = C.transform; -var repeat = C.repeat; -var label = C.label; -var sequence = C.sequence; -var asGenerator = C.asGenerator; -var sized = C.sized; -var recursive = C.recursive; -var choice = C.choice; -var Undefined = C.Undefined; - -// Stub these out so we can use outside tests -// if (!suite) var suite = function() {} -// if (!test) var test = function() {} - -// These aren't exported in claire/index. so I could have to reproduce -// them I guess. -function choose(a, b) { - return Math.random() * (b - a) + a; -} - -function chooseInt(a, b) { - return Math.floor(choose(a, b)); -} - -function rangeInt(name, a, b) { - return label(name, - asGenerator(function(_) { return chooseInt(a, b); })); -} - -function toFloat32(i) { - var b = Buffer.alloc(4); - b.writeFloatBE(i, 0); - return b.readFloatBE(0); -} - -function floatChooser(maxExp) { - return function() { - var n = Number.NaN; - while (isNaN(n)) { - var mantissa = Math.random() * 2 - 1; - var exponent = chooseInt(0, maxExp); - n = Math.pow(mantissa, exponent); - } - return n; - } -} - -function explicitType(t, underlying) { - return label(t, transform(function(n) { - return {'!': t, value: n}; - }, underlying)); -} - -// FIXME null, byte array, others? - -var Octet = rangeInt('octet', 0, 255); -var ShortStr = label('shortstr', - transform(function(s) { - return s.substr(0, 255); - }, arb.Str)); - -var LongStr = label('longstr', - transform( - function(bytes) { return Buffer.from(bytes); }, - repeat(Octet))); - -var UShort = rangeInt('short-uint', 0, 0xffff); -var ULong = rangeInt('long-uint', 0, 0xffffffff); -var ULongLong = rangeInt('longlong-uint', 0, 0xffffffffffffffff); -var Short = rangeInt('short-int', -0x8000, 0x7fff); -var Long = rangeInt('long-int', -0x80000000, 0x7fffffff); -var LongLong = rangeInt('longlong-int', -0x8000000000000000, - 0x7fffffffffffffff); -var Bit = label('bit', arb.Bool); -var Double = label('double', asGenerator(floatChooser(308))); -var Float = label('float', transform(toFloat32, floatChooser(38))); -var Timestamp = label('timestamp', transform( - function(n) { - return {'!': 'timestamp', value: n}; - }, ULongLong)); -var Decimal = label('decimal', transform( - function(args) { - return {'!': 'decimal', value: {places: args[1], digits: args[0]}}; - }, sequence(arb.UInt, Octet))); - -// Signed 8 bit int -var Byte = rangeInt('byte', -128, 127); - -// Explicitly typed values -var ExByte = explicitType('byte', Byte); -var ExInt8 = explicitType('int8', Byte); -var ExShort = explicitType('short', Short); -var ExInt16 = explicitType('int16', Short); -var ExInt = explicitType('int', Long); -var ExInt32 = explicitType('int32', Long); -var ExLong = explicitType('long', LongLong); -var ExInt64 = explicitType('int64', LongLong); - -var FieldArray = label('field-array', recursive(function() { - return arb.Array( - arb.Null, - LongStr, ShortStr, - Octet, UShort, ULong, ULongLong, - Byte, Short, Long, LongLong, - ExByte, ExInt8, ExShort, ExInt16, - ExInt, ExInt32, ExLong, ExInt64, - Bit, Float, Double, FieldTable, FieldArray) -})); - -var FieldTable = label('table', recursive(function() { - return sized(function() { return 5; }, - arb.Object( - arb.Null, - LongStr, ShortStr, Octet, - UShort, ULong, ULongLong, - Byte, Short, Long, LongLong, - ExByte, ExInt8, ExShort, ExInt16, - ExInt, ExInt32, ExLong, ExInt64, - Bit, Float, Double, FieldArray, FieldTable)) -})); - -// Internal tests of our properties -var domainProps = [ - [Octet, function(n) { return n >= 0 && n < 256; }], - [ShortStr, function(s) { return typeof s === 'string' && s.length < 256; }], - [LongStr, function(s) { return Buffer.isBuffer(s); }], - [UShort, function(n) { return n >= 0 && n <= 0xffff; }], - [ULong, function(n) { return n >= 0 && n <= 0xffffffff; }], - [ULongLong, function(n) { - return n >= 0 && n <= 0xffffffffffffffff; }], - [Short, function(n) { return n >= -0x8000 && n <= 0x8000; }], - [Long, function(n) { return n >= -0x80000000 && n < 0x80000000; }], - [LongLong, function(n) { return n >= -0x8000000000000000 && n < 0x8000000000000000; }], - [Bit, function(b) { return typeof b === 'boolean'; }], - [Double, function(f) { return !isNaN(f) && isFinite(f); }], - [Float, function(f) { return !isNaN(f) && isFinite(f) && (Math.log(Math.abs(f)) * Math.LOG10E) < 309; }], - [Decimal, function(d) { - return d['!'] === 'decimal' && - d.value['places'] <= 255 && - d.value['digits'] <= 0xffffffff; - }], - [Timestamp, function(t) { return t['!'] === 'timestamp'; }], - [FieldTable, function(t) { return typeof t === 'object'; }], - [FieldArray, function(a) { return Array.isArray(a); }] -]; - -suite("Domains", function() { - domainProps.forEach(function(p) { - test(p[0] + ' domain', - forAll(p[0]).satisfy(p[1]).asTest({times: 500})); - }); -}); - -// For methods and properties (as opposed to field table values) it's -// easier just to accept and produce numbers for timestamps. -var ArgTimestamp = label('timestamp', ULongLong); - -// These are the domains used in method arguments -var ARG_TYPES = { - 'octet': Octet, - 'shortstr': ShortStr, - 'longstr': LongStr, - 'short': UShort, - 'long': ULong, - 'longlong': ULongLong, - 'bit': Bit, - 'table': FieldTable, - 'timestamp': ArgTimestamp -}; - -function argtype(thing) { - if (thing.default === undefined) { - return ARG_TYPES[thing.type]; - } - else { - return choice(ARG_TYPES[thing.type], Undefined); - } -} - -function zipObject(vals, names) { - var obj = {}; - vals.forEach(function(v, i) { obj[names[i]] = v; }); - return obj; -} - -function name(arg) { return arg.name; } - -var defs = require('../lib/defs'); - -function method(info) { - var domain = sequence.apply(null, info.args.map(argtype)); - var names = info.args.map(name); - return label(info.name, transform(function(fieldVals) { - return {id: info.id, - fields: zipObject(fieldVals, names)}; - }, domain)); -} - -function properties(info) { - var types = info.args.map(argtype); - types.unshift(ULongLong); // size - var domain = sequence.apply(null, types); - var names = info.args.map(name); - return label(info.name, transform(function(fieldVals) { - return {id: info.id, - size: fieldVals[0], - fields: zipObject(fieldVals.slice(1), names)}; - }, domain)); -} - -var methods = []; -var propertieses = []; - -for (var k in defs) { - if (k.substr(0, 10) === 'methodInfo') { - methods.push(method(defs[k])); - methods[defs[k].name] = method(defs[k]); - } - else if (k.substr(0, 14) === 'propertiesInfo') { - propertieses.push(properties(defs[k])); - propertieses[defs[k].name] = properties(defs[k]); - } -}; - -module.exports = { - Octet: Octet, - ShortStr: ShortStr, - LongStr: LongStr, - UShort: UShort, - ULong: ULong, - ULongLong: ULongLong, - Short: Short, - Long: Long, - LongLong: LongLong, - Bit: Bit, - Double: Double, - Float: Float, - Timestamp: Timestamp, - Decimal: Decimal, - FieldArray: FieldArray, - FieldTable: FieldTable, - - methods: methods, - properties: propertieses -}; - -module.exports.rangeInt = rangeInt; diff --git a/node_modules/amqplib/test/frame.js b/node_modules/amqplib/test/frame.js deleted file mode 100644 index 26ac3b1..0000000 --- a/node_modules/amqplib/test/frame.js +++ /dev/null @@ -1,199 +0,0 @@ -'use strict'; - -var assert = require('assert'); -var succeed = require('./util').succeed; -var fail = require('./util').fail; -var Buffer = require('safe-buffer').Buffer; -var connection = require('../lib/connection'); -var Frames = connection.Connection; -var HEARTBEAT = require('../lib/frame').HEARTBEAT; -var Stream = require('stream'); -var PassThrough = Stream.PassThrough || - require('readable-stream/passthrough'); - -var defs = require('../lib/defs'); - -// We'll need to supply a stream which we manipulate ourselves - -function inputs() { - // don't coalesce buffers, since that could mess up properties - // (e.g., encoded frame size) - return new PassThrough({objectMode: true}); -} - -var HB = Buffer.from([defs.constants.FRAME_HEARTBEAT, - 0, 0, // channel 0 - 0, 0, 0, 0, // zero size - defs.constants.FRAME_END]); - -suite("Explicit parsing", function() { - - test('Parse heartbeat', function() { - var input = inputs(); - var frames = new Frames(input); - input.write(HB); - assert(frames.recvFrame() === HEARTBEAT); - assert(!frames.recvFrame()); - }); - - test('Parse partitioned', function() { - var input = inputs(); - var frames = new Frames(input); - input.write(HB.slice(0, 3)); - assert(!frames.recvFrame()); - input.write(HB.slice(3)); - assert(frames.recvFrame() === HEARTBEAT); - assert(!frames.recvFrame()); - }); - - function testBogusFrame(name, bytes) { - test(name, function(done) { - var input = inputs(); - var frames = new Frames(input); - frames.frameMax = 5; //for the max frame test - input.write(Buffer.from(bytes)); - frames.step(function(err, frame) { - if (err != null) done(); - else done(new Error('Was a bogus frame!')); - }); - }); - } - - testBogusFrame('Wrong sized frame', - [defs.constants.FRAME_BODY, - 0,0, 0,0,0,0, // zero length - 65, // but a byte! - defs.constants.FRAME_END]); - - testBogusFrame('Unknown method frame', - [defs.constants.FRAME_METHOD, - 0,0, 0,0,0,4, - 0,0,0,0, // garbage ID - defs.constants.FRAME_END]); - - testBogusFrame('> max frame', - [defs.constants.FRAME_BODY, - 0,0, 0,0,0,6, // too big! - 65,66,67,68,69,70, - defs.constants.FRAME_END]); - -}); - -// Now for a bit more fun. - -var amqp = require('./data'); -var claire = require('claire'); -var choice = claire.choice; -var forAll = claire.forAll; -var repeat = claire.repeat; -var label = claire.label; -var sequence = claire.sequence; -var transform = claire.transform; -var sized = claire.sized; - -var assertEqualModuloDefaults = - require('./codec').assertEqualModuloDefaults; - -var Trace = label('frame trace', - repeat(choice.apply(choice, amqp.methods))); - -suite("Parsing", function() { - - function testPartitioning(partition) { - return forAll(Trace).satisfy(function(t) { - var bufs = []; - var input = inputs(); - var frames = new Frames(input); - var i = 0, ex; - frames.accept = function(f) { - // A minor hack to make sure we get the assertion exception; - // otherwise, it's just a test that we reached the line - // incrementing `i` for each frame. - try { - assertEqualModuloDefaults(t[i], f.fields); - } - catch (e) { - ex = e; - } - i++; - }; - - t.forEach(function(f) { - f.channel = 0; - bufs.push(defs.encodeMethod(f.id, 0, f.fields)); - }); - - partition(bufs).forEach(input.write.bind(input)); - frames.acceptLoop(); - if (ex) throw ex; - return i === t.length; - }).asTest({times: 20}) - }; - - test("Parse trace of methods", - testPartitioning(function(bufs) { return bufs; })); - - test("Parse concat'd methods", - testPartitioning(function(bufs) { - return [Buffer.concat(bufs)]; - })); - - test("Parse partitioned methods", - testPartitioning(function(bufs) { - var full = Buffer.concat(bufs); - var onethird = Math.floor(full.length / 3); - var twothirds = 2 * onethird; - return [ - full.slice(0, onethird), - full.slice(onethird, twothirds), - full.slice(twothirds) - ]; - })); -}); - -var FRAME_MAX_MAX = 4096 * 4; -var FRAME_MAX_MIN = 4096; - -var FrameMax = amqp.rangeInt('frame max', - FRAME_MAX_MIN, - FRAME_MAX_MAX); - -var Body = sized(function(_n) { - return Math.floor(Math.random() * FRAME_MAX_MAX); -}, repeat(amqp.Octet)); - -var Content = transform(function(args) { - return { - method: args[0].fields, - header: args[1].fields, - body: Buffer.from(args[2]) - } -}, sequence(amqp.methods['BasicDeliver'], - amqp.properties['BasicProperties'], Body)); - -suite("Content framing", function() { - test("Adhere to frame max", - forAll(Content, FrameMax).satisfy(function(content, max) { - var input = inputs(); - var frames = new Frames(input); - frames.frameMax = max; - frames.sendMessage( - 0, - defs.BasicDeliver, content.method, - defs.BasicProperties, content.header, - content.body); - var f, i = 0, largest = 0; - while (f = input.read()) { - i++; - if (f.length > largest) largest = f.length; - if (f.length > max) { - return false; - } - } - // The ratio of frames to 'contents' should always be >= 2 - // (one properties frame and at least one content frame); > 2 - // indicates fragmentation. The largest is always, of course <= frame max - //console.log('Frames: %d; frames per message: %d; largest frame %d', i, i / t.length, largest); - return true; - }).asTest()); -}); diff --git a/node_modules/amqplib/test/mux.js b/node_modules/amqplib/test/mux.js deleted file mode 100644 index fef6e13..0000000 --- a/node_modules/amqplib/test/mux.js +++ /dev/null @@ -1,166 +0,0 @@ -'use strict'; - -var assert = require('assert'); -var Mux = require('../lib/mux').Mux; -var PassThrough = require('stream').PassThrough || - require('readable-stream/passthrough'); - -var latch = require('./util').latch; -var schedule = require('./util').schedule; - -function stream() { - return new PassThrough({objectMode: true}); -} - -function readAllObjects(s, cb) { - var objs = []; - - function read() { - var v = s.read(); - while (v !== null) { - objs.push(v); - v = s.read(); - } - } - - s.on('end', function() { cb(objs); }); - s.on('readable', read); - - read(); -} - -test("single input", function(done) { - var input = stream(); - var output = stream(); - input.on('end', function() { output.end() }); - - var mux = new Mux(output); - mux.pipeFrom(input); - - var data = [1,2,3,4,5,6,7,8,9]; - // not 0, it's treated specially by PassThrough for some reason. By - // 'specially' I mean it breaks the stream. See e.g., - // https://github.com/isaacs/readable-stream/pull/55 - data.forEach(input.write.bind(input)); - - readAllObjects(output, function(vals) { - assert.deepEqual(data, vals); - done(); - }); - - input.end(); -}); - -test("two sequential inputs", function(done) { - var input1 = stream(); - var input2 = stream(); - var output = stream(); - var mux = new Mux(output); - mux.pipeFrom(input1); - mux.pipeFrom(input2); - - var data = [1,2,3,4,5,6,7,8,9]; - data.forEach(function(v) { input1.write(v); }); - - input1.on('end', function() { - data.forEach(function (v) { input2.write(v); }); - input2.end(); - }); - input2.on('end', function() { output.end(); }); - - input1.end(); - readAllObjects(output, function(vs) { - assert.equal(2 * data.length, vs.length); - done(); - }); -}); - -test("two interleaved inputs", function(done) { - var input1 = stream(); - var input2 = stream(); - var output = stream(); - var mux = new Mux(output); - mux.pipeFrom(input1); - mux.pipeFrom(input2); - - var endLatch = latch(2, function() { output.end(); }); - input1.on('end', endLatch); - input2.on('end', endLatch); - - var data = [1,2,3,4,5,6,7,8,9]; - data.forEach(function(v) { input1.write(v); }); - input1.end(); - - data.forEach(function(v) { input2.write(v); }); - input2.end(); - - readAllObjects(output, function(vs) { - assert.equal(2 * data.length, vs.length); - done(); - }); -}); - -test("unpipe", function(done) { - var input = stream(); - var output = stream(); - var mux = new Mux(output); - - var pipedData = [1,2,3,4,5]; - var unpipedData = [6,7,8,9]; - - mux.pipeFrom(input); - - schedule(function() { - pipedData.forEach(input.write.bind(input)); - mux.unpipeFrom(input); - - schedule(function() { - unpipedData.forEach(input.write.bind(input)); - input.end(); - schedule(function() { - // exhaust so that 'end' fires - var v; while (v = input.read()); - }); - }); - }); - - input.on('end', function() { - output.end(); - }); - - readAllObjects(output, function(vals) { - try { - assert.deepEqual(pipedData, vals); - done(); - } - catch (e) { done(e); } - }); -}); - -test("roundrobin", function(done) { - var input1 = stream(); - var input2 = stream(); - var output = stream(); - var mux = new Mux(output); - - mux.pipeFrom(input1); - mux.pipeFrom(input2); - - var endLatch = latch(2, function() { output.end(); }); - input1.on('end', endLatch); - input2.on('end', endLatch); - - var ones = [1,1,1,1,1]; - ones.forEach(function(v) { input1.write(v); }); - input1.end(); - - var twos = [2,2,2,2,2]; - twos.forEach(function(v) { input2.write(v); }); - input2.end(); - - readAllObjects(output, function(vs) { - assert.deepEqual([1,2,1,2,1,2,1,2,1,2], vs); - done(); - }); - -}); diff --git a/node_modules/amqplib/test/util.js b/node_modules/amqplib/test/util.js deleted file mode 100644 index 0617ca9..0000000 --- a/node_modules/amqplib/test/util.js +++ /dev/null @@ -1,220 +0,0 @@ -'use strict'; - -var Promise = require('bluebird'); -var crypto = require('crypto'); -var Connection = require('../lib/connection').Connection; -var PassThrough = - require('stream').PassThrough || - require('readable-stream/passthrough'); -var defs = require('../lib/defs'); -var assert = require('assert'); - -var schedule = (typeof setImmediate === 'function') ? - setImmediate : process.nextTick; - -function randomString() { - var hash = crypto.createHash('sha1'); - hash.update(crypto.randomBytes(64)); - return hash.digest('base64'); -} - - -// Set up a socket pair {client, server}, such that writes to the -// client are readable from the server, and writes to the server are -// readable at the client. -// -// +---+ +---+ -// | C | | S | -// --write->| l |----->| e |--read--> -// | i | | r | -// <--read--| e |<-----| v |<-write-- -// | n | | e | -// | t | | r | -// +---+ +---+ -// -// I also need to make sure that end called on either socket affects -// the other. - -function socketPair() { - var server = new PassThrough(); - var client = new PassThrough(); - server.write = client.push.bind(client); - client.write = server.push.bind(server); - function end(chunk, encoding) { - if (chunk) this.push(chunk, encoding); - this.push(null); - } - server.end = end.bind(client); - client.end = end.bind(server); - - return {client: client, server: server}; -} - -function runServer(socket, run) { - var frames = new Connection(socket); - // We will be closing the socket without doing a closing handshake, - // so cheat - frames.expectSocketClose = true; - // We also need to create some channel buffers, again a cheat - frames.freshChannel(null); - frames.freshChannel(null); - frames.freshChannel(null); - - function send(id, fields, channel, content) { - channel = channel || 0; - if (content) { - schedule(function() { - frames.sendMessage(channel, id, fields, - defs.BasicProperties, fields, - content); - }); - } - else { - schedule(function() { - frames.sendMethod(channel, id, fields); - }); - } - } - - function await(method) { - return function() { - return new Promise(function(resolve, reject) { - if (method) { - frames.step(function(e, f) { - if (e !== null) return reject(e); - if (f.id === method) - resolve(f); - else - reject(new Error("Expected method: " + method + - ", got " + f.id)); - }); - } - else { - frames.step(function(e, f) { - if (e !== null) return reject(e); - else resolve(f); - }); - } - }); - }; - } - run(send, await); - return frames; -} - -// Produce a callback that will complete the test successfully -function succeed(done) { - return function() { done(); } -} - -// Produce a callback that will complete the test successfully -// only if the value is an object, it has the specified -// attribute, and its value is equals to the expected value -function succeedIfAttributeEquals(attribute, value, done) { - return function(object) { - if (object && !(object instanceof Error) && value === object[attribute]) { - return done(); - } - - done(new Error(attribute + " is not equal to " + value)); - }; -} - -// Produce a callback that will fail the test, given either an error -// (to be used as a failure continuation) or any other value (to be -// used as a success continuation when failure is expected) -function fail(done) { - return function(err) { - if (err instanceof Error) done(err); - else done(new Error("Expected to fail, instead got " + err.toString())); - } -} - -// Create a function that will call done once it's been called itself -// `count` times. If it's called with an error value, it will -// immediately call done with that error value. -function latch(count, done) { - var awaiting = count; - var alive = true; - return function(err) { - if (err instanceof Error && alive) { - alive = false; - done(err); - } - else { - awaiting--; - if (awaiting === 0 && alive) { - alive = false; - done(); - } - } - }; -} - -// Call a thunk with a continuation that will be called with an error -// if the thunk throws one, or nothing if it runs to completion. -function completes(thunk, done) { - try { - thunk(); - done(); - } - catch (e) { done(e); } -} - -// Construct a Node.JS-style callback from a success continuation and -// an error continuation -function kCallback(k, ek) { - return function(err, val) { - if (err === null) k && k(val); - else ek && ek(err); - }; -} - -// A noddy way to make tests depend on the node version. -function versionGreaterThan(actual, spec) { - - function int(e) { return parseInt(e); } - - var version = actual.split('.').map(int); - var desired = spec.split('.').map(int); - for (var i=0; i < desired.length; i++) { - var a = version[i], b = desired[i]; - if (a != b) return a > b; - } - return false; -} - -suite('versionGreaterThan', function() { - -test('full spec', function() { - assert(versionGreaterThan('0.8.26', '0.6.12')); - assert(versionGreaterThan('0.8.26', '0.8.21')); -}); - -test('partial spec', function() { - assert(versionGreaterThan('0.9.12', '0.8')); -}); - -test('not greater', function() { - assert(!versionGreaterThan('0.8.12', '0.8.26')); - assert(!versionGreaterThan('0.6.2', '0.6.12')); - assert(!versionGreaterThan('0.8.29', '0.8')); -}); - -test - -}); - -module.exports = { - socketPair: socketPair, - runServer: runServer, - succeed: succeed, - succeedIfAttributeEquals: succeedIfAttributeEquals, - fail: fail, - latch: latch, - completes: completes, - kCallback: kCallback, - schedule: schedule, - randomString: randomString, - versionGreaterThan: versionGreaterThan -}; diff --git a/node_modules/bitsyntax/.npmignore b/node_modules/bitsyntax/.npmignore deleted file mode 100644 index 40338d5..0000000 --- a/node_modules/bitsyntax/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -sketches -*~ -scratch diff --git a/node_modules/bitsyntax/.travis.yml b/node_modules/bitsyntax/.travis.yml deleted file mode 100644 index 2b0d3cb..0000000 --- a/node_modules/bitsyntax/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js - -node_js: - - "0.10" - - "0.8" - - "0.6" - - "0.11" diff --git a/node_modules/bitsyntax/Makefile b/node_modules/bitsyntax/Makefile deleted file mode 100644 index ee27ab8..0000000 --- a/node_modules/bitsyntax/Makefile +++ /dev/null @@ -1,15 +0,0 @@ -.PHONY: test all - -GRAMMAR=lib/grammar.pegjs -PEGJS=./node_modules/.bin/pegjs - -all: lib/parser.js - -lib/parser.js: $(PEGJS) - $(PEGJS) $(GRAMMAR) $@ - -$(PEGJS): - npm install - -test: lib/parser.js - ./node_modules/.bin/mocha --check-leaks -R list -u tdd test/*.js diff --git a/node_modules/bitsyntax/README.md b/node_modules/bitsyntax/README.md deleted file mode 100644 index 02eed9b..0000000 --- a/node_modules/bitsyntax/README.md +++ /dev/null @@ -1,306 +0,0 @@ -# Byte-wise matching for Node.JS - -[![Build Status](https://travis-ci.org/squaremo/bitsyntax-js.png?branch=master)](https://travis-ci.org/squaremo/bitsyntax-js) - -Gives a compact syntax for parsing and constructing byte buffers, -derived from [Erlang's bit -syntax](http://www.erlang.org/doc/programming_examples/bit_syntax.html#id64858). - -```js -var bitsyntax = require('bitsyntax'); -var pattern = bitsyntax.matcher('len:8/integer, str:len/binary'); -var bound = pattern(new Buffer([4, 0x41, 0x42, 0x43, 0x44])); -bound.str -// => -``` - -A typical use of this is parsing byte streams from sockets. For -example, size-prefixed frames: - -```js -var framePattern = bitsyntax.matcher('len:32/integer, frame:len/binary, rest/binary'); -socket.on('data', function process(data) { - var m; - if (m = framePattern(data)) { - emit('frame', m.frame); - process(m.rest); - } - else { - stashForNextData(data); - } -}); -``` - -Patterns can also be used to construct byte buffers from supplied -values: - -```js -var spdyDataFrame = require('bitsyntax') - .builder('streamId:32, flags:8, length:24, data/binary'); - -spdyDataFrame({streamId:5, flags:0, length:bin.length, data:bin}); -``` - -One or more segments of a pattern may also be supplied in multiple -arguments, if that is more convenient; this makes it easier to split a -long pattern over lines: - -```js -var p = bitsyntax.matcher('size:8, payload:size/binary', - 'rest/binary'); -``` - -## API - -### `matcher` - -Compiles a pattern as a string (or strings), to a function that will -return either a map of bindings, or `false`, given a buffer and -optionally an environment. The environment contains values for bound -variables in the pattern (if there are any). - -```js -var p = bitsyntax.matcher('header:headerSize/binary, rest/binary'); -var b = p(new Buffer([1, 2, 3, 4, 5]), {headerSize: 3}); -b.header -// => -``` - -A matcher will return `false` if the supplied buffer does not match -the pattern; for example, if it has too few bytes, or a literal is not -present. - -```js -var p = bitsyntax.matcher('"foo=", str/binary'); -p(new Buffer("bar=humbug")); -// => false -``` - -### `parse` and `match` - -When composed, equivalent to `matcher`; may be useful if you want to -examine the internal structure of patterns. - -`parse` takes strings as for `matcher`, and returns the internal -representation of the pattern. `match` takes this representation, a -buffer, and optionally an environment, and returns the bindings or -`false` (as with `matcher`). - -```js -var p = bitsyntax.parse('header:headerSize/binary', - 'rest/binary'); -var b = bitsyntax.match(p, new Buffer([1, 2, 3, 4, 5]), - {headerSize: 3}); -b.header -// => -``` - -### `builder` - -Takes a pattern and returns a function that will construct a byte -buffer, given values for the variables mentioned in the pattern. - -```js -var cons = bitsyntax.builder('size:8, bin/binary'); -cons({size:6, bin:new Buffer('foobar')}); -// => -``` - -Patterns supplied to builders are slightly different to patterns -supplied for matching, as noted below. - -### `build` - -Takes a parsed pattern and a map of variable values, and returns a -buffer. As with `match`, may be useful to debug patterns. - -```js -var pattern = bitsyntax.parse('size:8, bin:size/binary'); -bitsyntax.build(pattern, {size:6, bin: new Buffer('foobar')}); -// => -``` - -### `write` - -Writes variable values into a buffer, at an offset, according to the -parsed pattern given. Returns the finishing offset, i.e., the supplied -offset plus the number of bytes written. - -```js -var pattern = bitsyntax.parse('size:8, bin/binary'); -var buf = new Buffer(7); -bitsyntax.write(buf, 0, pattern, - {size:6, bin: new Buffer('foobar')}); -// => 7 -buf -// => -``` - -## Patterns - -Patterns are sequences of segments, each matching a value. Segments -have the general form - - value:size/type_specifier_list - -The size and type specifier list may be omitted, giving three extra -variations: - - value - value:size - value/type_specifier_list - -The type specifier list is a list of keywords separated by -hyphens. Type specifiers are described below. - -Patterns are generally supplied as strings, with a comma-separated -series of segments. - -### Variable or value - -The first part of a segment gives a variable name or a literal -value. If a variable name is given, the value matched by the segment -will be bound to that variable name for the rest of the pattern. If a -literal value is given, the matched value must equal that value. If a -variable's value is given in the environment, the matched value must -equal the provided value. - -When used in a builder, the literal value will be copied into the -buffer according to the type it is given. A variable name indicates a -slot into which a value supplied to the builder will be copied. - -The special variable name `_` discards the value matched; i.e., it -simply skips over the appropriate number of bits in the input. '_' is -not allowed in builder patterns. - -### Size and unit - -The size of a segment is given following the value or variable, -separated with a colon: - - foo:32 - -The unit is given in the list of specifiers as `'unit' and -an integer from 0..256, separated by a colon: - - foo:4/integer-unit:8 - -The size is the number of units in the value; the unit is given as a -number of bits. Unit can be of use, for example, when you want to -match integers of a number of bytes rather than a number of bits. - -For integers and floats, the default unit is 1 bit; to keep things -aligned on byte boundaries, `unit * size` must currently be a multiple -of 8. For binaries the default unit is 8, and the unit must be a -multiple of 8. - -If the size is omitted and the type is integer, the size defaults to -8. If the size is omitted and the type is binary, the segment will -match all remaining bytes in the input; such a segment may only be -used at the end of a pattern, when matching. - -The size may also be given as an integer variable matched earlier in -the pattern, as in the example given at the top. When constructing, a -size may be a variable referring to the supplied environment. - -In builders, numbers will be rounded, masked or padded to fit the size -and units given; for example, `'256:8'` gives the binary `Buffer<00>` -because the lowest eight bits are 0; `'255:16` gives the binary -`Buffer<00 ff>`. - -### Type name specifier - -One of `integer`, `binary`, `string`, `float`. If not given, the -default is `integer`. - -An integer is a big- or little-endian, signed or unsigned -integer. Integers up to 32 bits are supported. Signed integers are -two's complement format. In JavaScript, only integers between -(2^53) -and 2^53 can be represented, and bitwise operators are only defined on -32-bit signed integers. - -A binary is simply a byte buffer; usually this will result in a slice -of the input buffer being returned, so beware mutation. - -A string is a UTF8 string consisting of the given number of bytes. - -A float is a 32- or 64-bit IEEE754 floating-point value (this is the -standard JavaScript uses, as do Java and Erlang). - -### Endianness specifier - -Integers may be big- or little-endian; this refers to which 'end' of -the bytes making up the integer are most significant. In network -protocols integers are usually big-endian, meaning the first -(left-most) byte is the most significant, but this is not always the -case. - -A specifier of `big` means the integer will be parsed (or written into -the result) as big-endian, and `little` means the integer will be -parsed or written as little-endian. The default is big-endian. - -### Signedness specifier - -Integer segments may include a specifier of `signed` or `unsigned`. A -signed integer is parsed as two's complement format. The default is -unsigned. - -Signedness is ignored in builders. - -### Literal strings - -A quoted string appearing in a pattern is a shorthand for the bytes in -its UTF8 encoding. For example, - - "foobar", _/binary - -matches any buffer that starts with the bytes `0x66, 0x6f, 0x6f, 0x62, -0x61, 0x72`. - -When used in a builder, a quoted string is copied into the result as -the bytes of its UTF8 encoding. - -## Examples - -In the following the matched bytes are given in array notation for -convenience. Bear in mind that `match()` actually takes a buffer for -the bytes to match against. The phrase "returns X as Y" or "binds X as -Y" means the return value is an object with value X mapped to the key -Y. - - 54 - -Matches the single byte `54`. - - 54:32 - -Matches the bytes [0,0,0,54]. - - 54:32/little - -Matches the bytes [54,0,0,0]. - - 54:4/unit:8 - -Matches the bytes [0,0,0,54]. - - int:32/signed - -Matches a binary of four bytes, and returns a signed 32-bit integer as -`int`. - - len:16, str:len/binary - -Matches a binary of `2 + len` bytes, and returns an unsigned 16-bit -integer as `len` and a buffer of length `len` as `str`. - - len:16, _:len/binary, rest/binary - -Matches a binary of at least `2 + len` bytes, binds an unsigned 16-bit -integer as `len`, ignores the next `len` bytes, and binds the -remaining (possibly zero-length) binary as `rest`. - - s:8, key:s/binary, value/binary - -When given the environment `{s:6, key: "foobar"}`, will match a binary -starting with [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, ...]. diff --git a/node_modules/bitsyntax/index.js b/node_modules/bitsyntax/index.js deleted file mode 100644 index 3a894a9..0000000 --- a/node_modules/bitsyntax/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports.parse = require('./lib/parse').parse; -module.exports.match = require('./lib/interp').match; -module.exports.build = require('./lib/constructor').build; -module.exports.write = require('./lib/constructor').write; - -module.exports.matcher = module.exports.compile = - require('./lib/compile').compile; -module.exports.builder = require('./lib/compile').compile_builder; diff --git a/node_modules/bitsyntax/package.json b/node_modules/bitsyntax/package.json deleted file mode 100644 index 147b299..0000000 --- a/node_modules/bitsyntax/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "bitsyntax@~0.0.4", - "_id": "bitsyntax@0.0.4", - "_inBundle": false, - "_integrity": "sha1-6xDMb4K4xJDj6FaY8H6D1G4MuoI=", - "_location": "/bitsyntax", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bitsyntax@~0.0.4", - "name": "bitsyntax", - "escapedName": "bitsyntax", - "rawSpec": "~0.0.4", - "saveSpec": null, - "fetchSpec": "~0.0.4" - }, - "_requiredBy": [ - "/amqplib" - ], - "_resolved": "https://registry.npmjs.org/bitsyntax/-/bitsyntax-0.0.4.tgz", - "_shasum": "eb10cc6f82b8c490e3e85698f07e83d46e0cba82", - "_spec": "bitsyntax@~0.0.4", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", - "author": { - "name": "Michael Bridgen", - "email": "=0.6" - }, - "homepage": "https://github.com/squaremo/bitsyntax-js#readme", - "main": "./index", - "name": "bitsyntax", - "repository": { - "type": "git", - "url": "git://github.com/squaremo/bitsyntax-js.git" - }, - "scripts": { - "prepublish": "make all", - "test": "make test" - }, - "version": "0.0.4" -} diff --git a/node_modules/bitsyntax/test/consing.js b/node_modules/bitsyntax/test/consing.js deleted file mode 100644 index 4f1cd67..0000000 --- a/node_modules/bitsyntax/test/consing.js +++ /dev/null @@ -1,45 +0,0 @@ -var assert = require('assert'); -var parse = require('../').parse; -var build = require('../').build; -var builder = require('../').builder; -var write = require('../').write; - -TEST_CASES = [ - ['n:8', {n:255}, [255]], - ['n:16', {n: 0xf0f0}, [240, 240]], - ['n:32', {n: 0x12345678}, [18,52,86,120]], - ['n:64', {n: 0xffffffffffffffff}, [255,255,255,255,255,255,255,255]], - - ['n:8, s/binary', {n: 255, s: new Buffer("foobar")}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], - ['n:8, "foobar", m:8', {n: 255, m:0}, [255, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, 0]], - ['n:8, s:n/binary', {n:6, s: new Buffer('foobar')}, [6, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]], - ['n:8, s:n/binary', {n:4, s: new Buffer('foobar')}, [4, 0x66, 0x6f, 0x6f, 0x62]], - ['n:size', {n:4, size:8}, [4]], - ['206:n/unit:8', {n:1}, [206]] -]; - -function bufferToArray(buf) { - return Array.prototype.slice.call(buf); -} - -suite("Construction", function() { - TEST_CASES.forEach(function(c) { - var p = parse(c[0]); - test(c[0], function() { - assert.deepEqual(c[2], bufferToArray(build(p, c[1]))); - }); - test(c[0], function() { - var buf = new Buffer(1024); - var end = write(buf, 7, p, c[1]); - buf = buf.slice(7, end); - assert.deepEqual(c[2], bufferToArray(buf)); - }); - test(c[0], function() { - var cons = builder(c[0]); - var buf = cons(c[1]); - assert.deepEqual(c[2], bufferToArray(buf)); - }); - - }); - -}); diff --git a/node_modules/bitsyntax/test/matching.js b/node_modules/bitsyntax/test/matching.js deleted file mode 100644 index 1d5abe0..0000000 --- a/node_modules/bitsyntax/test/matching.js +++ /dev/null @@ -1,187 +0,0 @@ -var match = require('../').match; -var parse = require('../').parse; -var compile = require('../').matcher; -var assert = require('assert'); - - -var INT_TESTS = [ - ['n:8', - [[[255], 255]]], - ['n:8/signed', - [[[255], -1]]], - ['n:1/unit:8', - [[[129], 129]]], - ['n:1/unit:8-signed', - [[[129], -127]]], - - ['n:16', - [[[1, 255], 511]]], - ['n:16/signed', - [[[255, 65], -191]]], - ['n:16/little', - [[[255, 1], 511]]], - ['n:16/signed-little', - [[[65, 255], -191]]], - - ['n:32', - [[[45, 23, 97, 102], 756506982]]], - ['n:32/signed', - [[[245, 23, 97, 102], -183017114]]], - ['n:32/little', - [[[245, 23, 97, 102], 1717639157]]], - ['n:32/signed-little', - [[[245, 23, 97, 129], -2124343307]]], - - ['n:4/signed-little-unit:8', - [[[245, 23, 97, 129], -2124343307]]], - - ['n:64', - [[[1,2,3,4,5,6,7,8], 72623859790382856]]], - ['n:64/signed', - [[[255,2,3,4,5,6,7,8], -71491328285473016]]], - ['n:64/little', - [[[1,2,3,4,5,6,7,8], 578437695752307201]]], - ['n:64/little-signed', - [[[1,2,3,4,5,6,7,255], -70080650589044223]]], - ['n:8/signed-unit:8-little', - [[[1,2,3,4,5,6,7,255], -70080650589044223]]], -]; - -suite("Integer", - function() { - - INT_TESTS.forEach(function(p) { - var pattern = parse(p[0]); - var cpattern = compile(p[0]); - p[1].forEach(function(tc) { - test(p[0], function() { - assert.deepEqual({n: tc[1]}, match(pattern, new Buffer(tc[0]))); - }); - test(p[0], function() { - assert.deepEqual({n: tc[1]}, cpattern(new Buffer(tc[0]))); - }); - }); - }); - }); - - -// test cases largely constructed in Erlang using e.g., -// Pi = math:pi(), <>. -FLOAT_TESTS = [ - ['n:32/float', - [[[64,73,15,219], Math.PI], - [[0, 0, 0, 0], 0.0 ]]], - - ['n:64/float', - [[[64,9,33,251,84,68,45,24], Math.PI], - [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], - - ['n:32/float-little', - [[[219, 15, 73, 64], Math.PI], - [[0, 0, 0, 0], 0.0]]], - - ['n:64/float-little', - [[[24, 45, 68, 84, 251, 33, 9, 64], Math.PI], - [[0, 0, 0, 0, 0, 0, 0, 0], 0.0]]], - - ['n:4/float-unit:8', - [[[64,73,15,219], Math.PI], - [[0, 0, 0, 0], 0.0]]] -]; - -suite("Float", - function() { - var precision = 0.00001; - FLOAT_TESTS.forEach(function(p) { - var pattern = parse(p[0]); - var cpattern = compile(p[0]); - p[1].forEach(function(tc) { - test(p[0], function() { - var m = match(pattern, new Buffer(tc[0])); - assert.ok(m.n !== undefined); - assert.ok(Math.abs(tc[1] - m.n) < precision); - }); - test(p[0], function() { - var m = cpattern(new Buffer(tc[0])); - assert.ok(m.n !== undefined); - assert.ok(Math.abs(tc[1] - m.n) < precision); - }); - }); - }); - }); - -BINARY_TESTS = [ - ['n:0/unit:8-binary', []], - ['n:1/unit:8-binary', [93]], - ['n:5/unit:8-binary', [1, 2, 3, 4, 5]], - ['n:32/unit:1-binary', [255, 254, 253, 252]] -]; - -suite("Binary", - function() { - BINARY_TESTS.forEach(function(p) { - var pattern = parse(p[0]); - var cpattern = compile(p[0]); - var prest = p[0] + ', _/binary'; - var patternrest = parse(prest); - var cpatternrest = compile(prest); - test(p[0], function() { - assert.deepEqual({n: new Buffer(p[1])}, - match(pattern, new Buffer(p[1]))); - assert.deepEqual({n: new Buffer(p[1])}, - cpattern(new Buffer(p[1]))); - }); - test(prest, function() { - var plusgarbage = p[1].concat([5, 98, 23, 244]); - assert.deepEqual({n: new Buffer(p[1])}, - match(patternrest, new Buffer(plusgarbage))); - assert.deepEqual({n: new Buffer(p[1])}, - cpatternrest(new Buffer(plusgarbage))); - }); - }); - }); - -var VAR_TESTS = [ - ['size, n:size', - [[[8, 5], 5], - [[32, 0, 0, 0, 167], 167]]], - - ['size, n:size/binary', - [[[2, 5, 6], new Buffer([5, 6])]]], - - ['a, b:a, n:b', - [[[8, 32, 0, 0, 2, 100], 612]]] -]; - -suite("Environment", - function() { - VAR_TESTS.forEach(function(p) { - var pattern = parse(p[0]); - var cpattern = compile(p[0]); - p[1].forEach(function(tc) { - test(p[0], function() { - assert.deepEqual(tc[1], match(pattern, new Buffer(tc[0])).n); - }); - test(p[0], function() { - assert.deepEqual(tc[1], cpattern(new Buffer(tc[0])).n); - }); - }); - }); - }); - -STRING_TESTS = [ - ['"foobar", n:8', "foobarA", 'A'.charCodeAt(0)], - ['n:8, "foobar", _/binary', "CfoobarGARBAGE", 'C'.charCodeAt(0)], - ['"foo, :-bar\\"", n:8, "another"', 'foo, :-bar"Zanother', 'Z'.charCodeAt(0)] -]; - -suite("String", - function() { - STRING_TESTS.forEach(function(p) { - var pattern = parse(p[0]); - test(p[0], function() { - var res = match(pattern, new Buffer(p[1])); - assert.equal(res.n, p[2]); - }); - }); - }); diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE deleted file mode 100644 index ae732d5..0000000 --- a/node_modules/bluebird/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013-2017 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. diff --git a/node_modules/bluebird/README.md b/node_modules/bluebird/README.md deleted file mode 100644 index ba82f73..0000000 --- a/node_modules/bluebird/README.md +++ /dev/null @@ -1,52 +0,0 @@ - - Promises/A+ logo - - -[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) -[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) - -**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) - -# Introduction - -Bluebird is a fully featured promise library with focus on innovative features and performance - -See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. - -For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). - -# Questions and issues - -The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. - - - -## Thanks - -Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. - -# License - -The MIT License (MIT) - -Copyright (c) 2013-2017 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. - diff --git a/node_modules/bluebird/changelog.md b/node_modules/bluebird/changelog.md deleted file mode 100644 index 73b2eb6..0000000 --- a/node_modules/bluebird/changelog.md +++ /dev/null @@ -1 +0,0 @@ -[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) diff --git a/node_modules/bluebird/js/browser/bluebird.core.js b/node_modules/bluebird/js/browser/bluebird.core.js deleted file mode 100644 index 85b7791..0000000 --- a/node_modules/bluebird/js/browser/bluebird.core.js +++ /dev/null @@ -1,3781 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * Features enabled: core - * Features disabled: 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":17,"./schedule":18,"./util":21}],2:[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); -}; -}; - -},{}],3:[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":15}],4:[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":21}],5:[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":10,"./util":21}],6:[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; -}; - -},{}],7:[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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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; - } - } - return Promise; -}; - -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 && error.name != "SyntaxError") { - 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: error.name == "SyntaxError" ? 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":9,"./util":21}],8:[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); - } -}; -}; - -},{}],9:[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":10,"./util":21}],10:[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; - } - }; -} - -},{}],11:[function(_dereq_,module,exports){ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -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 === NEXT_FILTER) { - return ret; - } else 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); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - 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 Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":5,"./util":21}],12:[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 (!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, 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 (!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); - 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":21}],13:[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":21}],14:[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":9,"./es5":10,"./util":21}],15:[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, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - 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("Catch statement predicate: " + - "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" && - 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) { - if (executor === INTERNAL) return; - 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.5.1"; - - 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; - -}; - -},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[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 {}; - case -6: return new Map(); - } -} - -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":21}],17:[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.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; - -},{}],18:[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":21}],19:[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; -}; - -},{}],20:[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":21}],21:[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 instanceof Error || - (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]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -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, - hasEnvVariables: hasEnvVariables, - 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":10}]},{},[3])(3) -}); ;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/node_modules/bluebird/js/browser/bluebird.core.min.js b/node_modules/bluebird/js/browser/bluebird.core.min.js deleted file mode 100644 index 6aca6aa..0000000 --- a/node_modules/bluebird/js/browser/bluebird.core.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * Features enabled: core - * Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(a,s){if(!e[a]){if(!t[a]){var c="function"==typeof _dereq_&&_dereq_;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[a]={exports:{}};t[a][0].call(u.exports,function(e){var n=t[a][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[a].exports}for(var o="function"==typeof _dereq_&&_dereq_,a=0;a0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=s},{"./queue":17,"./schedule":18,"./util":21}],2:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},a=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},s=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var f={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,a,void 0,u,f),l._then(s,c,void 0,u,f),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],3:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":15}],4:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),a=o.tryCatch,s=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,a=t._peekContext,s=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=a,t.prototype._peekContext=s,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],7:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+I.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function a(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?I.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function f(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function h(){this._trace=new x(this._peekContext())}function _(t,e){if(H(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=E(t);I.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),I.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&X){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",a="";if(e._trace){for(var s=e._trace.stack.split("\n"),c=C(s),l=c.length-1;l>=0;--l){var u=c[l];if(!V.test(u)){var p=u.match(Q);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var f=c[0],l=0;l0&&(a="\n"+s[l-1]);break}}var h="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+a;r._warn(h,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new U(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var a=E(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||k(o,"",!0)}}function g(t,e){for(var n=0;n=0;--s)if(r[s]===o){a=s;break}for(var s=a;s>=0;--s){var c=r[s];if(e[i]!==c)break;e.pop(),i--}e=r}}function C(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function E(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:C(e)}}function k(t,e,n){if("undefined"!=typeof console){var r;if(I.isObject(t)){var i=t.stack;r=e+G(i,t)}else r=e+String(t);"function"==typeof N?N(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function j(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){B.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||k(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():I.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+T(e)+">, no stack trace)"}function T(t){var e=41;return t.lengtha||0>s||!n||!r||n!==r||a>=s||(nt=function(t){if(D.test(t))return!0;var e=R(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!0:!1})}}function x(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,x),e>32&&this.uncycle()}var O,A,N,L=e._getDomain,B=e._async,U=t("./errors").Warning,I=t("./util"),H=I.canAttachTrace,D=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,V=/\((?:timers\.js):\d+:\d+\)/,Q=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,G=null,M=!1,W=!(0==I.env("BLUEBIRD_DEBUG")||!I.env("BLUEBIRD_DEBUG")&&"development"!==I.env("NODE_ENV")),$=!(0==I.env("BLUEBIRD_WARNINGS")||!W&&!I.env("BLUEBIRD_WARNINGS")),z=!(0==I.env("BLUEBIRD_LONG_STACK_TRACES")||!W&&!I.env("BLUEBIRD_LONG_STACK_TRACES")),X=0!=I.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&($||!!I.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),j("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=L();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=L();O="function"==typeof t?null===e?t:I.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&P()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(B.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),B.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=h,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),B.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&P()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!I.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return I.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!I.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),I.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!I.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return I.isNode?function(){return process.emit.apply(process,arguments)}:I.global?function(t){var e="on"+t.toLowerCase(),n=I.global[e];return n?(n.apply(I.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){B.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){B.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,X=ot.warnings,I.isObject(n)&&"wForgottenReturn"in n&&(X=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(B.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=s,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=a,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;I.inherits(x,Error),n.CapturedTrace=x,x.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var a=e[r].stack,s=n[a];if(void 0!==s&&s!==r){s>0&&(e[s-1]._parent=void 0,e[s-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>s?(c._parent=e[s+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},x.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=E(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(C(i.stack.split("\n"))),i=i._parent;b(r),m(r),I.notEnumerableProp(t,"stack",g(n,r)),I.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,G=e;var n=Error.captureStackTrace;return nt=function(t){return D.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,G=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(G=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,G=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(N=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?N=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:I.isNode||"string"!=typeof(new Error).stack||(N=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:$,longStackTraces:!1,cancellation:!1,monitoring:!1};return z&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return f},checkForgottenReturns:d,setBounds:S,warn:y,deprecated:v,CapturedTrace:x,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":9,"./util":21}],8:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],9:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,a,s=t("./es5"),c=s.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,f=r("Warning","warning"),h=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,a=RangeError}catch(v){o=r("TypeError","type error"),a=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),g=0;g1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function s(){return l.call(this,this.promise._target()._settledValue())}function c(t){return a(this,t)?void 0:(f.e=t,f)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var h=n(u,i);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),f.e=_,f}h.isPending()&&h._attachCancellationCallback(new o(this))}return h._then(s,c,void 0,this,void 0)}}}return i.isRejected()?(a(this),f.e=t,f):(a(this),t)}var u=t("./util"),p=e.CancellationError,f=u.errorObj,h=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){a(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var a=arguments[r];if(!u.isObject(a))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(a)));i[o++]=a}i.length=o;var s=arguments[r];return this._passThrough(h(i,s,this),1,void 0,l)},i}},{"./catch_filter":5,"./util":21}],12:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,a){var s=t("./util");s.canEvaluate,s.tryCatch,s.errorObj;e.join=function(){var t,e=arguments.length-1;if(e>0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":21}],13:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var a=t("./util"),s=a.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+a.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=s(t).apply(this,arguments),a=r._popContext();return o.checkForgottenReturns(i,a,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+a.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=a.isArray(l)?s(t).apply(u,l):s(t).call(u,l)}else c=s(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===a.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":21}],14:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!h.isObject(o))return p("Catch statement predicate: expecting an object but got "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(F.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+h.classString(t);arguments.length>1&&(n+=", "+h.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+h.classString(t)):this.all()._then(t,void 0,void 0,C,void 0); -},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new k(this).promise()},i.prototype.error=function(t){return this.caught(h.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=x(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new k(t).promise()},i.cast=function(t){var e=E(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new g("expecting a function but got "+h.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var a=void 0!==o,s=a?o:new i(b),l=this._target(),u=l._bitField;a||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var p=c();if(0!==(50397184&u)){var f,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,f=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,f=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new m("late cancellation observer"),l._attachExtraTrace(_),f=e),v.invoke(d,l,{handler:null===p?f:"function"==typeof f&&h.domainBind(p,f),promise:s,receiver:r,value:_})}else l._addCallbacks(t,e,s,r,p);return s},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=f),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=f),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:h.domainBind(i,e));else{var a=4*o-4;this[a+2]=n,this[a+3]=r,"function"==typeof t&&(this[a+0]=null===i?t:h.domainBind(i,t)),"function"==typeof e&&(this[a+1]=null===i?e:h.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=E(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var a=this._length();a>0&&r._migrateCallback0(this);for(var s=1;a>s;++s)r._migrateCallbackAt(this,s);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new m("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=h.ensureErrorObject(t),i=r===t;if(!i&&!n&&F.warnings()){var o="a promise was rejected with a non-error: "+h.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===C?n&&"number"==typeof n.length?o=x(t).apply(this._boundValue(),n):(o=S,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=x(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===S?r._rejectCallback(o.e,!1):(F.checkForgottenReturns(o,a,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var a=t instanceof i,s=this._bitField,c=0!==(134217728&s);0!==(65536&s)?(a&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,x(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof k?t._cancel():r.cancel()):"function"==typeof e?a?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&s)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):a&&(c&&t._setAsyncGuaranteed(),0!==(33554432&s)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,h.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){F.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:a}},h.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,E,p,F),t("./bind")(i,b,E,F),t("./cancel")(i,k,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,E,b,v,c),i.Promise=i,i.version="3.5.1",h.toFastProperties(i),h.toFastProperties(i.prototype),s({a:1}),s({b:2}),s({c:3}),s(1),s(function(){}),s(void 0),s(!1),s(new i(b)),F.setBounds(d.firstLineError,h.lastLineError),i}},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function a(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function s(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(s,o),s.prototype.length=function(){return this._length},s.prototype.promise=function(){return this._promise},s.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var s=o._bitField;if(this._values=o,0===(50397184&s))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&s))return 0!==(16777216&s)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(a(n))):void this._iterate(o)},s.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,a=null,s=0;n>s;++s){var c=r(t[s],i);c instanceof e?(c=c._target(),a=c._bitField):a=null,o?null!==a&&c.suppressUnhandledRejections():null!==a?0===(50397184&a)?(c._proxy(this,s),this._values[s]=c):o=0!==(33554432&a)?this._promiseFulfilled(c._value(),s):0!==(16777216&a)?this._promiseRejected(c._reason(),s):this._promiseCancelled(s):o=this._promiseFulfilled(c,s)}o||i._setAsyncGuaranteed()},s.prototype._isResolved=function(){return null===this._values},s.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},s.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},s.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},s.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},s.prototype._promiseCancelled=function(){return this._cancel(),!0},s.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},s.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;no;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityn;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function f(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function h(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return N.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function g(t){try{u(t,"isOperational",!0)}catch(e){}}function m(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function C(t){return{}.toString.call(t)}function w(t,e,n){for(var r=F.names(t),i=0;i10||t[0]>0}(),D.isNode&&D.toFastProperties(process);try{throw new Error}catch(V){D.lastLineError=V}e.exports=D},{"./es5":10}]},{},[3])(3)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.js b/node_modules/bluebird/js/browser/bluebird.js deleted file mode 100644 index 2bc524b..0000000 --- a/node_modules/bluebird/js/browser/bluebird.js +++ /dev/null @@ -1,5623 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.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(); - 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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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; - } - } - return Promise; -}; - -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 && error.name != "SyntaxError") { - 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: error.name == "SyntaxError" ? 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, NEXT_FILTER) { -var util = _dereq_("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); - -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 === NEXT_FILTER) { - return ret; - } else 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); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - 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 Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; - -},{"./catch_filter":7,"./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", String(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 (!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, 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 (!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); - 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, NEXT_FILTER); -var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = _dereq_("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - 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("Catch statement predicate: " + - "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" && - 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) { - if (executor === INTERNAL) return; - 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.5.1"; -_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 {}; - case -6: return new Map(); - } -} - -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, isMap ? -6 : -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.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 instanceof Error || - (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]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -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, - hasEnvVariables: hasEnvVariables, - 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; } \ No newline at end of file diff --git a/node_modules/bluebird/js/browser/bluebird.min.js b/node_modules/bluebird/js/browser/bluebird.min.js deleted file mode 100644 index e02a9cd..0000000 --- a/node_modules/bluebird/js/browser/bluebird.min.js +++ /dev/null @@ -1,31 +0,0 @@ -/* @preserve - * The MIT License (MIT) - * - * Copyright (c) 2013-2017 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.5.1 - * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each -*/ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.Promise=t()}}(function(){var t,e,n;return function r(t,e,n){function i(s,a){if(!e[s]){if(!t[s]){var c="function"==typeof _dereq_&&_dereq_;if(!a&&c)return c(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=e[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return i(n?n:e)},u,u.exports,r,t,e,n)}return e[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},r.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},r.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},r.prototype._reset=function(){this._isTickUsed=!1},e.exports=r,e.exports.firstLineError=a},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},c=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var l=n(o),u=new t(e);u._propagateFrom(this,1);var p=this._target();if(u._setBoundTo(l),l instanceof t){var h={promiseRejectionQueued:!1,promise:u,target:p,bindingPromise:l};p._then(e,s,void 0,u,h),l._then(a,c,void 0,u,h),u._setOnCancel(l)}else u._resolveCallback(p);return u},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),c=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(c){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,c=e._async;e.prototype["break"]=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t._isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n._isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),t._setWillBeCancelled(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),c.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return null},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promiseCreated;return t._promiseCreated=null,e}return null},e.CapturedTrace=null,e.create=n,e.deactivateLongStackTraces=function(){},e.activateLongStackTraces=function(){var n=t.prototype._pushContext,o=t.prototype._popContext,s=t._peekContext,a=t.prototype._peekContext,c=t.prototype._promiseCreated;e.deactivateLongStackTraces=function(){t.prototype._pushContext=n,t.prototype._popContext=o,t._peekContext=s,t.prototype._peekContext=a,t.prototype._promiseCreated=c,i=!1},i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&null==t._promiseCreated&&(t._promiseCreated=this)}},e}},{}],9:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,e){return{promise:e}}function i(){return!1}function o(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(i){return i}}function s(t){if(!this._isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function a(){return this._onCancelField}function c(t){this._onCancelField=t}function l(){this._cancellationParent=void 0,this._onCancelField=void 0}function u(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function p(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof e?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new S(this._peekContext())}function _(t,e){if(N(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=j(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function d(t,e,n,r,i){if(void 0===t&&null!==e&&W){if(void 0!==i&&i._returnedNonUndefined())return;if(0===(65535&r._bitField))return;n&&(n+=" ");var o="",s="";if(e._trace){for(var a=e._trace.stack.split("\n"),c=w(a),l=c.length-1;l>=0;--l){var u=c[l];if(!U.test(u)){var p=u.match(M);p&&(o="at "+p[1]+":"+p[2]+":"+p[3]+" ");break}}if(c.length>0)for(var h=c[0],l=0;l0&&(s="\n"+a[l-1]);break}}var f="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;r._warn(f,!0,e)}}function v(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),y(n)}function y(t,n,r){if(ot.warnings){var i,o=new L(t);if(n)r._attachExtraTrace(o);else if(ot.longStackTraces&&(i=e._peekContext()))i.attachExtraTrace(o);else{var s=j(o);o.stack=s.message+"\n"+s.stack.join("\n")}tt("warning",o)||E(o,"",!0)}}function m(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var c=r[a];if(e[i]!==c)break;e.pop(),i--}e=r}}function w(t){for(var e=[],n=0;n0&&"SyntaxError"!=t.name&&(e=e.slice(n)),e}function j(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?C(t):[" (No stack trace)"],{message:n,stack:"SyntaxError"==t.name?e:w(e)}}function E(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+Q(i,t)}else r=e+String(t);"function"==typeof D?D(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function k(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(o){I.throwLater(o)}"unhandledRejection"===t?tt(t,n,r)||i||E(n,"Unhandled rejection "):tt(t,r)}function F(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(i){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(nt=function(t){if(B.test(t))return!0;var e=P(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function S(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);it(this,S),e>32&&this.uncycle()}var O,A,D,V=e._getDomain,I=e._async,L=t("./errors").Warning,H=t("./util"),N=H.canAttachTrace,B=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=/\((?:timers\.js):\d+:\d+\)/,M=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,q=null,Q=null,$=!1,G=!(0==H.env("BLUEBIRD_DEBUG")||!H.env("BLUEBIRD_DEBUG")&&"development"!==H.env("NODE_ENV")),z=!(0==H.env("BLUEBIRD_WARNINGS")||!G&&!H.env("BLUEBIRD_WARNINGS")),X=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!G&&!H.env("BLUEBIRD_LONG_STACK_TRACES")),W=0!=H.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(z||!!H.env("BLUEBIRD_W_FORGOTTEN_RETURN"));e.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|524288},e.prototype._ensurePossibleRejectionHandled=function(){if(0===(524288&this._bitField)){this._setRejectionIsUnhandled();var t=this;setTimeout(function(){t._notifyUnhandledRejection()},1)}},e.prototype._notifyUnhandledRejectionIsHandled=function(){k("rejectionHandled",O,void 0,this)},e.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},e.prototype._returnedNonUndefined=function(){return 0!==(268435456&this._bitField)},e.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),k("unhandledRejection",A,t,this)}},e.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},e.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},e.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},e.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},e.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},e.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},e.prototype._warn=function(t,e,n){return y(t,e,n||this)},e.onPossiblyUnhandledRejection=function(t){var e=V();A="function"==typeof t?null===e?t:H.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=V();O="function"==typeof t?null===e?t:H.domainBind(e,t):void 0};var K=function(){};e.longStackTraces=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!ot.longStackTraces&&T()){var t=e.prototype._captureStackTrace,r=e.prototype._attachExtraTrace;ot.longStackTraces=!0,K=function(){if(I.haveItemsQueued()&&!ot.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");e.prototype._captureStackTrace=t,e.prototype._attachExtraTrace=r,n.deactivateLongStackTraces(),I.enableTrampoline(),ot.longStackTraces=!1},e.prototype._captureStackTrace=f,e.prototype._attachExtraTrace=_,n.activateLongStackTraces(),I.disableTrampolineIfNecessary()}},e.hasLongStackTraces=function(){return ot.longStackTraces&&T()};var J=function(){try{if("function"==typeof CustomEvent){var t=new CustomEvent("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new CustomEvent(t.toLowerCase(),{detail:e,cancelable:!0});return!H.global.dispatchEvent(n)}}if("function"==typeof Event){var t=new Event("CustomEvent");return H.global.dispatchEvent(t),function(t,e){var n=new Event(t.toLowerCase(),{cancelable:!0});return n.detail=e,!H.global.dispatchEvent(n)}}var t=document.createEvent("CustomEvent");return t.initCustomEvent("testingtheevent",!1,!0,{}),H.global.dispatchEvent(t),function(t,e){var n=document.createEvent("CustomEvent");return n.initCustomEvent(t.toLowerCase(),!1,!0,e),!H.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),Y=function(){return H.isNode?function(){return process.emit.apply(process,arguments)}:H.global?function(t){var e="on"+t.toLowerCase(),n=H.global[e];return n?(n.apply(H.global,[].slice.call(arguments,1)),!0):!1}:function(){return!1}}(),Z={promiseCreated:r,promiseFulfilled:r,promiseRejected:r,promiseResolved:r,promiseCancelled:r,promiseChained:function(t,e,n){return{promise:e,child:n}},warning:function(t,e){return{warning:e}},unhandledRejection:function(t,e,n){return{reason:e,promise:n}},rejectionHandled:r},tt=function(t){var e=!1;try{e=Y.apply(null,arguments)}catch(n){I.throwLater(n),e=!0}var r=!1;try{r=J(t,Z[t].apply(null,arguments))}catch(n){I.throwLater(n),r=!0}return r||e};e.config=function(t){if(t=Object(t),"longStackTraces"in t&&(t.longStackTraces?e.longStackTraces():!t.longStackTraces&&e.hasLongStackTraces()&&K()),"warnings"in t){var n=t.warnings;ot.warnings=!!n,W=ot.warnings,H.isObject(n)&&"wForgottenReturn"in n&&(W=!!n.wForgottenReturn)}if("cancellation"in t&&t.cancellation&&!ot.cancellation){if(I.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");e.prototype._clearCancellationData=l,e.prototype._propagateFrom=u,e.prototype._onCancel=a,e.prototype._setOnCancel=c,e.prototype._attachCancellationCallback=s,e.prototype._execute=o,et=u,ot.cancellation=!0}return"monitoring"in t&&(t.monitoring&&!ot.monitoring?(ot.monitoring=!0,e.prototype._fireEvent=tt):!t.monitoring&&ot.monitoring&&(ot.monitoring=!1,e.prototype._fireEvent=i)),e},e.prototype._fireEvent=i,e.prototype._execute=function(t,e,n){try{t(e,n)}catch(r){return r}},e.prototype._onCancel=function(){},e.prototype._setOnCancel=function(t){},e.prototype._attachCancellationCallback=function(t){},e.prototype._captureStackTrace=function(){},e.prototype._attachExtraTrace=function(){},e.prototype._clearCancellationData=function(){},e.prototype._propagateFrom=function(t,e){};var et=p,nt=function(){return!1},rt=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(S,Error),n.CapturedTrace=S,S.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var c=r>0?e[r-1]:this;t-1>a?(c._parent=e[a+1],c._parent.uncycle(),c._length=c._parent._length+1):(c._parent=void 0,c._length=1);for(var l=c._length+1,u=r-2;u>=0;--u)e[u]._length=l,l++;return}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=j(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(w(i.stack.split("\n"))),i=i._parent;b(r),g(r),H.notEnumerableProp(t,"stack",m(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var it=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():F(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,q=t,Q=e;var n=Error.captureStackTrace;return nt=function(t){return B.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return q=/@/,Q=e,$=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(o){i="stack"in o}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(Q=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?F(e):e.toString()},null):(q=t,Q=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]);"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(D=function(t){console.warn(t)},H.isNode&&process.stderr.isTTY?D=function(t,e){var n=e?"":"";console.warn(n+t+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(D=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var ot={warnings:z,longStackTraces:!1,cancellation:!1,monitoring:!1};return X&&e.longStackTraces(),{longStackTraces:function(){return ot.longStackTraces},warnings:function(){return ot.warnings},cancellation:function(){return ot.cancellation},monitoring:function(){return ot.monitoring},propagateFromFunction:function(){return et},boundValueFunction:function(){return h},checkForgottenReturns:d,setBounds:R,warn:y,deprecated:v,CapturedTrace:S,fireDomEvent:J,fireGlobalEvent:Y}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype["return"]=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype["throw"]=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return i(this,t,e,0)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,r){return i(t,r,e,0)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(p(this,"message","string"==typeof r?r:e),p(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return u(n,Error),n}function i(t){return this instanceof i?(p(this,"name","OperationalError"),p(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(p(this,"message",t.message),p(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),c=a.freeze,l=t("./util"),u=l.inherits,p=l.notEnumerableProp,h=r("Warning","warning"),f=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(v){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var y="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function a(){return l.call(this,this.promise._target()._settledValue())}function c(t){return s(this,t)?void 0:(h.e=t,h)}function l(t){var i=this.promise,l=this.handler;if(!this.called){this.called=!0;var u=this.isFinallyHandler()?l.call(i._boundValue()):l.call(i._boundValue(),t);if(u===r)return u;if(void 0!==u){i._setReturnedNonUndefined();var f=n(u,i);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var _=new p("late cancellation observer");return i._attachExtraTrace(_),h.e=_,h}f.isPending()&&f._attachCancellationCallback(new o(this))}return f._then(a,c,void 0,this,void 0)}}}return i.isRejected()?(s(this),h.e=t,h):(s(this),t)}var u=t("./util"),p=e.CancellationError,h=u.errorObj,f=t("./catch_filter")(r);return i.prototype.isFinallyHandler=function(){return 0===this.type},o.prototype._resultCancelled=function(){s(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,new i(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,l,l)},e.prototype.tap=function(t){return this._passThrough(t,1,l)},e.prototype.tapCatch=function(t){var n=arguments.length;if(1===n)return this._passThrough(t,1,void 0,l);var r,i=new Array(n-1),o=0;for(r=0;n-1>r;++r){var s=arguments[r];if(!u.isObject(s))return e.reject(new TypeError("tapCatch statement predicate: expecting an object but got "+u.classString(s)));i[o++]=s}i.length=o;var a=arguments[r];return this._passThrough(f(i,a,this),1,void 0,l)},i}},{"./catch_filter":7,"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=l();this._callback=null===i?e:u.domainBind(i,e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],f.invoke(this._asyncInit,this,void 0)}function c(t,n,i,o){if("function"!=typeof n)return r("expecting a function but got "+u.classString(n));var s=0;if(void 0!==i){if("object"!=typeof i||null===i)return e.reject(new TypeError("options argument must be an object but it is "+u.classString(i)));if("number"!=typeof i.concurrency)return e.reject(new TypeError("'concurrency' must be a number but it is "+u.classString(i.concurrency)));s=i.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new a(t,n,s,o).promise()}var l=e._getDomain,u=t("./util"),p=u.tryCatch,h=u.errorObj,f=e._async;u.inherits(a,n),a.prototype._asyncInit=function(){this._init$(void 0,-2)},a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,c=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,c>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(c>=1&&this._inFlight>=c)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var l=this._promise,u=this._callback,f=l._boundValue();l._pushContext();var _=p(u).call(f,t,n,o),d=l._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",l),_===h)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return c>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return c(this,t,e,null)},e.map=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments),s=r._popContext();return o.checkForgottenReturns(i,s,"Promise.method",r),r._resolveFromSyncValue(i),r}},e.attempt=e["try"]=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var c;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var l=arguments[1],u=arguments[2];c=s.isArray(l)?a(t).apply(u,l):a(t).call(u,l)}else c=a(t)();var p=r._popContext();return o.checkForgottenReturns(c,p,"Promise.try",r),r._resolveFromSyncValue(c),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&u.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new l(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=u.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!f.isObject(o))return p("Catch statement predicate: expecting an object but got "+f.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(u,u,void 0,this,void 0)},i.prototype.then=function(t,e){if(x.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+f.classString(t);arguments.length>1&&(n+=", "+f.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?p("expecting a function but got "+f.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new E(this).promise()},i.prototype.error=function(t){return this.caught(f.originatesFromRejection,t)},i.getNewLibraryCopy=e.exports,i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b);e._captureStackTrace();var n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===S&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new E(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._captureStackTrace(),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));return v.setScheduler(t)},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),l=this._target(),u=l._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,a));var p=c();if(0!==(50397184&u)){var h,_,d=l._settlePromiseCtx;0!==(33554432&u)?(_=l._rejectionHandler0,h=t):0!==(16777216&u)?(_=l._fulfillmentHandler0,h=e,l._unsetRejectionIsUnhandled()):(d=l._settlePromiseLateCancellationObserver,_=new g("late cancellation observer"),l._attachExtraTrace(_),h=e),v.invoke(d,l,{handler:null===p?h:"function"==typeof h&&f.domainBind(p,h),promise:a,receiver:r,value:_})}else l._addCallbacks(t,e,a,r,p);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},i.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},i.prototype._setAsyncGuaranteed=function(){v.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===h?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=h),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=h),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:f.domainBind(i,e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:f.domainBind(i,t)),"function"==typeof e&&(this[s+1]=null===i?e:f.domainBind(i,e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(l(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target();if(r===this)return void this._reject(l());var o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var c=new g("late cancellation observer");r._attachExtraTrace(c),this._reject(c)}}},i.prototype._rejectCallback=function(t,e,n){var r=f.ensureErrorObject(t),i=r===t;if(!i&&!n&&x.warnings()){var o="a promise was rejected with a non-error: "+f.classString(t);this._warn(o,!0)}this._attachExtraTrace(r,e?i:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){if(t!==b){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)}},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=S,o.e=new m("cannot .spread() a non-array: "+f.classString(n))):o=O(t).call(e,n);var s=r._popContext();i=r._bitField,0===(65536&i)&&(o===C?r._reject(n):o===S?r._rejectCallback(o.e,!1):(x.checkForgottenReturns(o,s,"",r,this),r._resolveCallback(o)))}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,c=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),r instanceof T&&r.isFinallyHandler()?(r.cancelPromise=t,O(e).call(r,o)===S&&t._reject(S.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof E?t._cancel():r.cancel()):"function"==typeof e?s?(c&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(c&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=l();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,f.isNode):void((65535&e)>0?v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){x.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},f.notEnumerableProp(i,"_makeSelfResolutionError",l),t("./method")(i,b,j,p,x),t("./bind")(i,b,j,x),t("./cancel")(i,E,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,j,b,v,c),i.Promise=i,i.version="3.5.1",t("./map.js")(i,E,p,j,b,x),t("./call_get.js")(i),t("./using.js")(i,p,j,F,b,x),t("./timers.js")(i,b,x),t("./generators.js")(i,p,b,j,n,x),t("./nodeify.js")(i),t("./promisify.js")(i,b),t("./props.js")(i,E,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,E,p,j,b,x),t("./settle.js")(i,E,x),t("./some.js")(i,E,p),t("./filter.js")(i,b),t("./each.js")(i,b),t("./any.js")(i),f.toFastProperties(i),f.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),x.setBounds(d.firstLineError,f.lastLineError),i}},{"./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(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{};case-6:return new Map}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var c=t("./util");c.isArray;return c.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function l(t,n){var o=r(this._values,this._promise);if(o instanceof e){o=o._target();var a=o._bitField;if(this._values=o,0===(50397184&a))return this._promise._setAsyncGuaranteed(),o._then(l,this._reject,void 0,this,n);if(0===(33554432&a))return 0!==(16777216&a)?this._reject(o._reason()):this._cancel();o=o._value()}if(o=c.asArray(o),null===o){var u=i("expecting an array or an iterable object but got "+c.classString(o)).reason();return void this._promise._rejectCallback(u,!1)}return 0===o.length?void(-5===n?this._resolveEmptyArray():this._resolve(s(n))):void this._iterate(o)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var c=r(t[a],i);c instanceof e?(c=c._target(),s=c._bitField):s=null,o?null!==s&&c.suppressUnhandledRejections():null!==s?0===(50397184&s)?(c._proxy(this,a),this._values[a]=c):o=0!==(33554432&s)?this._promiseFulfilled(c._value(),a):0!==(16777216&s)?this._promiseRejected(c._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(c,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise._isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nc;c+=2){var u=s[c],p=s[c+1],_=u+e;if(r===k)t[_]=k(u,h,u,p,e,i);else{var d=r(p,function(){return k(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return k(t,e,void 0,t,null,n)}var p,h={},f=t("./util"),_=t("./nodeback"),d=f.withAppended,v=f.maybeWrapAsError,y=f.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return f.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},E=function(t){return t.replace(/([$])/,"\\$")},k=y?p:c;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+f.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?h:e.context,o=!!e.multiArgs,s=u(t,n,o);return f.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!f.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=f.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,n?-6:-3)}function s(t){var n,s=r(t);return l(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,c=t("./util"),l=c.isObject,u=t("./es5");"function"==typeof Map&&(a=Map);var p=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),h=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};c.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=h(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityh;++h){var _=t[h];(void 0!==_||h in t)&&e.cast(_)._then(u,p,void 0,l,null)}return l}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=h();this._fn=null===s?n:f.domainBind(s,n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,i===o?this._eachValues=Array(this._length):0===i?this._eachValues=null:this._eachValues=void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function c(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function l(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+f.classString(e));var o=new a(t,e,n,i);return o.promise()}function u(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(p,void 0,void 0,this,void 0)):p.call(this,n)}function p(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var h=e._getDomain,f=t("./util"),_=f.tryCatch;f.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&null!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return null!==this._eachValues&&this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(u,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(c,c,void 0,n,this)},e.prototype.reduce=function(t,e){return l(this,t,e,null)},e.reduce=function(t,e,n,r){return l(t,e,n,r)}}},{"./util":36}],29:[function(t,e,n){"use strict";var r,i=t("./util"),o=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")},s=i.getNativePromise();if(i.isNode&&"undefined"==typeof MutationObserver){var a=global.setImmediate,c=process.nextTick;r=i.isRecentNode?function(t){a.call(global,t)}:function(t){c.call(process,t)}}else if("function"==typeof s&&"function"==typeof s.resolve){var l=s.resolve();r=function(t){l.then(t)}}else r="undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&(window.navigator.standalone||window.cordova)?"undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:o:function(){var t=document.createElement("div"),e={attributes:!0},n=!1,r=document.createElement("div"),i=new MutationObserver(function(){t.classList.toggle("foo"),n=!1});i.observe(r,e);var o=function(){n||(n=!0,r.classList.toggle("foo"))};return function(n){var r=new MutationObserver(function(){r.disconnect(),n()});r.observe(t,e),o()}}();e.exports=r},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t), -this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,c=t("./errors").AggregateError,l=s.isArray,u={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=l(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(u),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new c,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.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()},r=e.prototype.error=e.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()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=function(){return 0!==(8454144&this._bitField)},t.prototype.__isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype._isCancelled=function(){return this._target().__isCancelled()},t.prototype.isCancelled=function(){return 0!==(8454144&this._target()._bitField)},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(u(t)){if(t instanceof e)return t;var i=o(t);if(i===l){r&&r._pushContext();var c=e.reject(i.e);return r&&r._popContext(),c}if("function"==typeof i){if(s(t)){var c=new e(n);return t._then(c._fulfill,c._reject,void 0,c,null),c}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(e){return l.e=e,l}}function s(t){try{return p.call(t,"_promise0")}catch(e){return!1}}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,p,!0),a=null)}var a=new e(n),u=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var p=!0,h=c.tryCatch(r).call(t,o,s);return p=!1,a&&h===l&&(a._rejectCallback(h.e,!0,!0),a=null),u}var c=t("./util"),l=c.errorObj,u=c.isObject,p={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.handle=t}function o(t){return clearTimeout(this.handle),t}function s(t){throw clearTimeout(this.handle),t}var a=t("./util"),c=e.TimeoutError;i.prototype._resultCancelled=function(){clearTimeout(this.handle)};var l=function(t){return u(+this).thenReturn(t)},u=e.delay=function(t,o){var s,a;return void 0!==o?(s=e.resolve(o)._then(l,null,null,t,void 0),r.cancellation()&&o instanceof e&&s._setOnCancel(o)):(s=new e(n),a=setTimeout(function(){s._fulfill()},+t),r.cancellation()&&s._setOnCancel(new i(a)),s._captureStackTrace()),s._setAsyncGuaranteed(),s};e.prototype.delay=function(t){return u(t,this)};var p=function(t,e,n){var r;r="string"!=typeof e?e instanceof Error?e:new c("operation timed out"):new c(e),a.markAsOriginatingFromRejection(r),t._attachExtraTrace(r),t._reject(r),null!=n&&n.cancel()};e.prototype.timeout=function(t,e){t=+t;var n,a,c=new i(setTimeout(function(){n.isPending()&&p(n,e,a)},t));return r.cancellation()?(a=this.then(),n=a._then(o,s,void 0,c,void 0),n._setOnCancel(c)):n=this._then(o,s,void 0,c,void 0),n}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function c(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function l(t,n){function i(){if(s>=l)return u._fulfill();var o=c(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(p){return a(p)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,l=t.length,u=new e(o);return i(),u}function u(t,e,n){this._data=t,this._promise=e,this._context=n}function p(t,e,n){this.constructor$(t,e,n)}function h(t){return u.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function f(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch,g={};u.prototype.data=function(){return this._data},u.prototype.promise=function(){return this._promise},u.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():g},u.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=e!==g?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},u.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(p,u),p.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},f.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var c=new f(t),p=0;t>p;++p){var d=o[p];if(u.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(h,null,null,{resources:c,index:p},void 0))}c[p]=d}for(var b=new Array(c.length),p=0;p0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new p(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(t,e,n){"use strict";function r(){try{var t=P;return P=null,t.apply(this,arguments)}catch(e){return T.e=e,T}}function i(t){return P=t,r}function o(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function s(t){return"function"==typeof t||"object"==typeof t&&null!==t}function a(t){return o(t)?new Error(v(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function u(t,e,n){if(o(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function p(t){throw t}function h(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=A.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(o){return!1}}function f(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function _(t){return D.test(t)}function d(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function v(t){try{return t+""}catch(e){return"[no string representation]"}}function y(t){return t instanceof Error||null!==t&&"object"==typeof t&&"string"==typeof t.message&&"string"==typeof t.name}function m(t){try{u(t,"isOperational",!0)}catch(e){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return y(t)&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i10||t[0]>0}(),B.isNode&&B.toFastProperties(process);try{throw new Error}catch(U){B.lastLineError=U}e.exports=B},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise); \ No newline at end of file diff --git a/node_modules/bluebird/js/release/any.js b/node_modules/bluebird/js/release/any.js deleted file mode 100644 index 05a6228..0000000 --- a/node_modules/bluebird/js/release/any.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -var SomePromiseArray = Promise._SomePromiseArray; -function any(promises) { - var ret = new SomePromiseArray(promises); - var promise = ret.promise(); - ret.setHowMany(1); - ret.setUnwrap(); - ret.init(); - return promise; -} - -Promise.any = function (promises) { - return any(promises); -}; - -Promise.prototype.any = function () { - return any(this); -}; - -}; diff --git a/node_modules/bluebird/js/release/assert.js b/node_modules/bluebird/js/release/assert.js deleted file mode 100644 index 4518231..0000000 --- a/node_modules/bluebird/js/release/assert.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -module.exports = (function(){ -var AssertionError = (function() { - function AssertionError(a) { - this.constructor$(a); - this.message = a; - this.name = "AssertionError"; - } - AssertionError.prototype = new Error(); - AssertionError.prototype.constructor = AssertionError; - AssertionError.prototype.constructor$ = Error; - return AssertionError; -})(); - -function getParams(args) { - var params = []; - for (var i = 0; i < args.length; ++i) params.push("arg" + i); - return params; -} - -function nativeAssert(callName, args, expect) { - try { - var params = getParams(args); - var constructorArgs = params; - constructorArgs.push("return " + - callName + "("+ params.join(",") + ");"); - var fn = Function.apply(null, constructorArgs); - return fn.apply(null, args); - } catch (e) { - if (!(e instanceof SyntaxError)) { - throw e; - } else { - return expect; - } - } -} - -return function assert(boolExpr, message) { - if (boolExpr === true) return; - - if (typeof boolExpr === "string" && - boolExpr.charAt(0) === "%") { - var nativeCallName = boolExpr; - var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];}; - if (nativeAssert(nativeCallName, args, message) === message) return; - message = (nativeCallName + " !== " + message); - } - - var ret = new AssertionError(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(ret, assert); - } - throw ret; -}; -})(); diff --git a/node_modules/bluebird/js/release/async.js b/node_modules/bluebird/js/release/async.js deleted file mode 100644 index 41f6655..0000000 --- a/node_modules/bluebird/js/release/async.js +++ /dev/null @@ -1,161 +0,0 @@ -"use strict"; -var firstLineError; -try {throw new Error(); } catch (e) {firstLineError = e;} -var schedule = require("./schedule"); -var Queue = require("./queue"); -var util = require("./util"); - -function Async() { - this._customScheduler = false; - this._isTickUsed = false; - this._lateQueue = new Queue(16); - this._normalQueue = new Queue(16); - this._haveDrainedQueues = false; - this._trampolineEnabled = true; - var self = this; - this.drainQueues = function () { - self._drainQueues(); - }; - this._schedule = schedule; -} - -Async.prototype.setScheduler = function(fn) { - var prev = this._schedule; - this._schedule = fn; - this._customScheduler = true; - return prev; -}; - -Async.prototype.hasCustomScheduler = function() { - return this._customScheduler; -}; - -Async.prototype.enableTrampoline = function() { - this._trampolineEnabled = true; -}; - -Async.prototype.disableTrampolineIfNecessary = function() { - if (util.hasDevTools) { - this._trampolineEnabled = false; - } -}; - -Async.prototype.haveItemsQueued = function () { - return this._isTickUsed || this._haveDrainedQueues; -}; - - -Async.prototype.fatalError = function(e, isNode) { - if (isNode) { - process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + - "\n"); - process.exit(2); - } else { - this.throwLater(e); - } -}; - -Async.prototype.throwLater = function(fn, arg) { - if (arguments.length === 1) { - arg = fn; - fn = function () { throw arg; }; - } - if (typeof setTimeout !== "undefined") { - setTimeout(function() { - fn(arg); - }, 0); - } else try { - this._schedule(function() { - fn(arg); - }); - } catch (e) { - throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } -}; - -function AsyncInvokeLater(fn, receiver, arg) { - this._lateQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncInvoke(fn, receiver, arg) { - this._normalQueue.push(fn, receiver, arg); - this._queueTick(); -} - -function AsyncSettlePromises(promise) { - this._normalQueue._pushOne(promise); - this._queueTick(); -} - -if (!util.hasDevTools) { - Async.prototype.invokeLater = AsyncInvokeLater; - Async.prototype.invoke = AsyncInvoke; - Async.prototype.settlePromises = AsyncSettlePromises; -} else { - Async.prototype.invokeLater = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvokeLater.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - setTimeout(function() { - fn.call(receiver, arg); - }, 100); - }); - } - }; - - Async.prototype.invoke = function (fn, receiver, arg) { - if (this._trampolineEnabled) { - AsyncInvoke.call(this, fn, receiver, arg); - } else { - this._schedule(function() { - fn.call(receiver, arg); - }); - } - }; - - Async.prototype.settlePromises = function(promise) { - if (this._trampolineEnabled) { - AsyncSettlePromises.call(this, promise); - } else { - this._schedule(function() { - promise._settlePromises(); - }); - } - }; -} - -Async.prototype._drainQueue = function(queue) { - while (queue.length() > 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; diff --git a/node_modules/bluebird/js/release/bind.js b/node_modules/bluebird/js/release/bind.js deleted file mode 100644 index fc3379d..0000000 --- a/node_modules/bluebird/js/release/bind.js +++ /dev/null @@ -1,67 +0,0 @@ -"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); -}; -}; diff --git a/node_modules/bluebird/js/release/bluebird.js b/node_modules/bluebird/js/release/bluebird.js deleted file mode 100644 index 1c36cf3..0000000 --- a/node_modules/bluebird/js/release/bluebird.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -var old; -if (typeof Promise !== "undefined") old = Promise; -function noConflict() { - try { if (Promise === bluebird) Promise = old; } - catch (e) {} - return bluebird; -} -var bluebird = require("./promise")(); -bluebird.noConflict = noConflict; -module.exports = bluebird; diff --git a/node_modules/bluebird/js/release/call_get.js b/node_modules/bluebird/js/release/call_get.js deleted file mode 100644 index 0ed7714..0000000 --- a/node_modules/bluebird/js/release/call_get.js +++ /dev/null @@ -1,123 +0,0 @@ -"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 = require("./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 $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - 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); -}; -}; diff --git a/node_modules/bluebird/js/release/cancel.js b/node_modules/bluebird/js/release/cancel.js deleted file mode 100644 index 7a12415..0000000 --- a/node_modules/bluebird/js/release/cancel.js +++ /dev/null @@ -1,129 +0,0 @@ -"use strict"; -module.exports = function(Promise, PromiseArray, apiRejection, debug) { -var util = require("./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(); -}; - -}; diff --git a/node_modules/bluebird/js/release/catch_filter.js b/node_modules/bluebird/js/release/catch_filter.js deleted file mode 100644 index 0f24ce2..0000000 --- a/node_modules/bluebird/js/release/catch_filter.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -module.exports = function(NEXT_FILTER) { -var util = require("./util"); -var getKeys = require("./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; -}; diff --git a/node_modules/bluebird/js/release/context.js b/node_modules/bluebird/js/release/context.js deleted file mode 100644 index c307414..0000000 --- a/node_modules/bluebird/js/release/context.js +++ /dev/null @@ -1,69 +0,0 @@ -"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; -}; diff --git a/node_modules/bluebird/js/release/debuggability.js b/node_modules/bluebird/js/release/debuggability.js deleted file mode 100644 index 6956804..0000000 --- a/node_modules/bluebird/js/release/debuggability.js +++ /dev/null @@ -1,919 +0,0 @@ -"use strict"; -module.exports = function(Promise, Context) { -var getDomain = Promise._getDomain; -var async = Promise._async; -var Warning = require("./errors").Warning; -var util = require("./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 && - (false || - 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(); - var self = this; - setTimeout(function() { - self._notifyUnhandledRejection(); - }, 1); -}; - -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; - } - } - return Promise; -}; - -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 && error.name != "SyntaxError") { - 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: error.name == "SyntaxError" ? 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 -}; -}; diff --git a/node_modules/bluebird/js/release/direct_resolve.js b/node_modules/bluebird/js/release/direct_resolve.js deleted file mode 100644 index a890298..0000000 --- a/node_modules/bluebird/js/release/direct_resolve.js +++ /dev/null @@ -1,46 +0,0 @@ -"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); - } -}; -}; diff --git a/node_modules/bluebird/js/release/each.js b/node_modules/bluebird/js/release/each.js deleted file mode 100644 index e4f3d05..0000000 --- a/node_modules/bluebird/js/release/each.js +++ /dev/null @@ -1,30 +0,0 @@ -"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; -}; - diff --git a/node_modules/bluebird/js/release/errors.js b/node_modules/bluebird/js/release/errors.js deleted file mode 100644 index f62f323..0000000 --- a/node_modules/bluebird/js/release/errors.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -var es5 = require("./es5"); -var Objectfreeze = es5.freeze; -var util = require("./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 -}; diff --git a/node_modules/bluebird/js/release/es5.js b/node_modules/bluebird/js/release/es5.js deleted file mode 100644 index ea41d5a..0000000 --- a/node_modules/bluebird/js/release/es5.js +++ /dev/null @@ -1,80 +0,0 @@ -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; - } - }; -} diff --git a/node_modules/bluebird/js/release/filter.js b/node_modules/bluebird/js/release/filter.js deleted file mode 100644 index ed57bf0..0000000 --- a/node_modules/bluebird/js/release/filter.js +++ /dev/null @@ -1,12 +0,0 @@ -"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); -}; -}; diff --git a/node_modules/bluebird/js/release/finally.js b/node_modules/bluebird/js/release/finally.js deleted file mode 100644 index d57444b..0000000 --- a/node_modules/bluebird/js/release/finally.js +++ /dev/null @@ -1,146 +0,0 @@ -"use strict"; -module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { -var util = require("./util"); -var CancellationError = Promise.CancellationError; -var errorObj = util.errorObj; -var catchFilter = require("./catch_filter")(NEXT_FILTER); - -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 === NEXT_FILTER) { - return ret; - } else 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); -}; - -Promise.prototype.tapCatch = function (handlerOrPredicate) { - var len = arguments.length; - if(len === 1) { - return this._passThrough(handlerOrPredicate, - 1, - undefined, - finallyHandler); - } else { - 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 Promise.reject(new TypeError( - "tapCatch statement predicate: " - + "expecting an object but got " + util.classString(item) - )); - } - } - catchInstances.length = j; - var handler = arguments[i]; - return this._passThrough(catchFilter(catchInstances, handler, this), - 1, - undefined, - finallyHandler); - } - -}; - -return PassThroughHandlerContext; -}; diff --git a/node_modules/bluebird/js/release/generators.js b/node_modules/bluebird/js/release/generators.js deleted file mode 100644 index 500c280..0000000 --- a/node_modules/bluebird/js/release/generators.js +++ /dev/null @@ -1,223 +0,0 @@ -"use strict"; -module.exports = function(Promise, - apiRejection, - INTERNAL, - tryConvertToPromise, - Proxyable, - debug) { -var errors = require("./errors"); -var TypeError = errors.TypeError; -var util = require("./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", String(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; -}; -}; diff --git a/node_modules/bluebird/js/release/join.js b/node_modules/bluebird/js/release/join.js deleted file mode 100644 index 4945e3f..0000000 --- a/node_modules/bluebird/js/release/join.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = -function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, - getDomain) { -var util = require("./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 $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; - if (fn) args.pop(); - var ret = new PromiseArray(args).promise(); - return fn !== undefined ? ret.spread(fn) : ret; -}; - -}; diff --git a/node_modules/bluebird/js/release/map.js b/node_modules/bluebird/js/release/map.js deleted file mode 100644 index 976f15e..0000000 --- a/node_modules/bluebird/js/release/map.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = require("./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); -}; - - -}; diff --git a/node_modules/bluebird/js/release/method.js b/node_modules/bluebird/js/release/method.js deleted file mode 100644 index ce9e4db..0000000 --- a/node_modules/bluebird/js/release/method.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -module.exports = -function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { -var util = require("./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); - } -}; -}; diff --git a/node_modules/bluebird/js/release/nodeback.js b/node_modules/bluebird/js/release/nodeback.js deleted file mode 100644 index 71e69eb..0000000 --- a/node_modules/bluebird/js/release/nodeback.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -var util = require("./util"); -var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors"); -var OperationalError = errors.OperationalError; -var es5 = require("./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 $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; - promise._fulfill(args); - } - promise = null; - }; -} - -module.exports = nodebackForPromise; diff --git a/node_modules/bluebird/js/release/nodeify.js b/node_modules/bluebird/js/release/nodeify.js deleted file mode 100644 index ce2b190..0000000 --- a/node_modules/bluebird/js/release/nodeify.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -module.exports = function(Promise) { -var util = require("./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; -}; -}; diff --git a/node_modules/bluebird/js/release/promise.js b/node_modules/bluebird/js/release/promise.js deleted file mode 100644 index f4a641c..0000000 --- a/node_modules/bluebird/js/release/promise.js +++ /dev/null @@ -1,775 +0,0 @@ -"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 = require("./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 = require("./es5"); -var Async = require("./async"); -var async = new Async(); -es5.defineProperty(Promise, "_async", {value: async}); -var errors = require("./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 = require("./thenables")(Promise, INTERNAL); -var PromiseArray = - require("./promise_array")(Promise, INTERNAL, - tryConvertToPromise, apiRejection, Proxyable); -var Context = require("./context")(Promise); - /*jshint unused:false*/ -var createContext = Context.create; -var debug = require("./debuggability")(Promise, Context); -var CapturedTrace = debug.CapturedTrace; -var PassThroughHandlerContext = - require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); -var catchFilter = require("./catch_filter")(NEXT_FILTER); -var nodebackForPromise = require("./nodeback"); -var errorObj = util.errorObj; -var tryCatch = util.tryCatch; -function check(self, executor) { - if (self == null || self.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); - } - if (typeof executor !== "function") { - throw new TypeError("expecting a function but got " + util.classString(executor)); - } - -} - -function Promise(executor) { - if (executor !== INTERNAL) { - check(this, executor); - } - this._bitField = 0; - this._fulfillmentHandler0 = undefined; - this._rejectionHandler0 = undefined; - this._promise0 = undefined; - this._receiver0 = undefined; - 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("Catch statement predicate: " + - "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" && - 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) { - if (executor === INTERNAL) return; - 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); - -require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, - debug); -require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); -require("./cancel")(Promise, PromiseArray, apiRejection, debug); -require("./direct_resolve")(Promise); -require("./synchronous_inspection")(Promise); -require("./join")( - Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); -Promise.Promise = Promise; -Promise.version = "3.5.1"; -require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -require('./call_get.js')(Promise); -require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); -require('./timers.js')(Promise, INTERNAL, debug); -require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); -require('./nodeify.js')(Promise); -require('./promisify.js')(Promise, INTERNAL); -require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); -require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); -require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); -require('./settle.js')(Promise, PromiseArray, debug); -require('./some.js')(Promise, PromiseArray, apiRejection); -require('./filter.js')(Promise, INTERNAL); -require('./each.js')(Promise, INTERNAL); -require('./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; - -}; diff --git a/node_modules/bluebird/js/release/promise_array.js b/node_modules/bluebird/js/release/promise_array.js deleted file mode 100644 index 0fb303e..0000000 --- a/node_modules/bluebird/js/release/promise_array.js +++ /dev/null @@ -1,185 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL, tryConvertToPromise, - apiRejection, Proxyable) { -var util = require("./util"); -var isArray = util.isArray; - -function toResolutionValue(val) { - switch(val) { - case -2: return []; - case -3: return {}; - case -6: return new Map(); - } -} - -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; -}; diff --git a/node_modules/bluebird/js/release/promisify.js b/node_modules/bluebird/js/release/promisify.js deleted file mode 100644 index aa98e5b..0000000 --- a/node_modules/bluebird/js/release/promisify.js +++ /dev/null @@ -1,314 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = require("./util"); -var nodebackForPromise = require("./nodeback"); -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var TypeError = require("./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); -}; -}; - diff --git a/node_modules/bluebird/js/release/props.js b/node_modules/bluebird/js/release/props.js deleted file mode 100644 index 6a34aaf..0000000 --- a/node_modules/bluebird/js/release/props.js +++ /dev/null @@ -1,118 +0,0 @@ -"use strict"; -module.exports = function( - Promise, PromiseArray, tryConvertToPromise, apiRejection) { -var util = require("./util"); -var isObject = util.isObject; -var es5 = require("./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, isMap ? -6 : -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); -}; -}; diff --git a/node_modules/bluebird/js/release/queue.js b/node_modules/bluebird/js/release/queue.js deleted file mode 100644 index ffd36fd..0000000 --- a/node_modules/bluebird/js/release/queue.js +++ /dev/null @@ -1,73 +0,0 @@ -"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.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; diff --git a/node_modules/bluebird/js/release/race.js b/node_modules/bluebird/js/release/race.js deleted file mode 100644 index b862f46..0000000 --- a/node_modules/bluebird/js/release/race.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -module.exports = function( - Promise, INTERNAL, tryConvertToPromise, apiRejection) { -var util = require("./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); -}; - -}; diff --git a/node_modules/bluebird/js/release/reduce.js b/node_modules/bluebird/js/release/reduce.js deleted file mode 100644 index 26e2b1a..0000000 --- a/node_modules/bluebird/js/release/reduce.js +++ /dev/null @@ -1,172 +0,0 @@ -"use strict"; -module.exports = function(Promise, - PromiseArray, - apiRejection, - tryConvertToPromise, - INTERNAL, - debug) { -var getDomain = Promise._getDomain; -var util = require("./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; -} -}; diff --git a/node_modules/bluebird/js/release/schedule.js b/node_modules/bluebird/js/release/schedule.js deleted file mode 100644 index f70df9f..0000000 --- a/node_modules/bluebird/js/release/schedule.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -var util = require("./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; diff --git a/node_modules/bluebird/js/release/settle.js b/node_modules/bluebird/js/release/settle.js deleted file mode 100644 index fade3a1..0000000 --- a/node_modules/bluebird/js/release/settle.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -module.exports = - function(Promise, PromiseArray, debug) { -var PromiseInspection = Promise.PromiseInspection; -var util = require("./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); -}; -}; diff --git a/node_modules/bluebird/js/release/some.js b/node_modules/bluebird/js/release/some.js deleted file mode 100644 index 400d852..0000000 --- a/node_modules/bluebird/js/release/some.js +++ /dev/null @@ -1,148 +0,0 @@ -"use strict"; -module.exports = -function(Promise, PromiseArray, apiRejection) { -var util = require("./util"); -var RangeError = require("./errors").RangeError; -var AggregateError = require("./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; -}; diff --git a/node_modules/bluebird/js/release/synchronous_inspection.js b/node_modules/bluebird/js/release/synchronous_inspection.js deleted file mode 100644 index 9c49d2e..0000000 --- a/node_modules/bluebird/js/release/synchronous_inspection.js +++ /dev/null @@ -1,103 +0,0 @@ -"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; -}; diff --git a/node_modules/bluebird/js/release/thenables.js b/node_modules/bluebird/js/release/thenables.js deleted file mode 100644 index d6ab9aa..0000000 --- a/node_modules/bluebird/js/release/thenables.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var util = require("./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; -}; diff --git a/node_modules/bluebird/js/release/timers.js b/node_modules/bluebird/js/release/timers.js deleted file mode 100644 index cb8f1f4..0000000 --- a/node_modules/bluebird/js/release/timers.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -module.exports = function(Promise, INTERNAL, debug) { -var util = require("./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; -}; - -}; diff --git a/node_modules/bluebird/js/release/using.js b/node_modules/bluebird/js/release/using.js deleted file mode 100644 index 65de531..0000000 --- a/node_modules/bluebird/js/release/using.js +++ /dev/null @@ -1,226 +0,0 @@ -"use strict"; -module.exports = function (Promise, apiRejection, tryConvertToPromise, - createContext, INTERNAL, debug) { - var util = require("./util"); - var TypeError = require("./errors").TypeError; - var inherits = require("./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(); - }; - -}; diff --git a/node_modules/bluebird/js/release/util.js b/node_modules/bluebird/js/release/util.js deleted file mode 100644 index 7ac0e2f..0000000 --- a/node_modules/bluebird/js/release/util.js +++ /dev/null @@ -1,380 +0,0 @@ -"use strict"; -var es5 = require("./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 instanceof Error || - (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]"; - -var hasEnvVariables = typeof process !== "undefined" && - typeof process.env !== "undefined"; - -function env(key) { - return hasEnvVariables ? process.env[key] : undefined; -} - -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, - hasEnvVariables: hasEnvVariables, - 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; diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json deleted file mode 100644 index 782d74d..0000000 --- a/node_modules/bluebird/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "bluebird@^3.4.6", - "_id": "bluebird@3.5.1", - "_inBundle": false, - "_integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", - "_location": "/bluebird", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bluebird@^3.4.6", - "name": "bluebird", - "escapedName": "bluebird", - "rawSpec": "^3.4.6", - "saveSpec": null, - "fetchSpec": "^3.4.6" - }, - "_requiredBy": [ - "/amqplib" - ], - "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", - "_shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", - "_spec": "bluebird@^3.4.6", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", - "author": { - "name": "Petka Antonov", - "email": "petka_antonov@hotmail.com", - "url": "http://github.com/petkaantonov/" - }, - "browser": "./js/browser/bluebird.js", - "bugs": { - "url": "http://github.com/petkaantonov/bluebird/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Full featured Promises/A+ implementation with exceptionally good performance", - "devDependencies": { - "acorn": "~0.6.0", - "baconjs": "^0.7.43", - "bluebird": "^2.9.2", - "body-parser": "^1.10.2", - "browserify": "^8.1.1", - "cli-table": "~0.3.1", - "co": "^4.2.0", - "cross-spawn": "^0.2.3", - "glob": "^4.3.2", - "grunt-saucelabs": "~8.4.1", - "highland": "^2.3.0", - "istanbul": "^0.3.5", - "jshint": "^2.6.0", - "jshint-stylish": "~0.2.0", - "kefir": "^2.4.1", - "mkdirp": "~0.5.0", - "mocha": "~2.1", - "open": "~0.0.5", - "optimist": "~0.6.1", - "rimraf": "~2.2.6", - "rx": "^2.3.25", - "serve-static": "^1.7.1", - "sinon": "~1.7.3", - "uglify-js": "~2.4.16" - }, - "files": [ - "js/browser", - "js/release", - "LICENSE" - ], - "homepage": "https://github.com/petkaantonov/bluebird", - "keywords": [ - "promise", - "performance", - "promises", - "promises-a", - "promises-aplus", - "async", - "await", - "deferred", - "deferreds", - "future", - "flow control", - "dsl", - "fluent interface" - ], - "license": "MIT", - "main": "./js/release/bluebird.js", - "name": "bluebird", - "repository": { - "type": "git", - "url": "git://github.com/petkaantonov/bluebird.git" - }, - "scripts": { - "generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", - "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", - "istanbul": "istanbul", - "lint": "node scripts/jshint.js", - "prepublish": "npm run generate-browser-core && npm run generate-browser-full", - "test": "node tools/test.js" - }, - "version": "3.5.1", - "webpack": "./js/release/bluebird.js" -} diff --git a/node_modules/buffer-more-ints/.npmignore b/node_modules/buffer-more-ints/.npmignore deleted file mode 100644 index abd60f7..0000000 --- a/node_modules/buffer-more-ints/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -/node_modules -*~ diff --git a/node_modules/buffer-more-ints/LICENSE b/node_modules/buffer-more-ints/LICENSE deleted file mode 100644 index e0d6370..0000000 --- a/node_modules/buffer-more-ints/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2012 David Wragg. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/buffer-more-ints/README.md b/node_modules/buffer-more-ints/README.md deleted file mode 100644 index 2fe7e91..0000000 --- a/node_modules/buffer-more-ints/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# buffer-more-ints: Add support for more integer widths to Buffer - -Node's Buffer only supports reading and writing integers of a limited -range of widths. This module provides support for more widths, so -that integers from 1 to 8 bytes (64 bits) can be accessed. The -support takes two forms. Firstly, as stand-alone functions similar to -the integer reading/writing methods of Buffer: - - $ node - > var moreints = require('buffer-more-ints') - undefined - > moreints.readInt64BE(new Buffer("0000deadbeef0000", "hex"), 0).toString(16) - 'deadbeef0000' - -Read and write functions for the regular widths (8, 16, 32) are also -present in this module, for consistency. - -The second form is methods patched into `Buffer.prototype`, installed -by requiring `'buffer-more-ints/polyfill'`: - - $ node - > require('buffer-more-ints/polyfill') - {} - > new Buffer("0000deadbeef0000", "hex").readInt64BE(0).toString(16) - 'deadbeef0000' - - -buffer-more-ints/polyfill also adds methods `readIntBE`, `writeIntBE`, -and their LE and UInt counterparts, which take an initial argument -giving the width of the integer in bytes: - - > var b = new Buffer(3); - > b.writeIntLE(3, -123456, 0); - > b.toString('hex') - 'c01dfe' - > b.readIntLE(3, 0); - -123456 - -The functions added by buffer-more-ints are all implemented in terms -of the core Buffer functions. Part way through writing the code, I -discovered that node.js currently implements those in JavaScript, so -this doesn't lead to performance benefits. But should node ever -switch to implementing its Buffer operations natively, this -module should get a speed boost. - -## Limitations - -As JavaScript uses IEEE754 doubles for numbers, the contiguous range -of integers it can represent is [-2^53 - 1, 2^53 - 1]. So only -integer widths up to 6 bytes or 48 bits can be read exactly. Reads of -7 or 8 bytes (56 or 64 bits) will return the closest value that can be -represented as a JavaScript number. - -In certain situations it might be important to check that a JavaScript -number was read exactly. The `isContiguousInt` or -`Buffer.isContiguousInt` (polyfill) function will determine this: - - > Buffer.isContiguousInt(0x1fffffffffffff); - true - > Buffer.isContiguousInt(0x20000000000000); - false - -And `assertContiguousInt` asserts that a number is so: - - > Buffer.assertContiguousInt(0x1fffffffffffff); - undefined - > Buffer.assertContiguousInt(0x20000000000000); - AssertionError: number cannot be represented as a contiguous integer diff --git a/node_modules/buffer-more-ints/buffer-more-ints-tests.js b/node_modules/buffer-more-ints/buffer-more-ints-tests.js deleted file mode 100644 index 25bd848..0000000 --- a/node_modules/buffer-more-ints/buffer-more-ints-tests.js +++ /dev/null @@ -1,207 +0,0 @@ -'use strict'; - -require('./polyfill'); - -// A simple abbreviation to obtain a buffer from a hex string -function h2b(str) { - return new Buffer(str, "hex"); -} - -// Reverse a buffer -function reverse(buf) { - var res = new Buffer(buf.length); - for (var i = 0, j = buf.length - 1; j >= 0; i++, j--) { - res[i] = buf[j]; - } - return res; -} - -// Fill a buffer with distinctive data -function scrub(buf) { - var pos = 0; - var written; - while ((written = buf.write("deadbeef", pos, 4, "hex")) == 4) { - pos += written; - } - return buf; -} - -function xint_case(xint) { - return function (assert, hex, val, inexact) { - var readBE = "read" + xint + "BE"; - var writeBE = "write" + xint + "BE"; - var readLE = "read" + xint + "LE"; - var writeLE = "write" + xint + "LE"; - - var len = hex.length / 2; - - // Straightforward read cases - assert.equal(h2b(hex)[readBE](len, 0), val); - assert.equal(reverse(h2b(hex))[readLE](len, 0), val); - - // Test straightforward writes and noAssert writes off the ends of - // the buffer - var buf = scrub(new Buffer(len)); - buf[writeBE](len, val, 0); - if (!inexact) { - assert.equal(buf.toString("hex"), hex); - } else { - assert.equal(buf[readBE](len, 0), val); - } - - var buf2 = scrub(new Buffer(len)); - buf2[writeBE](len, val, -1, true); - assert.equal(buf2.slice(0, len-1).toString("hex"), - buf.slice(1, len).toString("hex")); - scrub(buf2); - buf2[writeBE](len, val, 1, true); - assert.equal(buf2.slice(1, len).toString("hex"), - buf.slice(0, len-1).toString("hex")); - - scrub(buf); - buf[writeLE](len, val, 0); - if (!inexact) { - assert.equal(reverse(buf).toString("hex"), hex); - } else { - assert.equal(buf[readLE](len, 0), val); - } - - scrub(buf2); - buf2[writeLE](len, val, -1, true); - assert.equal(buf2.slice(0, len-1).toString("hex"), - buf.slice(1, len).toString("hex")); - scrub(buf2); - buf2[writeLE](len, val, 1, true); - assert.equal(buf2.slice(1, len).toString("hex"), - buf.slice(0, len-1).toString("hex")); - - // Accessess off the end of the buffer should throw. Node - // doesn't catch negative offsets. - assert.throws(function () { h2b(hex)[readBE](len, 1); }) - assert.throws(function () { reverse(h2b(hex))[readLE](len, 1); }) - assert.throws(function () { buf[writeBE](len, val, 1); }); - assert.throws(function () { buf[writeLE](len, val, 1); }); - - // Test noAssert reads that stray off the ends of the buffer. - var expect = h2b("00"+hex)[readBE](len, 0); - assert.equal(h2b(hex)[readBE](len, -1, true), expect); - assert.equals(reverse(h2b(hex))[readLE](len, 1, true), expect); - - expect = h2b(hex+"00")[readBE](len, 1); - assert.equal(h2b(hex)[readBE](len, 1, true), expect); - assert.equal(reverse(h2b(hex))[readLE](len, -1, true), expect); - }; -} - -var uint_case = xint_case("UInt"); -var int_case = xint_case("Int"); - -module.exports.uint = function (assert) { - uint_case(assert, "00", 0x00); - uint_case(assert, "01", 0x01); - uint_case(assert, "ff", 0xff); - - uint_case(assert, "0000", 0x0000); - uint_case(assert, "0102", 0x0102); - uint_case(assert, "ffff", 0xffff); - - uint_case(assert, "000000", 0x000000); - uint_case(assert, "010203", 0x010203); - uint_case(assert, "ffffff", 0xffffff); - - uint_case(assert, "00000000", 0x00000000); - uint_case(assert, "01020304", 0x01020304); - uint_case(assert, "ffffffff", 0xffffffff); - - uint_case(assert, "0000000000", 0x0000000000); - uint_case(assert, "0102030405", 0x0102030405); - uint_case(assert, "ffffffffff", 0xffffffffff); - - uint_case(assert, "000000000000", 0x000000000000); - uint_case(assert, "010203040506", 0x010203040506); - uint_case(assert, "ffffffffffff", 0xffffffffffff); - - uint_case(assert, "00000000000000", 0x00000000000000); - uint_case(assert, "01020304050607", 0x01020304050607); - uint_case(assert, "ffffffffffffff", 0xffffffffffffff); - - uint_case(assert, "0000000000000000", 0x0000000000000000); - uint_case(assert, "0102030405060708", 0x0102030405060708, true); - uint_case(assert, "ffffffffffffffff", 0xffffffffffffffff); - - assert.done(); -}; - -module.exports.int = function (assert) { - int_case(assert, "00", 0x00); - int_case(assert, "01", 0x01); - int_case(assert, "7f", 0x7f); - int_case(assert, "80", -0x80); - int_case(assert, "ff", -0x01); - - int_case(assert, "0000", 0x0000); - int_case(assert, "0102", 0x0102); - int_case(assert, "7fff", 0x7fff); - int_case(assert, "8000", -0x8000); - int_case(assert, "ffff", -0x0001); - - int_case(assert, "000000", 0x000000); - int_case(assert, "010203", 0x010203); - int_case(assert, "7fffff", 0x7fffff); - int_case(assert, "800000", -0x800000); - int_case(assert, "ffffff", -0x000001); - - int_case(assert, "00000000", 0x00000000); - int_case(assert, "01020304", 0x01020304); - int_case(assert, "7fffffff", 0x7fffffff); - int_case(assert, "80000000", -0x80000000); - int_case(assert, "ffffffff", -0x00000001); - - int_case(assert, "0000000000", 0x0000000000); - int_case(assert, "0102030405", 0x0102030405); - int_case(assert, "7fffffffff", 0x7fffffffff); - int_case(assert, "8000000000", -0x8000000000); - int_case(assert, "ffffffffff", -0x0000000001); - - int_case(assert, "000000000000", 0x000000000000); - int_case(assert, "010203040506", 0x010203040506); - int_case(assert, "7fffffffffff", 0x7fffffffffff); - int_case(assert, "800000000000", -0x800000000000); - int_case(assert, "ffffffffffff", -0x000000000001); - - int_case(assert, "00000000000000", 0x00000000000000); - int_case(assert, "01020304050607", 0x01020304050607); - int_case(assert, "7fffffffffffff", 0x7fffffffffffff); - int_case(assert, "80000000000000", -0x80000000000000); - int_case(assert, "ffffffffffffff", -0x00000000000001); - - int_case(assert, "0000000000000000", 0x0000000000000000); - int_case(assert, "0102030405060708", 0x0102030405060708, true); - int_case(assert, "7fffffffffffffff", 0x7fffffffffffffff); - int_case(assert, "8000000000000000", -0x8000000000000000); - int_case(assert, "ffffffffffffffff", -0x0000000000000001); - - assert.done(); -}; - -module.exports.isContiguousInt = function (assert) { - assert.equal(Buffer.isContiguousInt(0x1fffffffffffff), true); - assert.equal(Buffer.isContiguousInt(0x20000000000000), false); - assert.equal(Buffer.isContiguousInt(-0x1fffffffffffff), true); - assert.equal(Buffer.isContiguousInt(-0x20000000000000), false); - - assert.doesNotThrow(function () { - Buffer.assertContiguousInt(0x1fffffffffffff); - }); - assert.throws(function () { - Buffer.assertContiguousInt(0x20000000000000); - }); - assert.doesNotThrow(function () { - Buffer.assertContiguousInt(-0x1fffffffffffff); - }); - assert.throws(function () { - Buffer.assertContiguousInt(-0x20000000000000); - }); - - assert.done(); -}; diff --git a/node_modules/buffer-more-ints/buffer-more-ints.js b/node_modules/buffer-more-ints/buffer-more-ints.js deleted file mode 100644 index b0ae27d..0000000 --- a/node_modules/buffer-more-ints/buffer-more-ints.js +++ /dev/null @@ -1,472 +0,0 @@ -'use strict'; - -var assert = require("assert"); - -// JavaScript is numerically challenged -var SHIFT_LEFT_32 = (1 << 16) * (1 << 16); -var SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32; - -// The maximum contiguous integer that can be held in a IEEE754 double -var MAX_INT = 0x1fffffffffffff; - -function isContiguousInt(val) { - return val <= MAX_INT && val >= -MAX_INT; -} - -function assertContiguousInt(val) { - assert(isContiguousInt(val), "number cannot be represented as a contiguous integer"); -} - -module.exports.isContiguousInt = isContiguousInt; -module.exports.assertContiguousInt = assertContiguousInt; - -// Fill in the regular procedures -['UInt', 'Int'].forEach(function (sign) { - var suffix = sign + '8'; - module.exports['read' + suffix] = - Buffer.prototype['read' + suffix].call; - module.exports['write' + suffix] = - Buffer.prototype['write' + suffix].call; - - ['16', '32'].forEach(function (size) { - ['LE', 'BE'].forEach(function (endian) { - var suffix = sign + size + endian; - var read = Buffer.prototype['read' + suffix]; - module.exports['read' + suffix] = - function (buf, offset, noAssert) { - return read.call(buf, offset, noAssert); - }; - var write = Buffer.prototype['write' + suffix]; - module.exports['write' + suffix] = - function (buf, val, offset, noAssert) { - return write.call(buf, val, offset, noAssert); - }; - }); - }); -}); - -// Check that a value is an integer within the given range -function check_int(val, min, max) { - assert.ok(typeof(val) == 'number' && val >= min && val <= max && Math.floor(val) === val, "not a number in the required range"); -} - -function readUInt24BE(buf, offset, noAssert) { - return buf.readUInt8(offset, noAssert) << 16 | buf.readUInt16BE(offset + 1, noAssert); -} -module.exports.readUInt24BE = readUInt24BE; - -function writeUInt24BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffff); - assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeUInt8(val >>> 16, offset, noAssert); - buf.writeUInt16BE(val & 0xffff, offset + 1, noAssert); -} -module.exports.writeUInt24BE = writeUInt24BE; - -function readUInt40BE(buf, offset, noAssert) { - return (buf.readUInt8(offset, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1, noAssert); -} -module.exports.readUInt40BE = readUInt40BE; - -function writeUInt40BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffff); - assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 1, noAssert); -} -module.exports.writeUInt40BE = writeUInt40BE; - -function readUInt48BE(buf, offset, noAssert) { - return buf.readUInt16BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2, noAssert); -} -module.exports.readUInt48BE = readUInt48BE; - -function writeUInt48BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffff); - assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeUInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 2, noAssert); -} -module.exports.writeUInt48BE = writeUInt48BE; - -function readUInt56BE(buf, offset, noAssert) { - return ((buf.readUInt8(offset, noAssert) || 0) << 16 | buf.readUInt16BE(offset + 1, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3, noAssert); -} -module.exports.readUInt56BE = readUInt56BE; - -function writeUInt56BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffffff); - assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x100000000000000) { - var hi = Math.floor(val * SHIFT_RIGHT_32); - buf.writeUInt8(hi >>> 16, offset, noAssert); - buf.writeUInt16BE(hi & 0xffff, offset + 1, noAssert); - buf.writeInt32BE(val & -1, offset + 3, noAssert); - } else { - // Special case because 2^56-1 gets rounded up to 2^56 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - } -} -module.exports.writeUInt56BE = writeUInt56BE; - -function readUInt64BE(buf, offset, noAssert) { - return buf.readUInt32BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4, noAssert); -} -module.exports.readUInt64BE = readUInt64BE; - -function writeUInt64BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffffffff); - assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x10000000000000000) { - buf.writeUInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 4, noAssert); - } else { - // Special case because 2^64-1 gets rounded up to 2^64 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - buf[offset+7] = 0xff; - } -} -module.exports.writeUInt64BE = writeUInt64BE; - -function readUInt24LE(buf, offset, noAssert) { - return buf.readUInt8(offset + 2, noAssert) << 16 | buf.readUInt16LE(offset, noAssert); -} -module.exports.readUInt24LE = readUInt24LE; - -function writeUInt24LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffff); - assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeUInt16LE(val & 0xffff, offset, noAssert); - buf.writeUInt8(val >>> 16, offset + 2, noAssert); -} -module.exports.writeUInt24LE = writeUInt24LE; - -function readUInt40LE(buf, offset, noAssert) { - return (buf.readUInt8(offset + 4, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readUInt40LE = readUInt40LE; - -function writeUInt40LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffff); - assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeUInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); -} -module.exports.writeUInt40LE = writeUInt40LE; - -function readUInt48LE(buf, offset, noAssert) { - return buf.readUInt16LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readUInt48LE = readUInt48LE; - -function writeUInt48LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffff); - assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeUInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); -} -module.exports.writeUInt48LE = writeUInt48LE; - -function readUInt56LE(buf, offset, noAssert) { - return ((buf.readUInt8(offset + 6, noAssert) || 0) << 16 | buf.readUInt16LE(offset + 4, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readUInt56LE = readUInt56LE; - -function writeUInt56LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffffff); - assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x100000000000000) { - buf.writeInt32LE(val & -1, offset, noAssert); - var hi = Math.floor(val * SHIFT_RIGHT_32); - buf.writeUInt16LE(hi & 0xffff, offset + 4, noAssert); - buf.writeUInt8(hi >>> 16, offset + 6, noAssert); - } else { - // Special case because 2^56-1 gets rounded up to 2^56 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - } -} -module.exports.writeUInt56LE = writeUInt56LE; - -function readUInt64LE(buf, offset, noAssert) { - return buf.readUInt32LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readUInt64LE = readUInt64LE; - -function writeUInt64LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, 0, 0xffffffffffffffff); - assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x10000000000000000) { - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeUInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); - } else { - // Special case because 2^64-1 gets rounded up to 2^64 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - buf[offset+7] = 0xff; - } -} -module.exports.writeUInt64LE = writeUInt64LE; - - -function readInt24BE(buf, offset, noAssert) { - return (buf.readInt8(offset, noAssert) << 16) + buf.readUInt16BE(offset + 1, noAssert); -} -module.exports.readInt24BE = readInt24BE; - -function writeInt24BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000, 0x7fffff); - assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt8(val >> 16, offset, noAssert); - buf.writeUInt16BE(val & 0xffff, offset + 1, noAssert); -} -module.exports.writeInt24BE = writeInt24BE; - -function readInt40BE(buf, offset, noAssert) { - return (buf.readInt8(offset, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 1, noAssert); -} -module.exports.readInt40BE = readInt40BE; - -function writeInt40BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x8000000000, 0x7fffffffff); - assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 1, noAssert); -} -module.exports.writeInt40BE = writeInt40BE; - -function readInt48BE(buf, offset, noAssert) { - return buf.readInt16BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 2, noAssert); -} -module.exports.readInt48BE = readInt48BE; - -function writeInt48BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000000000, 0x7fffffffffff); - assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt16BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 2, noAssert); -} -module.exports.writeInt48BE = writeInt48BE; - -function readInt56BE(buf, offset, noAssert) { - return (((buf.readInt8(offset, noAssert) || 0) << 16) + buf.readUInt16BE(offset + 1, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 3, noAssert); -} -module.exports.readInt56BE = readInt56BE; - -function writeInt56BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000000000000, 0x7fffffffffffff); - assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x80000000000000) { - var hi = Math.floor(val * SHIFT_RIGHT_32); - buf.writeInt8(hi >> 16, offset, noAssert); - buf.writeUInt16BE(hi & 0xffff, offset + 1, noAssert); - buf.writeInt32BE(val & -1, offset + 3, noAssert); - } else { - // Special case because 2^55-1 gets rounded up to 2^55 - buf[offset] = 0x7f; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - } -} -module.exports.writeInt56BE = writeInt56BE; - -function readInt64BE(buf, offset, noAssert) { - return buf.readInt32BE(offset, noAssert) * SHIFT_LEFT_32 + buf.readUInt32BE(offset + 4, noAssert); -} -module.exports.readInt64BE = readInt64BE; - -function writeInt64BE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000000000000000, 0x7fffffffffffffff); - assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x8000000000000000) { - buf.writeInt32BE(Math.floor(val * SHIFT_RIGHT_32), offset, noAssert); - buf.writeInt32BE(val & -1, offset + 4, noAssert); - } else { - // Special case because 2^63-1 gets rounded up to 2^63 - buf[offset] = 0x7f; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - buf[offset+7] = 0xff; - } -} -module.exports.writeInt64BE = writeInt64BE; - -function readInt24LE(buf, offset, noAssert) { - return (buf.readInt8(offset + 2, noAssert) << 16) + buf.readUInt16LE(offset, noAssert); -} -module.exports.readInt24LE = readInt24LE; - -function writeInt24LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000, 0x7fffff); - assert.ok(offset + 3 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeUInt16LE(val & 0xffff, offset, noAssert); - buf.writeInt8(val >> 16, offset + 2, noAssert); -} -module.exports.writeInt24LE = writeInt24LE; - -function readInt40LE(buf, offset, noAssert) { - return (buf.readInt8(offset + 4, noAssert) || 0) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readInt40LE = readInt40LE; - -function writeInt40LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x8000000000, 0x7fffffffff); - assert.ok(offset + 5 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeInt8(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); -} -module.exports.writeInt40LE = writeInt40LE; - -function readInt48LE(buf, offset, noAssert) { - return buf.readInt16LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readInt48LE = readInt48LE; - -function writeInt48LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x800000000000, 0x7fffffffffff); - assert.ok(offset + 6 <= buf.length, "attempt to write beyond end of buffer"); - } - - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeInt16LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); -} -module.exports.writeInt48LE = writeInt48LE; - -function readInt56LE(buf, offset, noAssert) { - return (((buf.readInt8(offset + 6, noAssert) || 0) << 16) + buf.readUInt16LE(offset + 4, noAssert)) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readInt56LE = readInt56LE; - -function writeInt56LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x80000000000000, 0x7fffffffffffff); - assert.ok(offset + 7 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x80000000000000) { - buf.writeInt32LE(val & -1, offset, noAssert); - var hi = Math.floor(val * SHIFT_RIGHT_32); - buf.writeUInt16LE(hi & 0xffff, offset + 4, noAssert); - buf.writeInt8(hi >> 16, offset + 6, noAssert); - } else { - // Special case because 2^55-1 gets rounded up to 2^55 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0x7f; - } -} -module.exports.writeInt56LE = writeInt56LE; - -function readInt64LE(buf, offset, noAssert) { - return buf.readInt32LE(offset + 4, noAssert) * SHIFT_LEFT_32 + buf.readUInt32LE(offset, noAssert); -} -module.exports.readInt64LE = readInt64LE; - -function writeInt64LE(buf, val, offset, noAssert) { - if (!noAssert) { - check_int(val, -0x8000000000000000, 0x7fffffffffffffff); - assert.ok(offset + 8 <= buf.length, "attempt to write beyond end of buffer"); - } - - if (val < 0x8000000000000000) { - buf.writeInt32LE(val & -1, offset, noAssert); - buf.writeInt32LE(Math.floor(val * SHIFT_RIGHT_32), offset + 4, noAssert); - } else { - // Special case because 2^55-1 gets rounded up to 2^55 - buf[offset] = 0xff; - buf[offset+1] = 0xff; - buf[offset+2] = 0xff; - buf[offset+3] = 0xff; - buf[offset+4] = 0xff; - buf[offset+5] = 0xff; - buf[offset+6] = 0xff; - buf[offset+7] = 0x7f; - } -} -module.exports.writeInt64LE = writeInt64LE; diff --git a/node_modules/buffer-more-ints/package.json b/node_modules/buffer-more-ints/package.json deleted file mode 100644 index 11998f2..0000000 --- a/node_modules/buffer-more-ints/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "_from": "buffer-more-ints@0.0.2", - "_id": "buffer-more-ints@0.0.2", - "_inBundle": false, - "_integrity": "sha1-JrOIXRD6E9t/wBquOquHAZngEkw=", - "_location": "/buffer-more-ints", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "buffer-more-ints@0.0.2", - "name": "buffer-more-ints", - "escapedName": "buffer-more-ints", - "rawSpec": "0.0.2", - "saveSpec": null, - "fetchSpec": "0.0.2" - }, - "_requiredBy": [ - "/amqplib", - "/bitsyntax" - ], - "_resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-0.0.2.tgz", - "_shasum": "26b3885d10fa13db7fc01aae3aab870199e0124c", - "_spec": "buffer-more-ints@0.0.2", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", - "author": { - "name": "David Wragg", - "email": "david@wragg.org" - }, - "bugs": { - "url": "https://github.com/dpw/node-buffer-more-ints/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Add support for more integer widths to Buffer", - "devDependencies": { - "nodeunit": "" - }, - "homepage": "https://github.com/dpw/node-buffer-more-ints", - "main": "buffer-more-ints.js", - "name": "buffer-more-ints", - "repository": { - "type": "git", - "url": "git+https://github.com/dpw/node-buffer-more-ints.git" - }, - "scripts": { - "test": "node ./node_modules/nodeunit/bin/nodeunit buffer-more-ints-tests.js" - }, - "version": "0.0.2" -} diff --git a/node_modules/buffer-more-ints/polyfill.js b/node_modules/buffer-more-ints/polyfill.js deleted file mode 100644 index 762fd98..0000000 --- a/node_modules/buffer-more-ints/polyfill.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -var bmi = require('./buffer-more-ints'); - -Buffer.isContiguousInt = bmi.isContiguousInt; -Buffer.assertContiguousInt = bmi.assertContiguousInt; - -['UInt', 'Int'].forEach(function (signed) { - ['24', '40', '48', '56', '64'].forEach(function (size) { - ['BE', 'LE'].forEach(function (endian) { - var read = 'read' + signed + size + endian; - var reader = bmi[read]; - Buffer.prototype[read] = function(offset, noAssert) { - return reader(this, offset, noAssert); - }; - var write = 'write' + signed + size + endian; - var writer = bmi[write]; - Buffer.prototype[write] = function(val, offset, noAssert) { - writer(this, val, offset, noAssert); - }; - }); - }); -}); - -// Buffer.prototype.read{UInt,Int}8 returns undefined if the offset is -// outside of the buffer, unlike for other widths. These functions -// make it consistent with the others. -var consistent_readX8 = { - readUInt8: function (offset, noAssert) { - return this.readUInt8(offset, noAssert) || 0; - }, - readInt8: function (offset, noAssert) { - return this.readInt8(offset, noAssert) || 0; - } -}; - -function make_accessor(read, prefix, suffix) { - var accessors = [false, - (read ? consistent_readX8 : Buffer.prototype)[prefix + 8]]; - - for (var i = 16; i <= 64; i += 8) { - accessors.push(Buffer.prototype[prefix + i + suffix]); - } - - if (read) { - Buffer.prototype[prefix + suffix] = function (len, offset, noAssert) { - var reader = accessors[len]; - if (reader) { - return reader.call(this, offset, noAssert); - } else { - throw new Error("Cannot read integer of length " + len); - } - }; - } else { - Buffer.prototype[prefix + suffix] = function (len, val, offset, noAssert) { - var writer = accessors[len]; - if (writer) { - return writer.call(this, val, offset, noAssert); - } else { - throw new Error("Cannot write integer of length " + len); - } - } - } -} - -['UInt', 'Int'].forEach(function (t) { - ['BE', 'LE'].forEach(function (e) { - make_accessor(true, "read" + t, e); - make_accessor(false, "write" + t, e); - }); -}); diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE deleted file mode 100644 index d8d7f94..0000000 --- a/node_modules/core-util-is/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Node.js contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b41..0000000 --- a/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return 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'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json deleted file mode 100644 index 4c7ab94..0000000 --- a/node_modules/core-util-is/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "core-util-is@~1.0.0", - "_id": "core-util-is@1.0.2", - "_inBundle": false, - "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", - "_location": "/core-util-is", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "core-util-is@~1.0.0", - "name": "core-util-is", - "escapedName": "core-util-is", - "rawSpec": "~1.0.0", - "saveSpec": null, - "fetchSpec": "~1.0.0" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", - "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", - "_spec": "core-util-is@~1.0.0", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The `util.is*` functions introduced in Node v0.12.", - "devDependencies": { - "tap": "^2.3.0" - }, - "homepage": "https://github.com/isaacs/core-util-is#readme", - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "license": "MIT", - "main": "lib/util.js", - "name": "core-util-is", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is.git" - }, - "scripts": { - "test": "tap test.js" - }, - "version": "1.0.2" -} diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js deleted file mode 100644 index 1a490c6..0000000 --- a/node_modules/core-util-is/test.js +++ /dev/null @@ -1,68 +0,0 @@ -var assert = require('tap'); - -var t = require('./lib/util'); - -assert.equal(t.isArray([]), true); -assert.equal(t.isArray({}), false); - -assert.equal(t.isBoolean(null), false); -assert.equal(t.isBoolean(true), true); -assert.equal(t.isBoolean(false), true); - -assert.equal(t.isNull(null), true); -assert.equal(t.isNull(undefined), false); -assert.equal(t.isNull(false), false); -assert.equal(t.isNull(), false); - -assert.equal(t.isNullOrUndefined(null), true); -assert.equal(t.isNullOrUndefined(undefined), true); -assert.equal(t.isNullOrUndefined(false), false); -assert.equal(t.isNullOrUndefined(), true); - -assert.equal(t.isNumber(null), false); -assert.equal(t.isNumber('1'), false); -assert.equal(t.isNumber(1), true); - -assert.equal(t.isString(null), false); -assert.equal(t.isString('1'), true); -assert.equal(t.isString(1), false); - -assert.equal(t.isSymbol(null), false); -assert.equal(t.isSymbol('1'), false); -assert.equal(t.isSymbol(1), false); -assert.equal(t.isSymbol(Symbol()), true); - -assert.equal(t.isUndefined(null), false); -assert.equal(t.isUndefined(undefined), true); -assert.equal(t.isUndefined(false), false); -assert.equal(t.isUndefined(), true); - -assert.equal(t.isRegExp(null), false); -assert.equal(t.isRegExp('1'), false); -assert.equal(t.isRegExp(new RegExp()), true); - -assert.equal(t.isObject({}), true); -assert.equal(t.isObject([]), true); -assert.equal(t.isObject(new RegExp()), true); -assert.equal(t.isObject(new Date()), true); - -assert.equal(t.isDate(null), false); -assert.equal(t.isDate('1'), false); -assert.equal(t.isDate(new Date()), true); - -assert.equal(t.isError(null), false); -assert.equal(t.isError({ err: true }), false); -assert.equal(t.isError(new Error()), true); - -assert.equal(t.isFunction(null), false); -assert.equal(t.isFunction({ }), false); -assert.equal(t.isFunction(function() {}), true); - -assert.equal(t.isPrimitive(null), true); -assert.equal(t.isPrimitive(''), true); -assert.equal(t.isPrimitive(0), true); -assert.equal(t.isPrimitive(new Date()), false); - -assert.equal(t.isBuffer(null), false); -assert.equal(t.isBuffer({}), false); -assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js deleted file mode 100644 index 3b94763..0000000 --- a/node_modules/inherits/inherits.js +++ /dev/null @@ -1,7 +0,0 @@ -try { - var util = require('util'); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = require('./inherits_browser.js'); -} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a7..0000000 --- a/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json deleted file mode 100644 index aeeee23..0000000 --- a/node_modules/inherits/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "inherits@~2.0.1", - "_id": "inherits@2.0.3", - "_inBundle": false, - "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", - "_location": "/inherits", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "inherits@~2.0.1", - "name": "inherits", - "escapedName": "inherits", - "rawSpec": "~2.0.1", - "saveSpec": null, - "fetchSpec": "~2.0.1" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "_shasum": "633c2c83e3da42a502f52466022480f4208261de", - "_spec": "inherits@~2.0.1", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", - "browser": "./inherits_browser.js", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "devDependencies": { - "tap": "^7.1.0" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ], - "homepage": "https://github.com/isaacs/inherits#readme", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "license": "ISC", - "main": "./inherits.js", - "name": "inherits", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "scripts": { - "test": "node test" - }, - "version": "2.0.3" -} diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md deleted file mode 100644 index 052a62b..0000000 --- a/node_modules/isarray/README.md +++ /dev/null @@ -1,54 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/isarray/build/build.js b/node_modules/isarray/build/build.js deleted file mode 100644 index ec58596..0000000 --- a/node_modules/isarray/build/build.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Require the given path. - * - * @param {String} path - * @return {Object} exports - * @api public - */ - -function require(path, parent, orig) { - var resolved = require.resolve(path); - - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; - module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); - } - - return module.exports; -} - -/** - * Registered modules. - */ - -require.modules = {}; - -/** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. - * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - var index = path + '/index.js'; - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - } - - if (require.aliases.hasOwnProperty(index)) { - return require.aliases[index]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path - * @param {Function} definition - * @api private - */ - -require.register = function(path, definition) { - require.modules[path] = definition; -}; - -/** - * Alias a module definition. - * - * @param {String} from - * @param {String} to - * @api private - */ - -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; - }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; -}; -require.register("isarray/index.js", function(exports, require, module){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -}); -require.alias("isarray/index.js", "isarray/index.js"); - diff --git a/node_modules/isarray/component.json b/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/node_modules/isarray/index.js b/node_modules/isarray/index.js deleted file mode 100644 index 5f5ad45..0000000 --- a/node_modules/isarray/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json deleted file mode 100644 index c1d302c..0000000 --- a/node_modules/isarray/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "_from": "isarray@0.0.1", - "_id": "isarray@0.0.1", - "_inBundle": false, - "_integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", - "_location": "/isarray", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "isarray@0.0.1", - "name": "isarray", - "escapedName": "isarray", - "rawSpec": "0.0.1", - "saveSpec": null, - "fetchSpec": "0.0.1" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "_spec": "isarray@0.0.1", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "bugs": { - "url": "https://github.com/juliangruber/isarray/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Array#isArray for older browsers", - "devDependencies": { - "tap": "*" - }, - "homepage": "https://github.com/juliangruber/isarray", - "keywords": [ - "browser", - "isarray", - "array" - ], - "license": "MIT", - "main": "index.js", - "name": "isarray", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "version": "0.0.1" -} diff --git a/node_modules/readable-stream/.npmignore b/node_modules/readable-stream/.npmignore deleted file mode 100644 index 38344f8..0000000 --- a/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/node_modules/readable-stream/LICENSE b/node_modules/readable-stream/LICENSE deleted file mode 100644 index e3d4e69..0000000 --- a/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/readable-stream/README.md b/node_modules/readable-stream/README.md deleted file mode 100644 index e46b823..0000000 --- a/node_modules/readable-stream/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# readable-stream - -***Node-core streams for userland*** - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png&months=6&height=3)](https://nodei.co/npm/readable-stream/) - -This package is a mirror of the Streams2 and Streams3 implementations in Node-core. - -If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. - -**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. - -**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` - diff --git a/node_modules/readable-stream/duplex.js b/node_modules/readable-stream/duplex.js deleted file mode 100644 index ca807af..0000000 --- a/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/readable-stream/float.patch b/node_modules/readable-stream/float.patch deleted file mode 100644 index b984607..0000000 --- a/node_modules/readable-stream/float.patch +++ /dev/null @@ -1,923 +0,0 @@ -diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js -index c5a741c..a2e0d8e 100644 ---- a/lib/_stream_duplex.js -+++ b/lib/_stream_duplex.js -@@ -26,8 +26,8 @@ - - module.exports = Duplex; - var util = require('util'); --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('./_stream_readable'); -+var Writable = require('./_stream_writable'); - - util.inherits(Duplex, Readable); - -diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js -index a5e9864..330c247 100644 ---- a/lib/_stream_passthrough.js -+++ b/lib/_stream_passthrough.js -@@ -25,7 +25,7 @@ - - module.exports = PassThrough; - --var Transform = require('_stream_transform'); -+var Transform = require('./_stream_transform'); - var util = require('util'); - util.inherits(PassThrough, Transform); - -diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js -index 0c3fe3e..90a8298 100644 ---- a/lib/_stream_readable.js -+++ b/lib/_stream_readable.js -@@ -23,10 +23,34 @@ module.exports = Readable; - Readable.ReadableState = ReadableState; - - var EE = require('events').EventEmitter; -+if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { -+ return emitter.listeners(type).length; -+}; -+ -+if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { -+ return setTimeout(fn, 0); -+}; -+if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { -+ return clearTimeout(i); -+}; -+ - var Stream = require('stream'); - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - var StringDecoder; --var debug = util.debuglog('stream'); -+var debug; -+if (util.debuglog) -+ debug = util.debuglog('stream'); -+else try { -+ debug = require('debuglog')('stream'); -+} catch (er) { -+ debug = function() {}; -+} - - util.inherits(Readable, Stream); - -@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) { - - - function onEofChunk(stream, state) { -- if (state.decoder && !state.ended) { -+ if (state.decoder && !state.ended && state.decoder.end) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); -diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js -index b1f9fcc..b0caf57 100644 ---- a/lib/_stream_transform.js -+++ b/lib/_stream_transform.js -@@ -64,8 +64,14 @@ - - module.exports = Transform; - --var Duplex = require('_stream_duplex'); -+var Duplex = require('./_stream_duplex'); - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - util.inherits(Transform, Duplex); - - -diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js -index ba2e920..f49288b 100644 ---- a/lib/_stream_writable.js -+++ b/lib/_stream_writable.js -@@ -27,6 +27,12 @@ module.exports = Writable; - Writable.WritableState = WritableState; - - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - var Stream = require('stream'); - - util.inherits(Writable, Stream); -@@ -119,7 +125,7 @@ function WritableState(options, stream) { - function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. -- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) -+ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) - return new Writable(options); - - this._writableState = new WritableState(options, this); -diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js -index e3787e4..8cd2127 100644 ---- a/test/simple/test-stream-big-push.js -+++ b/test/simple/test-stream-big-push.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - var str = 'asdfasdfasdfasdfasdf'; - - var r = new stream.Readable({ -diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js -index bb73777..d40efc7 100644 ---- a/test/simple/test-stream-end-paused.js -+++ b/test/simple/test-stream-end-paused.js -@@ -25,7 +25,7 @@ var gotEnd = false; - - // Make sure we don't miss the end event for paused 0-length streams - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var stream = new Readable(); - var calledRead = false; - stream._read = function() { -diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js -index b46ee90..0be8366 100644 ---- a/test/simple/test-stream-pipe-after-end.js -+++ b/test/simple/test-stream-pipe-after-end.js -@@ -22,8 +22,8 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var util = require('util'); - - util.inherits(TestReadable, Readable); -diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js -deleted file mode 100644 -index f689358..0000000 ---- a/test/simple/test-stream-pipe-cleanup.js -+++ /dev/null -@@ -1,122 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- --// This test asserts that Stream.prototype.pipe does not leave listeners --// hanging on the source or dest. -- --var common = require('../common'); --var stream = require('stream'); --var assert = require('assert'); --var util = require('util'); -- --function Writable() { -- this.writable = true; -- this.endCalls = 0; -- stream.Stream.call(this); --} --util.inherits(Writable, stream.Stream); --Writable.prototype.end = function() { -- this.endCalls++; --}; -- --Writable.prototype.destroy = function() { -- this.endCalls++; --}; -- --function Readable() { -- this.readable = true; -- stream.Stream.call(this); --} --util.inherits(Readable, stream.Stream); -- --function Duplex() { -- this.readable = true; -- Writable.call(this); --} --util.inherits(Duplex, Writable); -- --var i = 0; --var limit = 100; -- --var w = new Writable(); -- --var r; -- --for (i = 0; i < limit; i++) { -- r = new Readable(); -- r.pipe(w); -- r.emit('end'); --} --assert.equal(0, r.listeners('end').length); --assert.equal(limit, w.endCalls); -- --w.endCalls = 0; -- --for (i = 0; i < limit; i++) { -- r = new Readable(); -- r.pipe(w); -- r.emit('close'); --} --assert.equal(0, r.listeners('close').length); --assert.equal(limit, w.endCalls); -- --w.endCalls = 0; -- --r = new Readable(); -- --for (i = 0; i < limit; i++) { -- w = new Writable(); -- r.pipe(w); -- w.emit('close'); --} --assert.equal(0, w.listeners('close').length); -- --r = new Readable(); --w = new Writable(); --var d = new Duplex(); --r.pipe(d); // pipeline A --d.pipe(w); // pipeline B --assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup --assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup --assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup --assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 1); // B.cleanup -- --r.emit('end'); --assert.equal(d.endCalls, 1); --assert.equal(w.endCalls, 0); --assert.equal(r.listeners('end').length, 0); --assert.equal(r.listeners('close').length, 0); --assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup --assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 1); // B.cleanup -- --d.emit('end'); --assert.equal(d.endCalls, 1); --assert.equal(w.endCalls, 1); --assert.equal(r.listeners('end').length, 0); --assert.equal(r.listeners('close').length, 0); --assert.equal(d.listeners('end').length, 0); --assert.equal(d.listeners('close').length, 0); --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 0); -diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js -index c5d724b..c7d6b7d 100644 ---- a/test/simple/test-stream-pipe-error-handling.js -+++ b/test/simple/test-stream-pipe-error-handling.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var Stream = require('stream').Stream; -+var Stream = require('../../').Stream; - - (function testErrorListenerCatches() { - var source = new Stream(); -diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js -index cb9d5fe..56f8d61 100644 ---- a/test/simple/test-stream-pipe-event.js -+++ b/test/simple/test-stream-pipe-event.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common'); --var stream = require('stream'); -+var stream = require('../../'); - var assert = require('assert'); - var util = require('util'); - -diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js -index f2e6ec2..a5c9bf9 100644 ---- a/test/simple/test-stream-push-order.js -+++ b/test/simple/test-stream-push-order.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var assert = require('assert'); - - var s = new Readable({ -diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js -index 06f43dc..1701a9a 100644 ---- a/test/simple/test-stream-push-strings.js -+++ b/test/simple/test-stream-push-strings.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var util = require('util'); - - util.inherits(MyStream, Readable); -diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js -index ba6a577..a8e6f7b 100644 ---- a/test/simple/test-stream-readable-event.js -+++ b/test/simple/test-stream-readable-event.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - (function first() { - // First test, not reading when the readable is added. -diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js -index 2891ad6..11689ba 100644 ---- a/test/simple/test-stream-readable-flow-recursion.js -+++ b/test/simple/test-stream-readable-flow-recursion.js -@@ -27,7 +27,7 @@ var assert = require('assert'); - // more data continuously, but without triggering a nextTick - // warning or RangeError. - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - // throw an error if we trigger a nextTick warning. - process.throwDeprecation = true; -diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js -index 0c96476..7827538 100644 ---- a/test/simple/test-stream-unshift-empty-chunk.js -+++ b/test/simple/test-stream-unshift-empty-chunk.js -@@ -24,7 +24,7 @@ var assert = require('assert'); - - // This test verifies that stream.unshift(Buffer(0)) or - // stream.unshift('') does not set state.reading=false. --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - var r = new Readable(); - var nChunks = 10; -diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js -index 83fd9fa..17c18aa 100644 ---- a/test/simple/test-stream-unshift-read-race.js -+++ b/test/simple/test-stream-unshift-read-race.js -@@ -29,7 +29,7 @@ var assert = require('assert'); - // 3. push() after the EOF signaling null is an error. - // 4. _read() is not called after pushing the EOF null chunk. - --var stream = require('stream'); -+var stream = require('../../'); - var hwm = 10; - var r = stream.Readable({ highWaterMark: hwm }); - var chunks = 10; -@@ -51,7 +51,14 @@ r._read = function(n) { - - function push(fast) { - assert(!pushedNull, 'push() after null push'); -- var c = pos >= data.length ? null : data.slice(pos, pos + n); -+ var c; -+ if (pos >= data.length) -+ c = null; -+ else { -+ if (n + pos > data.length) -+ n = data.length - pos; -+ c = data.slice(pos, pos + n); -+ } - pushedNull = c === null; - if (fast) { - pos += n; -diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js -index 5b49e6e..b5321f3 100644 ---- a/test/simple/test-stream-writev.js -+++ b/test/simple/test-stream-writev.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var stream = require('stream'); -+var stream = require('../../'); - - var queue = []; - for (var decode = 0; decode < 2; decode++) { -diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js -index 3814bf0..248c1be 100644 ---- a/test/simple/test-stream2-basic.js -+++ b/test/simple/test-stream2-basic.js -@@ -21,7 +21,7 @@ - - - var common = require('../common.js'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js -index 6cdd4e9..f0fa84b 100644 ---- a/test/simple/test-stream2-compatibility.js -+++ b/test/simple/test-stream2-compatibility.js -@@ -21,7 +21,7 @@ - - - var common = require('../common.js'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js -index 39b274f..006a19b 100644 ---- a/test/simple/test-stream2-finish-pipe.js -+++ b/test/simple/test-stream2-finish-pipe.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var stream = require('stream'); -+var stream = require('../../'); - var Buffer = require('buffer').Buffer; - - var r = new stream.Readable(); -diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js -deleted file mode 100644 -index e162406..0000000 ---- a/test/simple/test-stream2-fs.js -+++ /dev/null -@@ -1,72 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- --var common = require('../common.js'); --var R = require('_stream_readable'); --var assert = require('assert'); -- --var fs = require('fs'); --var FSReadable = fs.ReadStream; -- --var path = require('path'); --var file = path.resolve(common.fixturesDir, 'x1024.txt'); -- --var size = fs.statSync(file).size; -- --var expectLengths = [1024]; -- --var util = require('util'); --var Stream = require('stream'); -- --util.inherits(TestWriter, Stream); -- --function TestWriter() { -- Stream.apply(this); -- this.buffer = []; -- this.length = 0; --} -- --TestWriter.prototype.write = function(c) { -- this.buffer.push(c.toString()); -- this.length += c.length; -- return true; --}; -- --TestWriter.prototype.end = function(c) { -- if (c) this.buffer.push(c.toString()); -- this.emit('results', this.buffer); --} -- --var r = new FSReadable(file); --var w = new TestWriter(); -- --w.on('results', function(res) { -- console.error(res, w.length); -- assert.equal(w.length, size); -- var l = 0; -- assert.deepEqual(res.map(function (c) { -- return c.length; -- }), expectLengths); -- console.log('ok'); --}); -- --r.pipe(w); -diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js -deleted file mode 100644 -index 15cffc2..0000000 ---- a/test/simple/test-stream2-httpclient-response-end.js -+++ /dev/null -@@ -1,52 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- --var common = require('../common.js'); --var assert = require('assert'); --var http = require('http'); --var msg = 'Hello'; --var readable_event = false; --var end_event = false; --var server = http.createServer(function(req, res) { -- res.writeHead(200, {'Content-Type': 'text/plain'}); -- res.end(msg); --}).listen(common.PORT, function() { -- http.get({port: common.PORT}, function(res) { -- var data = ''; -- res.on('readable', function() { -- console.log('readable event'); -- readable_event = true; -- data += res.read(); -- }); -- res.on('end', function() { -- console.log('end event'); -- end_event = true; -- assert.strictEqual(msg, data); -- server.close(); -- }); -- }); --}); -- --process.on('exit', function() { -- assert(readable_event); -- assert(end_event); --}); -- -diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js -index 2fbfbca..667985b 100644 ---- a/test/simple/test-stream2-large-read-stall.js -+++ b/test/simple/test-stream2-large-read-stall.js -@@ -30,7 +30,7 @@ var PUSHSIZE = 20; - var PUSHCOUNT = 1000; - var HWM = 50; - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var r = new Readable({ - highWaterMark: HWM - }); -@@ -39,23 +39,23 @@ var rs = r._readableState; - r._read = push; - - r.on('readable', function() { -- console.error('>> readable'); -+ //console.error('>> readable'); - do { -- console.error(' > read(%d)', READSIZE); -+ //console.error(' > read(%d)', READSIZE); - var ret = r.read(READSIZE); -- console.error(' < %j (%d remain)', ret && ret.length, rs.length); -+ //console.error(' < %j (%d remain)', ret && ret.length, rs.length); - } while (ret && ret.length === READSIZE); - -- console.error('<< after read()', -- ret && ret.length, -- rs.needReadable, -- rs.length); -+ //console.error('<< after read()', -+ // ret && ret.length, -+ // rs.needReadable, -+ // rs.length); - }); - - var endEmitted = false; - r.on('end', function() { - endEmitted = true; -- console.error('end'); -+ //console.error('end'); - }); - - var pushes = 0; -@@ -64,11 +64,11 @@ function push() { - return; - - if (pushes++ === PUSHCOUNT) { -- console.error(' push(EOF)'); -+ //console.error(' push(EOF)'); - return r.push(null); - } - -- console.error(' push #%d', pushes); -+ //console.error(' push #%d', pushes); - if (r.push(new Buffer(PUSHSIZE))) - setTimeout(push); - } -diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js -index 3e6931d..ff47d89 100644 ---- a/test/simple/test-stream2-objects.js -+++ b/test/simple/test-stream2-objects.js -@@ -21,8 +21,8 @@ - - - var common = require('../common.js'); --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var assert = require('assert'); - - // tiny node-tap lookalike. -diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js -index cf7531c..e3f3e4e 100644 ---- a/test/simple/test-stream2-pipe-error-handling.js -+++ b/test/simple/test-stream2-pipe-error-handling.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - - (function testErrorListenerCatches() { - var count = 1000; -diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js -index 5e8e3cb..53b2616 100755 ---- a/test/simple/test-stream2-pipe-error-once-listener.js -+++ b/test/simple/test-stream2-pipe-error-once-listener.js -@@ -24,7 +24,7 @@ var common = require('../common.js'); - var assert = require('assert'); - - var util = require('util'); --var stream = require('stream'); -+var stream = require('../../'); - - - var Read = function() { -diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js -index b63edc3..eb2b0e9 100644 ---- a/test/simple/test-stream2-push.js -+++ b/test/simple/test-stream2-push.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var stream = require('stream'); -+var stream = require('../../'); - var Readable = stream.Readable; - var Writable = stream.Writable; - var assert = require('assert'); -diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js -index e8a7305..9740a47 100644 ---- a/test/simple/test-stream2-read-sync-stack.js -+++ b/test/simple/test-stream2-read-sync-stack.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var r = new Readable(); - var N = 256 * 1024; - -diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js -index cd30178..4b1659d 100644 ---- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js -+++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js -@@ -22,10 +22,9 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - test1(); --test2(); - - function test1() { - var r = new Readable(); -@@ -88,31 +87,3 @@ function test1() { - console.log('ok'); - }); - } -- --function test2() { -- var r = new Readable({ encoding: 'base64' }); -- var reads = 5; -- r._read = function(n) { -- if (!reads--) -- return r.push(null); // EOF -- else -- return r.push(new Buffer('x')); -- }; -- -- var results = []; -- function flow() { -- var chunk; -- while (null !== (chunk = r.read())) -- results.push(chunk + ''); -- } -- r.on('readable', flow); -- r.on('end', function() { -- results.push('EOF'); -- }); -- flow(); -- -- process.on('exit', function() { -- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); -- console.log('ok'); -- }); --} -diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js -index 7c96ffe..04a96f5 100644 ---- a/test/simple/test-stream2-readable-from-list.js -+++ b/test/simple/test-stream2-readable-from-list.js -@@ -21,7 +21,7 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var fromList = require('_stream_readable')._fromList; -+var fromList = require('../../lib/_stream_readable')._fromList; - - // tiny node-tap lookalike. - var tests = []; -diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js -index 675da8e..51fd3d5 100644 ---- a/test/simple/test-stream2-readable-legacy-drain.js -+++ b/test/simple/test-stream2-readable-legacy-drain.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Stream = require('stream'); -+var Stream = require('../../'); - var Readable = Stream.Readable; - - var r = new Readable(); -diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js -index 7314ae7..c971898 100644 ---- a/test/simple/test-stream2-readable-non-empty-end.js -+++ b/test/simple/test-stream2-readable-non-empty-end.js -@@ -21,7 +21,7 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var Readable = require('_stream_readable'); -+var Readable = require('../../lib/_stream_readable'); - - var len = 0; - var chunks = new Array(10); -diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js -index 2e5cf25..fd8a3dc 100644 ---- a/test/simple/test-stream2-readable-wrap-empty.js -+++ b/test/simple/test-stream2-readable-wrap-empty.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); -+var Readable = require('../../lib/_stream_readable'); - var EE = require('events').EventEmitter; - - var oldStream = new EE(); -diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js -index 90eea01..6b177f7 100644 ---- a/test/simple/test-stream2-readable-wrap.js -+++ b/test/simple/test-stream2-readable-wrap.js -@@ -22,8 +22,8 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var EE = require('events').EventEmitter; - - var testRuns = 0, completedRuns = 0; -diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js -index 5d2c32a..685531b 100644 ---- a/test/simple/test-stream2-set-encoding.js -+++ b/test/simple/test-stream2-set-encoding.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var util = require('util'); - - // tiny node-tap lookalike. -diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js -index 9c9ddd8..a0cacc6 100644 ---- a/test/simple/test-stream2-transform.js -+++ b/test/simple/test-stream2-transform.js -@@ -21,8 +21,8 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var PassThrough = require('_stream_passthrough'); --var Transform = require('_stream_transform'); -+var PassThrough = require('../../').PassThrough; -+var Transform = require('../../').Transform; - - // tiny node-tap lookalike. - var tests = []; -diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js -index d66dc3c..365b327 100644 ---- a/test/simple/test-stream2-unpipe-drain.js -+++ b/test/simple/test-stream2-unpipe-drain.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - var crypto = require('crypto'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js -index 99f8746..17c92ae 100644 ---- a/test/simple/test-stream2-unpipe-leak.js -+++ b/test/simple/test-stream2-unpipe-leak.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - - var chunk = new Buffer('hallo'); - -diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js -index 704100c..209c3a6 100644 ---- a/test/simple/test-stream2-writable.js -+++ b/test/simple/test-stream2-writable.js -@@ -20,8 +20,8 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var W = require('_stream_writable'); --var D = require('_stream_duplex'); -+var W = require('../../').Writable; -+var D = require('../../').Duplex; - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js -index b91bde3..2f72c15 100644 ---- a/test/simple/test-stream3-pause-then-read.js -+++ b/test/simple/test-stream3-pause-then-read.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var stream = require('stream'); -+var stream = require('../../'); - var Readable = stream.Readable; - var Writable = stream.Writable; - diff --git a/node_modules/readable-stream/package.json b/node_modules/readable-stream/package.json deleted file mode 100644 index 048bab6..0000000 --- a/node_modules/readable-stream/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "_from": "readable-stream@1.x >=1.1.9", - "_id": "readable-stream@1.1.14", - "_inBundle": false, - "_integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=", - "_location": "/readable-stream", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "readable-stream@1.x >=1.1.9", - "name": "readable-stream", - "escapedName": "readable-stream", - "rawSpec": "1.x >=1.1.9", - "saveSpec": null, - "fetchSpec": "1.x >=1.1.9" - }, - "_requiredBy": [ - "/amqplib" - ], - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz", - "_shasum": "7cf4c54ef648e3813084c636dd2079e166c081d9", - "_spec": "readable-stream@1.x >=1.1.9", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "browser": { - "util": false - }, - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "bundleDependencies": false, - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.1", - "isarray": "0.0.1", - "string_decoder": "~0.10.x" - }, - "deprecated": false, - "description": "Streams3, a user-land copy of the stream library from Node.js v0.11.x", - "devDependencies": { - "tap": "~0.2.6" - }, - "homepage": "https://github.com/isaacs/readable-stream#readme", - "keywords": [ - "readable", - "stream", - "pipe" - ], - "license": "MIT", - "main": "readable.js", - "name": "readable-stream", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream.git" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "version": "1.1.14" -} diff --git a/node_modules/readable-stream/passthrough.js b/node_modules/readable-stream/passthrough.js deleted file mode 100644 index 27e8d8a..0000000 --- a/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/readable-stream/readable.js b/node_modules/readable-stream/readable.js deleted file mode 100644 index 2a8b5c6..0000000 --- a/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,10 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = require('stream'); -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); -if (!process.browser && process.env.READABLE_STREAM === 'disable') { - module.exports = require('stream'); -} diff --git a/node_modules/readable-stream/transform.js b/node_modules/readable-stream/transform.js deleted file mode 100644 index 5d482f0..0000000 --- a/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/readable-stream/writable.js b/node_modules/readable-stream/writable.js deleted file mode 100644 index e1e9efd..0000000 --- a/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/safe-buffer/.travis.yml b/node_modules/safe-buffer/.travis.yml deleted file mode 100644 index 7b20f28..0000000 --- a/node_modules/safe-buffer/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - 'node' - - '5' - - '4' - - '0.12' - - '0.10' diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068ce..0000000 --- a/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md deleted file mode 100644 index e9a81af..0000000 --- a/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,584 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js deleted file mode 100644 index 22438da..0000000 --- a/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,62 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json deleted file mode 100644 index 8d9d93d..0000000 --- a/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@^5.0.1", - "_id": "safe-buffer@5.1.1", - "_inBundle": false, - "_integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", - "_location": "/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "safe-buffer@^5.0.1", - "name": "safe-buffer", - "escapedName": "safe-buffer", - "rawSpec": "^5.0.1", - "saveSpec": null, - "fetchSpec": "^5.0.1" - }, - "_requiredBy": [ - "/amqplib" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", - "_shasum": "893312af69b2123def71f57889001671eeb2c853", - "_spec": "safe-buffer@^5.0.1", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/amqplib", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Safer Node.js Buffer API", - "devDependencies": { - "standard": "*", - "tape": "^4.0.0", - "zuul": "^3.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "name": "safe-buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "5.1.1" -} diff --git a/node_modules/safe-buffer/test.js b/node_modules/safe-buffer/test.js deleted file mode 100644 index 4925059..0000000 --- a/node_modules/safe-buffer/test.js +++ /dev/null @@ -1,101 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ - -var test = require('tape') -var SafeBuffer = require('./').Buffer - -test('new SafeBuffer(value) works just like Buffer', function (t) { - t.deepEqual(new SafeBuffer('hey'), new Buffer('hey')) - t.deepEqual(new SafeBuffer('hey', 'utf8'), new Buffer('hey', 'utf8')) - t.deepEqual(new SafeBuffer('686579', 'hex'), new Buffer('686579', 'hex')) - t.deepEqual(new SafeBuffer([1, 2, 3]), new Buffer([1, 2, 3])) - t.deepEqual(new SafeBuffer(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) - - t.equal(typeof SafeBuffer.isBuffer, 'function') - t.equal(SafeBuffer.isBuffer(new SafeBuffer('hey')), true) - t.equal(Buffer.isBuffer(new SafeBuffer('hey')), true) - t.notOk(SafeBuffer.isBuffer({})) - - t.end() -}) - -test('SafeBuffer.from(value) converts to a Buffer', function (t) { - t.deepEqual(SafeBuffer.from('hey'), new Buffer('hey')) - t.deepEqual(SafeBuffer.from('hey', 'utf8'), new Buffer('hey', 'utf8')) - t.deepEqual(SafeBuffer.from('686579', 'hex'), new Buffer('686579', 'hex')) - t.deepEqual(SafeBuffer.from([1, 2, 3]), new Buffer([1, 2, 3])) - t.deepEqual(SafeBuffer.from(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) - - t.end() -}) - -test('SafeBuffer.alloc(number) returns zeroed-out memory', function (t) { - for (var i = 0; i < 10; i++) { - var expected1 = new Buffer(1000) - expected1.fill(0) - t.deepEqual(SafeBuffer.alloc(1000), expected1) - - var expected2 = new Buffer(1000 * 1000) - expected2.fill(0) - t.deepEqual(SafeBuffer.alloc(1000 * 1000), expected2) - } - t.end() -}) - -test('SafeBuffer.allocUnsafe(number)', function (t) { - var buf = SafeBuffer.allocUnsafe(100) // unitialized memory - t.equal(buf.length, 100) - t.equal(SafeBuffer.isBuffer(buf), true) - t.equal(Buffer.isBuffer(buf), true) - t.end() -}) - -test('SafeBuffer.from() throws with number types', function (t) { - t.plan(5) - t.throws(function () { - SafeBuffer.from(0) - }) - t.throws(function () { - SafeBuffer.from(-1) - }) - t.throws(function () { - SafeBuffer.from(NaN) - }) - t.throws(function () { - SafeBuffer.from(Infinity) - }) - t.throws(function () { - SafeBuffer.from(99) - }) -}) - -test('SafeBuffer.allocUnsafe() throws with non-number types', function (t) { - t.plan(4) - t.throws(function () { - SafeBuffer.allocUnsafe('hey') - }) - t.throws(function () { - SafeBuffer.allocUnsafe('hey', 'utf8') - }) - t.throws(function () { - SafeBuffer.allocUnsafe([1, 2, 3]) - }) - t.throws(function () { - SafeBuffer.allocUnsafe({}) - }) -}) - -test('SafeBuffer.alloc() throws with non-number types', function (t) { - t.plan(4) - t.throws(function () { - SafeBuffer.alloc('hey') - }) - t.throws(function () { - SafeBuffer.alloc('hey', 'utf8') - }) - t.throws(function () { - SafeBuffer.alloc([1, 2, 3]) - }) - t.throws(function () { - SafeBuffer.alloc({}) - }) -}) diff --git a/node_modules/string_decoder/.npmignore b/node_modules/string_decoder/.npmignore deleted file mode 100644 index 206320c..0000000 --- a/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE deleted file mode 100644 index 6de584a..0000000 --- a/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md deleted file mode 100644 index 4d2aa00..0000000 --- a/node_modules/string_decoder/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**string_decoder.js** (`require('string_decoder')`) from Node.js core - -Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. - -Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** - -The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/node_modules/string_decoder/index.js b/node_modules/string_decoder/index.js deleted file mode 100644 index b00e54f..0000000 --- a/node_modules/string_decoder/index.js +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = require('buffer').Buffer; - -var 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 true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - 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; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -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; -} diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json deleted file mode 100644 index b923280..0000000 --- a/node_modules/string_decoder/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "_from": "string_decoder@~0.10.x", - "_id": "string_decoder@0.10.31", - "_inBundle": false, - "_integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", - "_location": "/string_decoder", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "string_decoder@~0.10.x", - "name": "string_decoder", - "escapedName": "string_decoder", - "rawSpec": "~0.10.x", - "saveSpec": null, - "fetchSpec": "~0.10.x" - }, - "_requiredBy": [ - "/readable-stream" - ], - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "_spec": "string_decoder@~0.10.x", - "_where": "/Users/wilsonm/gits/wilsonmar/JMeter-Rabbit-AMQP/node_modules/readable-stream", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "The string_decoder module from Node core", - "devDependencies": { - "tap": "~0.4.8" - }, - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "main": "index.js", - "name": "string_decoder", - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "version": "0.10.31" -}