diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..2b48c8b
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1,6 @@
+# package directories
+node_modules
+jspm_packages
+
+# Serverless directories
+.serverless
\ No newline at end of file
diff --git a/.nvmrc b/.nvmrc
new file mode 100644
index 0000000..6a1fccf
--- /dev/null
+++ b/.nvmrc
@@ -0,0 +1 @@
+6.9.0
\ No newline at end of file
diff --git a/.serverless/cloudformation-template-create-stack.json b/.serverless/cloudformation-template-create-stack.json
new file mode 100644
index 0000000..3be3c87
--- /dev/null
+++ b/.serverless/cloudformation-template-create-stack.json
@@ -0,0 +1,16 @@
+{
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Description": "The AWS CloudFormation template for this Serverless application",
+ "Resources": {
+ "ServerlessDeploymentBucket": {
+ "Type": "AWS::S3::Bucket"
+ }
+ },
+ "Outputs": {
+ "ServerlessDeploymentBucketName": {
+ "Value": {
+ "Ref": "ServerlessDeploymentBucket"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.serverless/cloudformation-template-update-stack.json b/.serverless/cloudformation-template-update-stack.json
new file mode 100644
index 0000000..d29f2ab
--- /dev/null
+++ b/.serverless/cloudformation-template-update-stack.json
@@ -0,0 +1,416 @@
+{
+ "AWSTemplateFormatVersion": "2010-09-09",
+ "Description": "The AWS CloudFormation template for this Serverless application",
+ "Resources": {
+ "ServerlessDeploymentBucket": {
+ "Type": "AWS::S3::Bucket"
+ },
+ "IamRoleLambdaExecution": {
+ "Type": "AWS::IAM::Role",
+ "Properties": {
+ "AssumeRolePolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {
+ "Service": [
+ "lambda.amazonaws.com"
+ ]
+ },
+ "Action": [
+ "sts:AssumeRole"
+ ]
+ }
+ ]
+ },
+ "Path": "/"
+ }
+ },
+ "IamPolicyLambdaExecution": {
+ "Type": "AWS::IAM::Policy",
+ "Properties": {
+ "PolicyName": "dev-lti-lambda-lambda",
+ "PolicyDocument": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "logs:CreateLogGroup",
+ "logs:CreateLogStream",
+ "logs:PutLogEvents"
+ ],
+ "Resource": "arn:aws:logs:us-east-1:*:*"
+ }
+ ]
+ },
+ "Roles": [
+ {
+ "Ref": "IamRoleLambdaExecution"
+ }
+ ]
+ }
+ },
+ "LtiLambdaFunction": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "Code": {
+ "S3Bucket": {
+ "Ref": "ServerlessDeploymentBucket"
+ },
+ "S3Key": "serverless/lti-lambda/dev/1477516476677-2016-10-26T21:14:36.677Z/lti-lambda.zip"
+ },
+ "FunctionName": "lti-lambda-dev-lti",
+ "Handler": "lti.handler",
+ "MemorySize": 1024,
+ "Role": {
+ "Fn::GetAtt": [
+ "IamRoleLambdaExecution",
+ "Arn"
+ ]
+ },
+ "Runtime": "nodejs4.3",
+ "Timeout": 10
+ }
+ },
+ "ApiGatewayRestApi": {
+ "Type": "AWS::ApiGateway::RestApi",
+ "Properties": {
+ "Name": "dev-lti-lambda"
+ }
+ },
+ "ApiGatewayResourceLti": {
+ "Type": "AWS::ApiGateway::Resource",
+ "Properties": {
+ "ParentId": {
+ "Fn::GetAtt": [
+ "ApiGatewayRestApi",
+ "RootResourceId"
+ ]
+ },
+ "PathPart": "lti",
+ "RestApiId": {
+ "Ref": "ApiGatewayRestApi"
+ }
+ }
+ },
+ "ApiGatewayMethodLtiPost": {
+ "Type": "AWS::ApiGateway::Method",
+ "Properties": {
+ "AuthorizationType": "NONE",
+ "HttpMethod": "POST",
+ "MethodResponses": [
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 200
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 400
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 401
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 403
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 404
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 422
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 500
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 502
+ },
+ {
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Content-Type": true
+ },
+ "ResponseModels": {},
+ "StatusCode": 504
+ }
+ ],
+ "RequestParameters": {},
+ "Integration": {
+ "IntegrationHttpMethod": "POST",
+ "Type": "AWS",
+ "Uri": {
+ "Fn::Join": [
+ "",
+ [
+ "arn:aws:apigateway:",
+ {
+ "Ref": "AWS::Region"
+ },
+ ":lambda:path/2015-03-31/functions/",
+ {
+ "Fn::GetAtt": [
+ "LtiLambdaFunction",
+ "Arn"
+ ]
+ },
+ "/invocations"
+ ]
+ ]
+ },
+ "RequestTemplates": {
+ "application/json": "\n #define( $loop )\n {\n #foreach($key in $map.keySet())\n \"$util.escapeJavaScript($key)\":\n \"$util.escapeJavaScript($map.get($key))\"\n #if( $foreach.hasNext ) , #end\n #end\n }\n #end\n\n {\n \"body\": $input.json(\"$\"),\n \"method\": \"$context.httpMethod\",\n \"principalId\": \"$context.authorizer.principalId\",\n \"stage\": \"$context.stage\",\n\n #set( $map = $input.params().header )\n \"headers\": $loop,\n\n #set( $map = $input.params().querystring )\n \"query\": $loop,\n\n #set( $map = $input.params().path )\n \"path\": $loop,\n\n #set( $map = $context.identity )\n \"identity\": $loop,\n\n #set( $map = $stageVariables )\n \"stageVariables\": $loop\n }\n ",
+ "application/x-www-form-urlencoded": "\n #define( $body )\n {\n #foreach( $token in $input.path('$').split('&') )\n #set( $keyVal = $token.split('=') )\n #set( $keyValSize = $keyVal.size() )\n #if( $keyValSize >= 1 )\n #set( $key = $util.escapeJavaScript($util.urlDecode($keyVal[0])) )\n #if( $keyValSize >= 2 )\n #set( $val = $util.escapeJavaScript($util.urlDecode($keyVal[1])) )\n #else\n #set( $val = '' )\n #end\n \"$key\": \"$val\"#if($foreach.hasNext),#end\n #end\n #end\n }\n #end\n\n #define( $loop )\n {\n #foreach($key in $map.keySet())\n \"$util.escapeJavaScript($key)\":\n \"$util.escapeJavaScript($map.get($key))\"\n #if( $foreach.hasNext ) , #end\n #end\n }\n #end\n\n {\n \"body\": $body,\n \"method\": \"$context.httpMethod\",\n \"principalId\": \"$context.authorizer.principalId\",\n \"stage\": \"$context.stage\",\n\n #set( $map = $input.params().header )\n \"headers\": $loop,\n\n #set( $map = $input.params().querystring )\n \"query\": $loop,\n\n #set( $map = $input.params().path )\n \"path\": $loop,\n\n #set( $map = $context.identity )\n \"identity\": $loop,\n\n #set( $map = $stageVariables )\n \"stageVariables\": $loop\n }\n "
+ },
+ "PassthroughBehavior": "NEVER",
+ "IntegrationResponses": [
+ {
+ "StatusCode": 200,
+ "SelectionPattern": "",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 400,
+ "SelectionPattern": ".*\\[400\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 401,
+ "SelectionPattern": ".*\\[401\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 403,
+ "SelectionPattern": ".*\\[403\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 404,
+ "SelectionPattern": ".*\\[404\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 422,
+ "SelectionPattern": ".*\\[422\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 500,
+ "SelectionPattern": ".*(Process\\s?exited\\s?before\\s?completing\\s?request|\\[500\\]).*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 502,
+ "SelectionPattern": ".*\\[502\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ },
+ {
+ "StatusCode": 504,
+ "SelectionPattern": ".*\\[504\\].*",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Content-Type": "'text/html'"
+ },
+ "ResponseTemplates": {
+ "application/json": "$input.path('$').body"
+ }
+ }
+ ]
+ },
+ "ResourceId": {
+ "Ref": "ApiGatewayResourceLti"
+ },
+ "RestApiId": {
+ "Ref": "ApiGatewayRestApi"
+ }
+ }
+ },
+ "ApiGatewayMethodLtiOptions": {
+ "Type": "AWS::ApiGateway::Method",
+ "Properties": {
+ "AuthorizationType": "NONE",
+ "HttpMethod": "OPTIONS",
+ "MethodResponses": [
+ {
+ "ResponseModels": {},
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": true,
+ "method.response.header.Access-Control-Allow-Headers": true,
+ "method.response.header.Access-Control-Allow-Methods": true
+ },
+ "StatusCode": "200"
+ }
+ ],
+ "RequestParameters": {},
+ "Integration": {
+ "Type": "MOCK",
+ "RequestTemplates": {
+ "application/json": "{statusCode:200}"
+ },
+ "IntegrationResponses": [
+ {
+ "StatusCode": "200",
+ "ResponseParameters": {
+ "method.response.header.Access-Control-Allow-Origin": "'*'",
+ "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
+ "method.response.header.Access-Control-Allow-Methods": "'OPTIONS,POST'"
+ },
+ "ResponseTemplates": {
+ "application/json": ""
+ }
+ }
+ ]
+ },
+ "ResourceId": {
+ "Ref": "ApiGatewayResourceLti"
+ },
+ "RestApiId": {
+ "Ref": "ApiGatewayRestApi"
+ }
+ }
+ },
+ "ApiGatewayDeployment1477516476686": {
+ "Type": "AWS::ApiGateway::Deployment",
+ "Properties": {
+ "RestApiId": {
+ "Ref": "ApiGatewayRestApi"
+ },
+ "StageName": "dev"
+ },
+ "DependsOn": [
+ "ApiGatewayMethodLtiPost"
+ ]
+ },
+ "LtiLambdaPermissionApiGateway": {
+ "Type": "AWS::Lambda::Permission",
+ "Properties": {
+ "FunctionName": {
+ "Fn::GetAtt": [
+ "LtiLambdaFunction",
+ "Arn"
+ ]
+ },
+ "Action": "lambda:InvokeFunction",
+ "Principal": "apigateway.amazonaws.com"
+ }
+ }
+ },
+ "Outputs": {
+ "ServerlessDeploymentBucketName": {
+ "Value": {
+ "Ref": "ServerlessDeploymentBucket"
+ }
+ },
+ "LtiLambdaFunctionArn": {
+ "Description": "Lambda function info",
+ "Value": {
+ "Fn::GetAtt": [
+ "LtiLambdaFunction",
+ "Arn"
+ ]
+ }
+ },
+ "ServiceEndpoint": {
+ "Description": "URL of the service endpoint",
+ "Value": {
+ "Fn::Join": [
+ "",
+ [
+ "https://",
+ {
+ "Ref": "ApiGatewayRestApi"
+ },
+ ".execute-api.us-east-1.amazonaws.com/dev"
+ ]
+ ]
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.serverless/lti-lambda.zip b/.serverless/lti-lambda.zip
new file mode 100644
index 0000000..6fedb7b
Binary files /dev/null and b/.serverless/lti-lambda.zip differ
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..59dc654
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,33 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Atomic Jolt, Inc. http://www.atomicjolt.com
+
+The following license applies to all parts of this software except as
+documented below:
+
+====
+
+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.
+
+====
+
+All files located in the node_modules and external directories are
+externally maintained libraries used by this software which have their
+own licenses; we recommend you read them, as their terms may differ from
+the terms above.
diff --git a/README b/README
new file mode 100644
index 0000000..9dc5a88
--- /dev/null
+++ b/README
@@ -0,0 +1,41 @@
+# LTI Lambda
+-----------------------
+This project demonstrates how to do a basic LTI launch using AWS Lambda. This uses the (Serverless framework)[https://serverless.com].
+
+# Getting started
+-----------------------
+You will need an AWS account and credentials to run the function.
+
+## Follow the Serverless getting started documentation
+
+https://serverless.com/framework/docs/providers/aws/guide/intro/
+
+## Deploy
+
+ `serverless deploy`
+
+## LTI Setup
+-----------------------
+Add a new LTI tool to your LMS. Use any value for the lti key. The value for the lti secret is hard coded to 'secret'.
+
+Here's an example XML configuration that can be used to add a course navigation tool to Instructure Canvas. Be sure to replace the
+urls with your own urls:
+
+
+
+ Attendance
+ LTI Lambda
+ https://ngdjwzl0v6.execute-api.us-east-1.amazonaws.com/dev/lti
+ https://ngdjwzl0v6.execute-api.us-east-1.amazonaws.com/dev/images/oauth_icon.png
+
+
+ enabled
+ true
+ LTI Lambda
+ https://ngdjwzl0v6.execute-api.us-east-1.amazonaws.com/dev/lti
+ public
+
+ https://ngdjwzl0v6.execute-api.us-east-1.amazonaws.com
+ public
+
+
diff --git a/event.json b/event.json
new file mode 100644
index 0000000..57fc6cc
--- /dev/null
+++ b/event.json
@@ -0,0 +1,87 @@
+{
+ "body": {
+ "oauth_consumer_key": "atomic-lti-demo",
+ "oauth_signature_method": "HMAC-SHA1",
+ "oauth_timestamp": "1472793890",
+ "oauth_nonce": "zOE0Ch5gn7RkWEeR4zzv0XByoKTOPCPGZ4TTDuGs4",
+ "oauth_version": "1.0",
+ "context_id": "a8a76fb8fbcc2d09787dafd28564e2ecdab51f11",
+ "context_label": "Grade 8 Math",
+ "context_title": "8th Grade Math - Ball",
+ "custom_canvas_api_domain": "atomicjolt.instructure.com",
+ "custom_canvas_course_id": "253",
+ "custom_canvas_enrollment_state": "active",
+ "custom_canvas_user_id": "1",
+ "custom_canvas_user_login_id": "justinball@gmail.com",
+ "ext_roles": "urn:lti:instrole:ims/lis/Administrator,urn:lti:instrole:ims/lis/Instructor,urn:lti:role:ims/lis/Instructor,urn:lti:sysrole:ims/lis/User",
+ "launch_presentation_document_target": "iframe",
+ "launch_presentation_height": "400",
+ "launch_presentation_locale": "en",
+ "launch_presentation_return_url": "https://atomicjolt.instructure.com/courses/253/external_content/success/external_tool_redirect",
+ "launch_presentation_width": "800",
+ "lis_course_offering_sourcedid": "MATH1010032016S",
+ "lis_person_contact_email_primary": "justinball@gmail.com",
+ "lis_person_name_family": "",
+ "lis_person_name_full": "justinball@gmail.com",
+ "lis_person_name_given": "justinball@gmail.com",
+ "lis_person_sourcedid": "1234",
+ "lti_message_type": "basic-lti-launch-request",
+ "lti_version": "LTI-1p0",
+ "oauth_callback": "about:blank",
+ "resource_link_id": "a8a76fb8fbcc2d09787dafd28564e2ecdab51f11",
+ "resource_link_title": "Atomic LTI",
+ "roles": "Instructor,urn:lti:instrole:ims/lis/Administrator",
+ "tool_consumer_info_product_family_code": "canvas",
+ "tool_consumer_info_version": "cloud",
+ "tool_consumer_instance_contact_email": "notifications@instructure.com",
+ "tool_consumer_instance_guid": "4MRcxnx6vQbFXxhLb8005m5WXFM2Z2i8lQwhJ1QT:canvas-lms",
+ "tool_consumer_instance_name": "Atomic Jolt",
+ "user_id": "0340cde37624c04979a6c3fdd0afc2479f8405ad",
+ "user_image": "https://secure.gravatar.com/avatar/bba664c75a2d85d1493a96dadbdedf1b?s=50&d=https%3A%2F%2Fatomicjolt.instructure.com%2Fimages%2Fmessages%2Favatar-50.png",
+ "oauth_signature": "yhW84qeoswxfs1VlbrDxyCRBoeQ="
+ },
+ "method": "POST",
+ "principalId": "",
+ "stage": "dev",
+ "resourcePath": "/lti",
+ "resourceId": "6y0epe",
+ "headers": {
+ "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
+ "accept-encoding": "gzip, deflate, br",
+ "accept-language": "en-US,en;q=0.8",
+ "cache-control": "max-age=0",
+ "cloudfront-forwarded-proto": "https",
+ "cloudfront-is-desktop-viewer": "true",
+ "cloudfront-is-mobile-viewer": "false",
+ "cloudfront-is-smarttv-viewer": "false",
+ "cloudfront-is-tablet-viewer": "false",
+ "cloudfront-viewer-country": "US",
+ "content-type": "application/x-www-form-urlencoded",
+ "host": "8048qxq9dh.execute-api.us-east-1.amazonaws.com",
+ "origin": "https://atomicjolt.instructure.com",
+ "referer": "https://atomicjolt.instructure.com/courses/253/external_tools/948",
+ "upgrade-insecure-requests": "1",
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
+ "via": "1.1 296faebadd40feee8b2eb0e10d5786d2.cloudfront.net (CloudFront)",
+ "x-amz-cf-id": "hn7sEgJnGCLwlK5ckBSTabqM0EtWTLKxqlLrsXbNVxRyIg3vsjRb5A==",
+ "x-forwarded-for": "76.27.110.110, 54.239.203.101",
+ "x-forwarded-port": "443",
+ "x-forwarded-proto": "https"
+ },
+ "query": {},
+ "path": {},
+ "identity": {
+ "cognitoidentitypoolid": "",
+ "accountid": "",
+ "cognitoidentityid": "",
+ "caller": "",
+ "apikey": "",
+ "sourceip": "76.27.110.110",
+ "cognitoauthenticationtype": "",
+ "cognitoauthenticationprovider": "",
+ "userarn": "",
+ "useragent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
+ "user": ""
+ },
+ "stageVariables": {}
+}
\ No newline at end of file
diff --git a/handler.js b/handler.js
new file mode 100644
index 0000000..92749f2
--- /dev/null
+++ b/handler.js
@@ -0,0 +1,30 @@
+"use strict";
+
+import lti from 'ims-lti';
+import querystring from 'querystring';
+
+const lti_shared_secret = "secret";
+
+module.exports.handler = function(event, context, callback) {
+
+ const protocol = event.headers['X-Forwarded-Proto'];
+
+ // Fix up the event to look like a node request for the ims-lti library
+ event.headers.host = event.headers.Host
+ event.url = `${protocol}://${event.headers.Host}/${event.stage}/lti`; // Note that we hard code the path of 'lti' here. This must match the 'path' set in serverless.yml.
+ event.protocol = protocol;
+
+ // Validate the lti launch
+ const provider = new lti.Provider(event.body.oauth_consumer_key, lti_shared_secret);
+
+ provider.valid_request(event, (error, isValid) => {
+
+ const body = isValid ?
+ `
Hello ${event.body.lis_person_name_full}
` :
+ `Error: Failed LTI Launch
${error}
`;
+
+ callback(null, { body: body });
+
+ });
+
+};
\ No newline at end of file
diff --git a/node_modules/.bin/webpack b/node_modules/.bin/webpack
new file mode 120000
index 0000000..d462c1d
--- /dev/null
+++ b/node_modules/.bin/webpack
@@ -0,0 +1 @@
+../webpack/bin/webpack.js
\ No newline at end of file
diff --git a/node_modules/.yarn-integrity b/node_modules/.yarn-integrity
new file mode 100644
index 0000000..87e3e63
--- /dev/null
+++ b/node_modules/.yarn-integrity
@@ -0,0 +1 @@
+65a625794086bc7c03fc335d1643128fd1f237d3d2d128d5b3a0a0ad0a710fd1
\ No newline at end of file
diff --git a/node_modules/Base64/.npmignore b/node_modules/Base64/.npmignore
new file mode 100644
index 0000000..cba87a3
--- /dev/null
+++ b/node_modules/Base64/.npmignore
@@ -0,0 +1,2 @@
+/coverage/
+/node_modules/
diff --git a/node_modules/Base64/.travis.yml b/node_modules/Base64/.travis.yml
new file mode 100644
index 0000000..fbde051
--- /dev/null
+++ b/node_modules/Base64/.travis.yml
@@ -0,0 +1,7 @@
+language: node_js
+node_js:
+ - "0.8"
+ - "0.10"
+ - "0.11"
+install: make setup
+script: make test
diff --git a/node_modules/Base64/LICENSE b/node_modules/Base64/LICENSE
new file mode 100644
index 0000000..4832767
--- /dev/null
+++ b/node_modules/Base64/LICENSE
@@ -0,0 +1,14 @@
+
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+ Version 2, December 2004
+
+ Copyright (c) 2011..2012 David Chambers
+
+ Everyone is permitted to copy and distribute verbatim or modified
+ copies of this license document, and changing it is allowed as long
+ as the name is changed.
+
+ DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. You just DO WHAT THE FUCK YOU WANT TO.
diff --git a/node_modules/Base64/Makefile b/node_modules/Base64/Makefile
new file mode 100644
index 0000000..5c475df
--- /dev/null
+++ b/node_modules/Base64/Makefile
@@ -0,0 +1,42 @@
+ISTANBUL = node_modules/.bin/istanbul
+UGLIFYJS = node_modules/.bin/uglifyjs
+XYZ = node_modules/.bin/xyz --message X.Y.Z --tag X.Y.Z
+
+SRC = base64.js
+MIN = $(patsubst %.js,%.min.js,$(SRC))
+
+
+.PHONY: all
+all: $(MIN)
+
+%.min.js: %.js
+ $(UGLIFYJS) $< --compress --mangle > $@
+
+
+.PHONY: bytes
+bytes: base64.min.js
+ gzip --best --stdout $< | wc -c | tr -d ' '
+
+
+.PHONY: clean
+clean:
+ rm -f -- $(MIN)
+
+
+.PHONY: release-major release-minor release-patch
+release-major:
+ $(XYZ) --increment major
+release-minor:
+ $(XYZ) --increment minor
+release-patch:
+ $(XYZ) --increment patch
+
+
+.PHONY: setup
+setup:
+ npm install
+
+
+.PHONY: test
+test:
+ $(ISTANBUL) cover node_modules/.bin/_mocha -- --compilers coffee:coffee-script/register
diff --git a/node_modules/Base64/README.md b/node_modules/Base64/README.md
new file mode 100644
index 0000000..e5dafed
--- /dev/null
+++ b/node_modules/Base64/README.md
@@ -0,0 +1,34 @@
+# Base64.js
+
+≈ 500 byte* polyfill for browsers which don't provide [`window.btoa`][1] and
+[`window.atob`][2].
+
+Although the script does no harm in browsers which do provide these functions,
+a conditional script loader such as [yepnope][3] can prevent unnecessary HTTP
+requests.
+
+```javascript
+yepnope({
+ test: window.btoa && window.atob,
+ nope: 'base64.js',
+ callback: function () {
+ // `btoa` and `atob` are now safe to use
+ }
+})
+```
+
+Base64.js stems from a [gist][4] by [yahiko][5].
+
+### Running the test suite
+
+ make setup
+ make test
+
+\* Minified and gzipped. Run `make bytes` to verify.
+
+
+[1]: https://developer.mozilla.org/en/DOM/window.btoa
+[2]: https://developer.mozilla.org/en/DOM/window.atob
+[3]: http://yepnopejs.com/
+[4]: https://gist.github.com/229984
+[5]: https://github.com/yahiko
diff --git a/node_modules/Base64/base64.js b/node_modules/Base64/base64.js
new file mode 100644
index 0000000..15d3a8a
--- /dev/null
+++ b/node_modules/Base64/base64.js
@@ -0,0 +1,60 @@
+;(function () {
+
+ var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+
+ function InvalidCharacterError(message) {
+ this.message = message;
+ }
+ InvalidCharacterError.prototype = new Error;
+ InvalidCharacterError.prototype.name = 'InvalidCharacterError';
+
+ // encoder
+ // [https://gist.github.com/999166] by [https://github.com/nignag]
+ object.btoa || (
+ object.btoa = function (input) {
+ for (
+ // initialize result and counter
+ var block, charCode, idx = 0, map = chars, output = '';
+ // if the next input index does not exist:
+ // change the mapping table to "="
+ // check if d has no fractional digits
+ input.charAt(idx | 0) || (map = '=', idx % 1);
+ // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
+ output += map.charAt(63 & block >> 8 - idx % 1 * 8)
+ ) {
+ charCode = input.charCodeAt(idx += 3/4);
+ if (charCode > 0xFF) {
+ throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
+ }
+ block = block << 8 | charCode;
+ }
+ return output;
+ });
+
+ // decoder
+ // [https://gist.github.com/1020396] by [https://github.com/atk]
+ object.atob || (
+ object.atob = function (input) {
+ input = input.replace(/=+$/, '');
+ if (input.length % 4 == 1) {
+ throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
+ }
+ for (
+ // initialize result and counters
+ var bc = 0, bs, buffer, idx = 0, output = '';
+ // get next character
+ buffer = input.charAt(idx++);
+ // character found in table? initialize bit storage and add its ascii value;
+ ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
+ // and if not first of each 4 characters,
+ // convert the first 8 bits to one ascii character
+ bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
+ ) {
+ // try to find character in table (0-63, not found => -1)
+ buffer = chars.indexOf(buffer);
+ }
+ return output;
+ });
+
+}());
diff --git a/node_modules/Base64/base64.min.js b/node_modules/Base64/base64.min.js
new file mode 100644
index 0000000..33c7aa4
--- /dev/null
+++ b/node_modules/Base64/base64.min.js
@@ -0,0 +1 @@
+!function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=new Error,t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-a%1*8)){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),e.length%4==1)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(-2*a&6)):0)n=r.indexOf(n);return c})}();
\ No newline at end of file
diff --git a/node_modules/Base64/package.json b/node_modules/Base64/package.json
new file mode 100644
index 0000000..e453567
--- /dev/null
+++ b/node_modules/Base64/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "Base64",
+ "version": "0.2.1",
+ "description": "Base64 encoding and decoding",
+ "author": "David Chambers ",
+ "main": "./base64.js",
+ "licenses": [
+ {
+ "type": "WTFPL",
+ "url": "https://raw.github.com/davidchambers/Base64.js/master/LICENSE"
+ }
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/davidchambers/Base64.js.git"
+ },
+ "devDependencies": {
+ "coffee-script": "1.7.x",
+ "istanbul": "0.2.x",
+ "mocha": "1.18.x",
+ "uglify-js": "2.4.x",
+ "xyz": "0.1.x"
+ }
+}
diff --git a/node_modules/Base64/test/base64.coffee b/node_modules/Base64/test/base64.coffee
new file mode 100644
index 0000000..e25cf5c
--- /dev/null
+++ b/node_modules/Base64/test/base64.coffee
@@ -0,0 +1,52 @@
+assert = require 'assert'
+
+{btoa, atob} = require '..'
+
+
+describe 'Base64.js', ->
+
+ it 'can encode ASCII input', ->
+ assert.strictEqual btoa(''), ''
+ assert.strictEqual btoa('f'), 'Zg=='
+ assert.strictEqual btoa('fo'), 'Zm8='
+ assert.strictEqual btoa('foo'), 'Zm9v'
+ assert.strictEqual btoa('quux'), 'cXV1eA=='
+ assert.strictEqual btoa('!"#$%'), 'ISIjJCU='
+ assert.strictEqual btoa("&'()*+"), 'JicoKSor'
+ assert.strictEqual btoa(',-./012'), 'LC0uLzAxMg=='
+ assert.strictEqual btoa('3456789:'), 'MzQ1Njc4OTo='
+ assert.strictEqual btoa(';<=>?@ABC'), 'Ozw9Pj9AQUJD'
+ assert.strictEqual btoa('DEFGHIJKLM'), 'REVGR0hJSktMTQ=='
+ assert.strictEqual btoa('NOPQRSTUVWX'), 'Tk9QUVJTVFVWV1g='
+ assert.strictEqual btoa('YZ[\\]^_`abc'), 'WVpbXF1eX2BhYmM='
+ assert.strictEqual btoa('defghijklmnop'), 'ZGVmZ2hpamtsbW5vcA=='
+ assert.strictEqual btoa('qrstuvwxyz{|}~'), 'cXJzdHV2d3h5ent8fX4='
+
+ it 'cannot encode non-ASCII input', ->
+ assert.throws (-> btoa '✈'), (err) ->
+ err instanceof Error and
+ err.name is 'InvalidCharacterError' and
+ err.message is "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."
+
+ it 'can decode Base64-encoded input', ->
+ assert.strictEqual atob(''), ''
+ assert.strictEqual atob('Zg=='), 'f'
+ assert.strictEqual atob('Zm8='), 'fo'
+ assert.strictEqual atob('Zm9v'), 'foo'
+ assert.strictEqual atob('cXV1eA=='), 'quux'
+ assert.strictEqual atob('ISIjJCU='), '!"#$%'
+ assert.strictEqual atob('JicoKSor'), "&'()*+"
+ assert.strictEqual atob('LC0uLzAxMg=='), ',-./012'
+ assert.strictEqual atob('MzQ1Njc4OTo='), '3456789:'
+ assert.strictEqual atob('Ozw9Pj9AQUJD'), ';<=>?@ABC'
+ assert.strictEqual atob('REVGR0hJSktMTQ=='), 'DEFGHIJKLM'
+ assert.strictEqual atob('Tk9QUVJTVFVWV1g='), 'NOPQRSTUVWX'
+ assert.strictEqual atob('WVpbXF1eX2BhYmM='), 'YZ[\\]^_`abc'
+ assert.strictEqual atob('ZGVmZ2hpamtsbW5vcA=='), 'defghijklmnop'
+ assert.strictEqual atob('cXJzdHV2d3h5ent8fX4='), 'qrstuvwxyz{|}~'
+
+ it 'cannot decode invalid input', ->
+ assert.throws (-> atob 'a'), (err) ->
+ err instanceof Error and
+ err.name is 'InvalidCharacterError' and
+ err.message is "'atob' failed: The string to be decoded is not correctly encoded."
diff --git a/node_modules/abbrev/LICENSE b/node_modules/abbrev/LICENSE
new file mode 100644
index 0000000..19129e3
--- /dev/null
+++ b/node_modules/abbrev/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+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/abbrev/README.md b/node_modules/abbrev/README.md
new file mode 100644
index 0000000..99746fe
--- /dev/null
+++ b/node_modules/abbrev/README.md
@@ -0,0 +1,23 @@
+# abbrev-js
+
+Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).
+
+Usage:
+
+ var abbrev = require("abbrev");
+ abbrev("foo", "fool", "folding", "flop");
+
+ // returns:
+ { fl: 'flop'
+ , flo: 'flop'
+ , flop: 'flop'
+ , fol: 'folding'
+ , fold: 'folding'
+ , foldi: 'folding'
+ , foldin: 'folding'
+ , folding: 'folding'
+ , foo: 'foo'
+ , fool: 'fool'
+ }
+
+This is handy for command-line scripts, or other cases where you want to be able to accept shorthands.
diff --git a/node_modules/abbrev/abbrev.js b/node_modules/abbrev/abbrev.js
new file mode 100644
index 0000000..69cfeac
--- /dev/null
+++ b/node_modules/abbrev/abbrev.js
@@ -0,0 +1,62 @@
+
+module.exports = exports = abbrev.abbrev = abbrev
+
+abbrev.monkeyPatch = monkeyPatch
+
+function monkeyPatch () {
+ Object.defineProperty(Array.prototype, 'abbrev', {
+ value: function () { return abbrev(this) },
+ enumerable: false, configurable: true, writable: true
+ })
+
+ Object.defineProperty(Object.prototype, 'abbrev', {
+ value: function () { return abbrev(Object.keys(this)) },
+ enumerable: false, configurable: true, writable: true
+ })
+}
+
+function abbrev (list) {
+ if (arguments.length !== 1 || !Array.isArray(list)) {
+ list = Array.prototype.slice.call(arguments, 0)
+ }
+ for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {
+ args[i] = typeof list[i] === "string" ? list[i] : String(list[i])
+ }
+
+ // sort them lexicographically, so that they're next to their nearest kin
+ args = args.sort(lexSort)
+
+ // walk through each, seeing how much it has in common with the next and previous
+ var abbrevs = {}
+ , prev = ""
+ for (var i = 0, l = args.length ; i < l ; i ++) {
+ var current = args[i]
+ , next = args[i + 1] || ""
+ , nextMatches = true
+ , prevMatches = true
+ if (current === next) continue
+ for (var j = 0, cl = current.length ; j < cl ; j ++) {
+ var curChar = current.charAt(j)
+ nextMatches = nextMatches && curChar === next.charAt(j)
+ prevMatches = prevMatches && curChar === prev.charAt(j)
+ if (!nextMatches && !prevMatches) {
+ j ++
+ break
+ }
+ }
+ prev = current
+ if (j === cl) {
+ abbrevs[current] = current
+ continue
+ }
+ for (var a = current.substr(0, j) ; j <= cl ; j ++) {
+ abbrevs[a] = current
+ a += current.charAt(j)
+ }
+ }
+ return abbrevs
+}
+
+function lexSort (a, b) {
+ return a === b ? 0 : a > b ? 1 : -1
+}
diff --git a/node_modules/abbrev/package.json b/node_modules/abbrev/package.json
new file mode 100644
index 0000000..d794c03
--- /dev/null
+++ b/node_modules/abbrev/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "abbrev",
+ "version": "1.0.9",
+ "description": "Like ruby's abbrev module, but in js",
+ "author": "Isaac Z. Schlueter ",
+ "main": "abbrev.js",
+ "scripts": {
+ "test": "tap test.js --cov"
+ },
+ "repository": "http://github.com/isaacs/abbrev-js",
+ "license": "ISC",
+ "devDependencies": {
+ "tap": "^5.7.2"
+ },
+ "files": [
+ "abbrev.js"
+ ]
+}
diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md
new file mode 100644
index 0000000..0477ed7
--- /dev/null
+++ b/node_modules/accepts/HISTORY.md
@@ -0,0 +1,212 @@
+1.3.3 / 2016-05-02
+==================
+
+ * deps: mime-types@~2.1.11
+ - deps: mime-db@~1.23.0
+ * deps: negotiator@0.6.1
+ - perf: improve `Accept` parsing speed
+ - perf: improve `Accept-Charset` parsing speed
+ - perf: improve `Accept-Encoding` parsing speed
+ - perf: improve `Accept-Language` parsing speed
+
+1.3.2 / 2016-03-08
+==================
+
+ * deps: mime-types@~2.1.10
+ - Fix extension of `application/dash+xml`
+ - Update primary extension for `audio/mp4`
+ - deps: mime-db@~1.22.0
+
+1.3.1 / 2016-01-19
+==================
+
+ * deps: mime-types@~2.1.9
+ - deps: mime-db@~1.21.0
+
+1.3.0 / 2015-09-29
+==================
+
+ * deps: mime-types@~2.1.7
+ - deps: mime-db@~1.19.0
+ * deps: negotiator@0.6.0
+ - Fix including type extensions in parameters in `Accept` parsing
+ - Fix parsing `Accept` parameters with quoted equals
+ - Fix parsing `Accept` parameters with quoted semicolons
+ - Lazy-load modules from main entry point
+ - perf: delay type concatenation until needed
+ - perf: enable strict mode
+ - perf: hoist regular expressions
+ - perf: remove closures getting spec properties
+ - perf: remove a closure from media type parsing
+ - perf: remove property delete from media type parsing
+
+1.2.13 / 2015-09-06
+===================
+
+ * deps: mime-types@~2.1.6
+ - deps: mime-db@~1.18.0
+
+1.2.12 / 2015-07-30
+===================
+
+ * deps: mime-types@~2.1.4
+ - deps: mime-db@~1.16.0
+
+1.2.11 / 2015-07-16
+===================
+
+ * deps: mime-types@~2.1.3
+ - deps: mime-db@~1.15.0
+
+1.2.10 / 2015-07-01
+===================
+
+ * deps: mime-types@~2.1.2
+ - deps: mime-db@~1.14.0
+
+1.2.9 / 2015-06-08
+==================
+
+ * deps: mime-types@~2.1.1
+ - perf: fix deopt during mapping
+
+1.2.8 / 2015-06-07
+==================
+
+ * deps: mime-types@~2.1.0
+ - deps: mime-db@~1.13.0
+ * perf: avoid argument reassignment & argument slice
+ * perf: avoid negotiator recursive construction
+ * perf: enable strict mode
+ * perf: remove unnecessary bitwise operator
+
+1.2.7 / 2015-05-10
+==================
+
+ * deps: negotiator@0.5.3
+ - Fix media type parameter matching to be case-insensitive
+
+1.2.6 / 2015-05-07
+==================
+
+ * deps: mime-types@~2.0.11
+ - deps: mime-db@~1.9.1
+ * deps: negotiator@0.5.2
+ - Fix comparing media types with quoted values
+ - Fix splitting media types with quoted commas
+
+1.2.5 / 2015-03-13
+==================
+
+ * deps: mime-types@~2.0.10
+ - deps: mime-db@~1.8.0
+
+1.2.4 / 2015-02-14
+==================
+
+ * Support Node.js 0.6
+ * deps: mime-types@~2.0.9
+ - deps: mime-db@~1.7.0
+ * deps: negotiator@0.5.1
+ - Fix preference sorting to be stable for long acceptable lists
+
+1.2.3 / 2015-01-31
+==================
+
+ * deps: mime-types@~2.0.8
+ - deps: mime-db@~1.6.0
+
+1.2.2 / 2014-12-30
+==================
+
+ * deps: mime-types@~2.0.7
+ - deps: mime-db@~1.5.0
+
+1.2.1 / 2014-12-30
+==================
+
+ * deps: mime-types@~2.0.5
+ - deps: mime-db@~1.3.1
+
+1.2.0 / 2014-12-19
+==================
+
+ * deps: negotiator@0.5.0
+ - Fix list return order when large accepted list
+ - Fix missing identity encoding when q=0 exists
+ - Remove dynamic building of Negotiator class
+
+1.1.4 / 2014-12-10
+==================
+
+ * deps: mime-types@~2.0.4
+ - deps: mime-db@~1.3.0
+
+1.1.3 / 2014-11-09
+==================
+
+ * deps: mime-types@~2.0.3
+ - deps: mime-db@~1.2.0
+
+1.1.2 / 2014-10-14
+==================
+
+ * deps: negotiator@0.4.9
+ - Fix error when media type has invalid parameter
+
+1.1.1 / 2014-09-28
+==================
+
+ * deps: mime-types@~2.0.2
+ - deps: mime-db@~1.1.0
+ * deps: negotiator@0.4.8
+ - Fix all negotiations to be case-insensitive
+ - Stable sort preferences of same quality according to client order
+
+1.1.0 / 2014-09-02
+==================
+
+ * update `mime-types`
+
+1.0.7 / 2014-07-04
+==================
+
+ * Fix wrong type returned from `type` when match after unknown extension
+
+1.0.6 / 2014-06-24
+==================
+
+ * deps: negotiator@0.4.7
+
+1.0.5 / 2014-06-20
+==================
+
+ * fix crash when unknown extension given
+
+1.0.4 / 2014-06-19
+==================
+
+ * use `mime-types`
+
+1.0.3 / 2014-06-11
+==================
+
+ * deps: negotiator@0.4.6
+ - Order by specificity when quality is the same
+
+1.0.2 / 2014-05-29
+==================
+
+ * Fix interpretation when header not in request
+ * deps: pin negotiator@0.4.5
+
+1.0.1 / 2014-01-18
+==================
+
+ * Identity encoding isn't always acceptable
+ * deps: negotiator@~0.4.0
+
+1.0.0 / 2013-12-27
+==================
+
+ * Genesis
diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE
new file mode 100644
index 0000000..0616607
--- /dev/null
+++ b/node_modules/accepts/LICENSE
@@ -0,0 +1,23 @@
+(The MIT License)
+
+Copyright (c) 2014 Jonathan Ong
+Copyright (c) 2015 Douglas Christopher Wilson
+
+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/accepts/README.md b/node_modules/accepts/README.md
new file mode 100644
index 0000000..ae36676
--- /dev/null
+++ b/node_modules/accepts/README.md
@@ -0,0 +1,135 @@
+# accepts
+
+[![NPM Version][npm-image]][npm-url]
+[![NPM Downloads][downloads-image]][downloads-url]
+[![Node.js Version][node-version-image]][node-version-url]
+[![Build Status][travis-image]][travis-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+
+Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
+
+In addition to negotiator, it allows:
+
+- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.
+- Allows type shorthands such as `json`.
+- Returns `false` when no types match
+- Treats non-existent headers as `*`
+
+## Installation
+
+```sh
+npm install accepts
+```
+
+## API
+
+```js
+var accepts = require('accepts')
+```
+
+### accepts(req)
+
+Create a new `Accepts` object for the given `req`.
+
+#### .charset(charsets)
+
+Return the first accepted charset. If nothing in `charsets` is accepted,
+then `false` is returned.
+
+#### .charsets()
+
+Return the charsets that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .encoding(encodings)
+
+Return the first accepted encoding. If nothing in `encodings` is accepted,
+then `false` is returned.
+
+#### .encodings()
+
+Return the encodings that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .language(languages)
+
+Return the first accepted language. If nothing in `languages` is accepted,
+then `false` is returned.
+
+#### .languages()
+
+Return the languages that the request accepts, in the order of the client's
+preference (most preferred first).
+
+#### .type(types)
+
+Return the first accepted type (and it is returned as the same text as what
+appears in the `types` array). If nothing in `types` is accepted, then `false`
+is returned.
+
+The `types` array can contain full MIME types or file extensions. Any value
+that is not a full MIME types is passed to `require('mime-types').lookup`.
+
+#### .types()
+
+Return the types that the request accepts, in the order of the client's
+preference (most preferred first).
+
+## Examples
+
+### Simple type negotiation
+
+This simple example shows how to use `accepts` to return a different typed
+respond body based on what the client wants to accept. The server lists it's
+preferences in order and will get back the best match between the client and
+server.
+
+```js
+var accepts = require('accepts')
+var http = require('http')
+
+function app(req, res) {
+ var accept = accepts(req)
+
+ // the order of this list is significant; should be server preferred order
+ switch(accept.type(['json', 'html'])) {
+ case 'json':
+ res.setHeader('Content-Type', 'application/json')
+ res.write('{"hello":"world!"}')
+ break
+ case 'html':
+ res.setHeader('Content-Type', 'text/html')
+ res.write('hello, world!')
+ break
+ default:
+ // the fallback is text/plain, so no need to specify it above
+ res.setHeader('Content-Type', 'text/plain')
+ res.write('hello, world!')
+ break
+ }
+
+ res.end()
+}
+
+http.createServer(app).listen(3000)
+```
+
+You can test this out with the cURL program:
+```sh
+curl -I -H'Accept: text/html' http://localhost:3000/
+```
+
+## License
+
+[MIT](LICENSE)
+
+[npm-image]: https://img.shields.io/npm/v/accepts.svg
+[npm-url]: https://npmjs.org/package/accepts
+[node-version-image]: https://img.shields.io/node/v/accepts.svg
+[node-version-url]: http://nodejs.org/download/
+[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg
+[travis-url]: https://travis-ci.org/jshttp/accepts
+[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg
+[coveralls-url]: https://coveralls.io/r/jshttp/accepts
+[downloads-image]: https://img.shields.io/npm/dm/accepts.svg
+[downloads-url]: https://npmjs.org/package/accepts
diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js
new file mode 100644
index 0000000..e80192a
--- /dev/null
+++ b/node_modules/accepts/index.js
@@ -0,0 +1,231 @@
+/*!
+ * accepts
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var Negotiator = require('negotiator')
+var mime = require('mime-types')
+
+/**
+ * Module exports.
+ * @public
+ */
+
+module.exports = Accepts
+
+/**
+ * Create a new Accepts object for the given req.
+ *
+ * @param {object} req
+ * @public
+ */
+
+function Accepts(req) {
+ if (!(this instanceof Accepts))
+ return new Accepts(req)
+
+ this.headers = req.headers
+ this.negotiator = new Negotiator(req)
+}
+
+/**
+ * Check if the given `type(s)` is acceptable, returning
+ * the best match when true, otherwise `undefined`, in which
+ * case you should respond with 406 "Not Acceptable".
+ *
+ * The `type` value may be a single mime type string
+ * such as "application/json", the extension name
+ * such as "json" or an array `["json", "html", "text/plain"]`. When a list
+ * or array is given the _best_ match, if any is returned.
+ *
+ * Examples:
+ *
+ * // Accept: text/html
+ * this.types('html');
+ * // => "html"
+ *
+ * // Accept: text/*, application/json
+ * this.types('html');
+ * // => "html"
+ * this.types('text/html');
+ * // => "text/html"
+ * this.types('json', 'text');
+ * // => "json"
+ * this.types('application/json');
+ * // => "application/json"
+ *
+ * // Accept: text/*, application/json
+ * this.types('image/png');
+ * this.types('png');
+ * // => undefined
+ *
+ * // Accept: text/*;q=.5, application/json
+ * this.types(['html', 'json']);
+ * this.types('html', 'json');
+ * // => "json"
+ *
+ * @param {String|Array} types...
+ * @return {String|Array|Boolean}
+ * @public
+ */
+
+Accepts.prototype.type =
+Accepts.prototype.types = function (types_) {
+ var types = types_
+
+ // support flattened arguments
+ if (types && !Array.isArray(types)) {
+ types = new Array(arguments.length)
+ for (var i = 0; i < types.length; i++) {
+ types[i] = arguments[i]
+ }
+ }
+
+ // no types, return all requested types
+ if (!types || types.length === 0) {
+ return this.negotiator.mediaTypes()
+ }
+
+ if (!this.headers.accept) return types[0];
+ var mimes = types.map(extToMime);
+ var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
+ var first = accepts[0];
+ if (!first) return false;
+ return types[mimes.indexOf(first)];
+}
+
+/**
+ * Return accepted encodings or best fit based on `encodings`.
+ *
+ * Given `Accept-Encoding: gzip, deflate`
+ * an array sorted by quality is returned:
+ *
+ * ['gzip', 'deflate']
+ *
+ * @param {String|Array} encodings...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.encoding =
+Accepts.prototype.encodings = function (encodings_) {
+ var encodings = encodings_
+
+ // support flattened arguments
+ if (encodings && !Array.isArray(encodings)) {
+ encodings = new Array(arguments.length)
+ for (var i = 0; i < encodings.length; i++) {
+ encodings[i] = arguments[i]
+ }
+ }
+
+ // no encodings, return all requested encodings
+ if (!encodings || encodings.length === 0) {
+ return this.negotiator.encodings()
+ }
+
+ return this.negotiator.encodings(encodings)[0] || false
+}
+
+/**
+ * Return accepted charsets or best fit based on `charsets`.
+ *
+ * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
+ * an array sorted by quality is returned:
+ *
+ * ['utf-8', 'utf-7', 'iso-8859-1']
+ *
+ * @param {String|Array} charsets...
+ * @return {String|Array}
+ * @public
+ */
+
+Accepts.prototype.charset =
+Accepts.prototype.charsets = function (charsets_) {
+ var charsets = charsets_
+
+ // support flattened arguments
+ if (charsets && !Array.isArray(charsets)) {
+ charsets = new Array(arguments.length)
+ for (var i = 0; i < charsets.length; i++) {
+ charsets[i] = arguments[i]
+ }
+ }
+
+ // no charsets, return all requested charsets
+ if (!charsets || charsets.length === 0) {
+ return this.negotiator.charsets()
+ }
+
+ return this.negotiator.charsets(charsets)[0] || false
+}
+
+/**
+ * Return accepted languages or best fit based on `langs`.
+ *
+ * Given `Accept-Language: en;q=0.8, es, pt`
+ * an array sorted by quality is returned:
+ *
+ * ['es', 'pt', 'en']
+ *
+ * @param {String|Array} langs...
+ * @return {Array|String}
+ * @public
+ */
+
+Accepts.prototype.lang =
+Accepts.prototype.langs =
+Accepts.prototype.language =
+Accepts.prototype.languages = function (languages_) {
+ var languages = languages_
+
+ // support flattened arguments
+ if (languages && !Array.isArray(languages)) {
+ languages = new Array(arguments.length)
+ for (var i = 0; i < languages.length; i++) {
+ languages[i] = arguments[i]
+ }
+ }
+
+ // no languages, return all requested languages
+ if (!languages || languages.length === 0) {
+ return this.negotiator.languages()
+ }
+
+ return this.negotiator.languages(languages)[0] || false
+}
+
+/**
+ * Convert extnames to mime.
+ *
+ * @param {String} type
+ * @return {String}
+ * @private
+ */
+
+function extToMime(type) {
+ return type.indexOf('/') === -1
+ ? mime.lookup(type)
+ : type
+}
+
+/**
+ * Check if mime is valid.
+ *
+ * @param {String} type
+ * @return {String}
+ * @private
+ */
+
+function validMime(type) {
+ return typeof type === 'string';
+}
diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json
new file mode 100644
index 0000000..ed422bd
--- /dev/null
+++ b/node_modules/accepts/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "accepts",
+ "description": "Higher-level content negotiation",
+ "version": "1.3.3",
+ "contributors": [
+ "Douglas Christopher Wilson ",
+ "Jonathan Ong (http://jongleberry.com)"
+ ],
+ "license": "MIT",
+ "repository": "jshttp/accepts",
+ "dependencies": {
+ "mime-types": "~2.1.11",
+ "negotiator": "0.6.1"
+ },
+ "devDependencies": {
+ "istanbul": "0.4.3",
+ "mocha": "~1.21.5"
+ },
+ "files": [
+ "LICENSE",
+ "HISTORY.md",
+ "index.js"
+ ],
+ "engines": {
+ "node": ">= 0.6"
+ },
+ "scripts": {
+ "test": "mocha --reporter spec --check-leaks --bail test/",
+ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
+ "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
+ },
+ "keywords": [
+ "content",
+ "negotiation",
+ "accept",
+ "accepts"
+ ]
+}
diff --git a/node_modules/acorn/.editorconfig b/node_modules/acorn/.editorconfig
new file mode 100644
index 0000000..c14d5c6
--- /dev/null
+++ b/node_modules/acorn/.editorconfig
@@ -0,0 +1,7 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+end_of_line = lf
+insert_final_newline = true
diff --git a/node_modules/acorn/.gitattributes b/node_modules/acorn/.gitattributes
new file mode 100644
index 0000000..fcadb2c
--- /dev/null
+++ b/node_modules/acorn/.gitattributes
@@ -0,0 +1 @@
+* text eol=lf
diff --git a/node_modules/acorn/.npmignore b/node_modules/acorn/.npmignore
new file mode 100644
index 0000000..ecba291
--- /dev/null
+++ b/node_modules/acorn/.npmignore
@@ -0,0 +1,3 @@
+/.tern-port
+/test
+/local
diff --git a/node_modules/acorn/.tern-project b/node_modules/acorn/.tern-project
new file mode 100644
index 0000000..6718ce0
--- /dev/null
+++ b/node_modules/acorn/.tern-project
@@ -0,0 +1,6 @@
+{
+ "plugins": {
+ "node": true,
+ "es_modules": true
+ }
+}
\ No newline at end of file
diff --git a/node_modules/acorn/.travis.yml b/node_modules/acorn/.travis.yml
new file mode 100644
index 0000000..d9ee88b
--- /dev/null
+++ b/node_modules/acorn/.travis.yml
@@ -0,0 +1,7 @@
+language: node_js
+sudo: false
+node_js:
+ - '0.12'
+ - '4'
+ - '5'
+ - '6'
diff --git a/node_modules/acorn/AUTHORS b/node_modules/acorn/AUTHORS
new file mode 100644
index 0000000..1b2061c
--- /dev/null
+++ b/node_modules/acorn/AUTHORS
@@ -0,0 +1,59 @@
+List of Acorn contributors. Updated before every release.
+
+Adrian Rakovsky
+Alistair Braidwood
+Amila Welihinda
+Andres Suarez
+Angelo
+Aparajita Fishman
+Arian Stolwijk
+Artem Govorov
+Brandon Mills
+Charles Hughes
+Conrad Irwin
+Daniel Tschinder
+David Bonnet
+Domenico Matteo
+ForbesLindesay
+Forbes Lindesay
+Gilad Peleg
+impinball
+Ingvar Stepanyan
+Jackson Ray Hamilton
+Jesse McCarthy
+Jiaxing Wang
+Joel Kemp
+Johannes Herr
+Jordan Klassen
+Jürg Lehni
+keeyipchan
+Keheliya Gallaba
+Kevin Irish
+Kevin Kwok
+krator
+Marijn Haverbeke
+Martin Carlberg
+Mathias Bynens
+Mathieu 'p01' Henri
+Matthew Bastien
+Max Schaefer
+Max Zerzouri
+Mihai Bazon
+Mike Rennie
+Nicholas C. Zakas
+Nick Fitzgerald
+Olivier Thomann
+Oskar Schöldström
+Paul Harper
+Peter Rust
+PlNG
+Prayag Verma
+ReadmeCritic
+r-e-d
+Richard Gibson
+Rich Harris
+Rich-Harris
+Sebastian McKenzie
+Timothy Gu
+Toru Nagashima
+zsjforcn
diff --git a/node_modules/acorn/CHANGELOG.md b/node_modules/acorn/CHANGELOG.md
new file mode 100644
index 0000000..16b8212
--- /dev/null
+++ b/node_modules/acorn/CHANGELOG.md
@@ -0,0 +1,159 @@
+## 3.3.0 (2016-07-25)
+
+### Bug fixes
+
+Fix bug in tokenizing of regexp operator after a function declaration.
+
+Fix parser crash when parsing an array pattern with a hole.
+
+### New features
+
+Implement check against complex argument lists in functions that
+enable strict mode in ES7.
+
+## 3.2.0 (2016-06-07)
+
+### Bug fixes
+
+Improve handling of lack of unicode regexp support in host
+environment.
+
+Properly reject shorthand properties whose name is a keyword.
+
+Don't crash when the loose parser is called without options object.
+
+### New features
+
+Visitors created with `visit.make` now have their base as _prototype_,
+rather than copying properties into a fresh object.
+
+Make it possible to use `visit.ancestor` with a walk state.
+
+## 3.1.0 (2016-04-18)
+
+### Bug fixes
+
+Fix issue where the loose parser created invalid TemplateElement nodes
+for unclosed template literals.
+
+Properly tokenize the division operator directly after a function
+expression.
+
+Allow trailing comma in destructuring arrays.
+
+### New features
+
+The walker now allows defining handlers for `CatchClause` nodes.
+
+## 3.0.4 (2016-02-25)
+
+### Fixes
+
+Allow update expressions as left-hand-side of the ES7 exponential
+operator.
+
+## 3.0.2 (2016-02-10)
+
+### Fixes
+
+Fix bug that accidentally made `undefined` a reserved word when
+parsing ES7.
+
+## 3.0.0 (2016-02-10)
+
+### Breaking changes
+
+The default value of the `ecmaVersion` option is now 6 (used to be 5).
+
+Support for comprehension syntax (which was dropped from the draft
+spec) has been removed.
+
+### Fixes
+
+`let` and `yield` are now “contextual keywords”, meaning you can
+mostly use them as identifiers in ES5 non-strict code.
+
+A parenthesized class or function expression after `export default` is
+now parsed correctly.
+
+### New features
+
+When `ecmaVersion` is set to 7, Acorn will parse the exponentiation
+operator (`**`).
+
+The identifier character ranges are now based on Unicode 8.0.0.
+
+Plugins can now override the `raiseRecoverable` method to override the
+way non-critical errors are handled.
+
+## 2.7.0 (2016-01-04)
+
+### Fixes
+
+Stop allowing rest parameters in setters.
+
+Make sure the loose parser always attaches a `local` property to
+`ImportNamespaceSpecifier` nodes.
+
+Disallow `y` rexexp flag in ES5.
+
+Disallow `\00` and `\000` escapes in strict mode.
+
+Raise an error when an import name is a reserved word.
+
+## 2.6.4 (2015-11-12)
+
+### Fixes
+
+Fix crash in loose parser when parsing invalid object pattern.
+
+### New features
+
+Support plugins in the loose parser.
+
+## 2.6.2 (2015-11-10)
+
+### Fixes
+
+Don't crash when no options object is passed.
+
+## 2.6.0 (2015-11-09)
+
+### Fixes
+
+Add `await` as a reserved word in module sources.
+
+Disallow `yield` in a parameter default value for a generator.
+
+Forbid using a comma after a rest pattern in an array destructuring.
+
+### New features
+
+Support parsing stdin in command-line tool.
+
+## 2.5.2 (2015-10-27)
+
+### Fixes
+
+Fix bug where the walker walked an exported `let` statement as an
+expression.
+
+## 2.5.0 (2015-10-27)
+
+### Fixes
+
+Fix tokenizer support in the command-line tool.
+
+In the loose parser, don't allow non-string-literals as import
+sources.
+
+Stop allowing `new.target` outside of functions.
+
+Remove legacy `guard` and `guardedHandler` properties from try nodes.
+
+Stop allowing multiple `__proto__` properties on an object literal in
+strict mode.
+
+Don't allow rest parameters to be non-identifier patterns.
+
+Check for duplicate paramter names in arrow functions.
diff --git a/node_modules/acorn/LICENSE b/node_modules/acorn/LICENSE
new file mode 100644
index 0000000..a35ebf4
--- /dev/null
+++ b/node_modules/acorn/LICENSE
@@ -0,0 +1,19 @@
+Copyright (C) 2012-2016 by various contributors (see AUTHORS)
+
+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/acorn/README.md b/node_modules/acorn/README.md
new file mode 100644
index 0000000..0c514d5
--- /dev/null
+++ b/node_modules/acorn/README.md
@@ -0,0 +1,407 @@
+# Acorn
+
+[![Build Status](https://travis-ci.org/ternjs/acorn.svg?branch=master)](https://travis-ci.org/ternjs/acorn)
+[![NPM version](https://img.shields.io/npm/v/acorn.svg)](https://www.npmjs.com/package/acorn)
+[Author funding status: ![maintainer happiness](https://marijnhaverbeke.nl/fund/status_s.png?force)](https://marijnhaverbeke.nl/fund/)
+
+A tiny, fast JavaScript parser, written completely in JavaScript.
+
+## Community
+
+Acorn is open source software released under an
+[MIT license](https://github.com/ternjs/acorn/blob/master/LICENSE).
+
+You are welcome to
+[report bugs](https://github.com/ternjs/acorn/issues) or create pull
+requests on [github](https://github.com/ternjs/acorn). For questions
+and discussion, please use the
+[Tern discussion forum](https://discuss.ternjs.net).
+
+## Installation
+
+The easiest way to install acorn is with [`npm`][npm].
+
+[npm]: https://www.npmjs.com/
+
+```sh
+npm install acorn
+```
+
+Alternately, download the source.
+
+```sh
+git clone https://github.com/ternjs/acorn.git
+```
+
+## Components
+
+When run in a CommonJS (node.js) or AMD environment, exported values
+appear in the interfaces exposed by the individual files, as usual.
+When loaded in the browser (Acorn works in any JS-enabled browser more
+recent than IE5) without any kind of module management, a single
+global object `acorn` will be defined, and all the exported properties
+will be added to that.
+
+### Main parser
+
+This is implemented in `dist/acorn.js`, and is what you get when you
+`require("acorn")` in node.js.
+
+**parse**`(input, options)` is used to parse a JavaScript program.
+The `input` parameter is a string, `options` can be undefined or an
+object setting some of the options listed below. The return value will
+be an abstract syntax tree object as specified by the
+[ESTree spec][estree].
+
+When encountering a syntax error, the parser will raise a
+`SyntaxError` object with a meaningful message. The error object will
+have a `pos` property that indicates the character offset at which the
+error occurred, and a `loc` object that contains a `{line, column}`
+object referring to that same position.
+
+[estree]: https://github.com/estree/estree
+
+- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be
+ either 3, 5, 6, or 7. This influences support for strict mode, the set
+ of reserved words, and support for new syntax features. Default is 6.
+
+ **NOTE**: Only 'stage 4' (finalized) ECMAScript 7 features are being
+ implemented by Acorn. That means that most of the draft standard is
+ not yet being parsed.
+
+- **sourceType**: Indicate the mode the code should be parsed in. Can be
+ either `"script"` or `"module"`.
+
+- **onInsertedSemicolon**: If given a callback, that callback will be
+ called whenever a missing semicolon is inserted by the parser. The
+ callback will be given the character offset of the point where the
+ semicolon is inserted as argument, and if `locations` is on, also a
+ `{line, column}` object representing this position.
+
+- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing
+ commas.
+
+- **allowReserved**: If `false`, using a reserved word will generate
+ an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher
+ versions. When given the value `"never"`, reserved words and
+ keywords can also not be used as property names (as in Internet
+ Explorer's old parser).
+
+- **allowReturnOutsideFunction**: By default, a return statement at
+ the top level raises an error. Set this to `true` to accept such
+ code.
+
+- **allowImportExportEverywhere**: By default, `import` and `export`
+ declarations can only appear at a program's top level. Setting this
+ option to `true` allows them anywhere where a statement is allowed.
+
+- **allowHashBang**: When this is enabled (off by default), if the
+ code starts with the characters `#!` (as in a shellscript), the
+ first line will be treated as a comment.
+
+- **locations**: When `true`, each node has a `loc` object attached
+ with `start` and `end` subobjects, each of which contains the
+ one-based line and zero-based column numbers in `{line, column}`
+ form. Default is `false`.
+
+- **onToken**: If a function is passed for this option, each found
+ token will be passed in same format as tokens returned from
+ `tokenizer().getToken()`.
+
+ If array is passed, each found token is pushed to it.
+
+ Note that you are not allowed to call the parser from the
+ callback—that will corrupt its internal state.
+
+- **onComment**: If a function is passed for this option, whenever a
+ comment is encountered the function will be called with the
+ following parameters:
+
+ - `block`: `true` if the comment is a block comment, false if it
+ is a line comment.
+ - `text`: The content of the comment.
+ - `start`: Character offset of the start of the comment.
+ - `end`: Character offset of the end of the comment.
+
+ When the `locations` options is on, the `{line, column}` locations
+ of the comment’s start and end are passed as two additional
+ parameters.
+
+ If array is passed for this option, each found comment is pushed
+ to it as object in Esprima format:
+
+ ```javascript
+ {
+ "type": "Line" | "Block",
+ "value": "comment text",
+ "start": Number,
+ "end": Number,
+ // If `locations` option is on:
+ "loc": {
+ "start": {line: Number, column: Number}
+ "end": {line: Number, column: Number}
+ },
+ // If `ranges` option is on:
+ "range": [Number, Number]
+ }
+ ```
+
+ Note that you are not allowed to call the parser from the
+ callback—that will corrupt its internal state.
+
+- **ranges**: Nodes have their start and end characters offsets
+ recorded in `start` and `end` properties (directly on the node,
+ rather than the `loc` object, which holds line/column data. To also
+ add a [semi-standardized][range] `range` property holding a
+ `[start, end]` array with the same numbers, set the `ranges` option
+ to `true`.
+
+- **program**: It is possible to parse multiple files into a single
+ AST by passing the tree produced by parsing the first file as the
+ `program` option in subsequent parses. This will add the toplevel
+ forms of the parsed file to the "Program" (top) node of an existing
+ parse tree.
+
+- **sourceFile**: When the `locations` option is `true`, you can pass
+ this option to add a `source` attribute in every node’s `loc`
+ object. Note that the contents of this option are not examined or
+ processed in any way; you are free to use whatever format you
+ choose.
+
+- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property
+ will be added (regardless of the `location` option) directly to the
+ nodes, rather than the `loc` object.
+
+- **preserveParens**: If this option is `true`, parenthesized expressions
+ are represented by (non-standard) `ParenthesizedExpression` nodes
+ that have a single `expression` property containing the expression
+ inside parentheses.
+
+[range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
+
+**parseExpressionAt**`(input, offset, options)` will parse a single
+expression in a string, and return its AST. It will not complain if
+there is more of the string left after the expression.
+
+**getLineInfo**`(input, offset)` can be used to get a `{line,
+column}` object for a given program string and character offset.
+
+**tokenizer**`(input, options)` returns an object with a `getToken`
+method that can be called repeatedly to get the next token, a `{start,
+end, type, value}` object (with added `loc` property when the
+`locations` option is enabled and `range` property when the `ranges`
+option is enabled). When the token's type is `tokTypes.eof`, you
+should stop calling the method, since it will keep returning that same
+token forever.
+
+In ES6 environment, returned result can be used as any other
+protocol-compliant iterable:
+
+```javascript
+for (let token of acorn.tokenizer(str)) {
+ // iterate over the tokens
+}
+
+// transform code to array of tokens:
+var tokens = [...acorn.tokenizer(str)];
+```
+
+**tokTypes** holds an object mapping names to the token type objects
+that end up in the `type` properties of tokens.
+
+#### Note on using with [Escodegen][escodegen]
+
+Escodegen supports generating comments from AST, attached in
+Esprima-specific format. In order to simulate same format in
+Acorn, consider following example:
+
+```javascript
+var comments = [], tokens = [];
+
+var ast = acorn.parse('var x = 42; // answer', {
+ // collect ranges for each node
+ ranges: true,
+ // collect comments in Esprima's format
+ onComment: comments,
+ // collect token ranges
+ onToken: tokens
+});
+
+// attach comments using collected information
+escodegen.attachComments(ast, comments, tokens);
+
+// generate code
+console.log(escodegen.generate(ast, {comment: true}));
+// > 'var x = 42; // answer'
+```
+
+[escodegen]: https://github.com/estools/escodegen
+
+### dist/acorn_loose.js ###
+
+This file implements an error-tolerant parser. It exposes a single
+function. The loose parser is accessible in node.js via `require("acorn/dist/acorn_loose")`.
+
+**parse_dammit**`(input, options)` takes the same arguments and
+returns the same syntax tree as the `parse` function in `acorn.js`,
+but never raises an error, and will do its best to parse syntactically
+invalid code in as meaningful a way as it can. It'll insert identifier
+nodes with name `"✖"` as placeholders in places where it can't make
+sense of the input. Depends on `acorn.js`, because it uses the same
+tokenizer.
+
+### dist/walk.js ###
+
+Implements an abstract syntax tree walker. Will store its interface in
+`acorn.walk` when loaded without a module system.
+
+**simple**`(node, visitors, base, state)` does a 'simple' walk over
+a tree. `node` should be the AST node to walk, and `visitors` an
+object with properties whose names correspond to node types in the
+[ESTree spec][estree]. The properties should contain functions
+that will be called with the node object and, if applicable the state
+at that point. The last two arguments are optional. `base` is a walker
+algorithm, and `state` is a start state. The default walker will
+simply visit all statements and expressions and not produce a
+meaningful state. (An example of a use of state is to track scope at
+each point in the tree.)
+
+**ancestor**`(node, visitors, base, state)` does a 'simple' walk over
+a tree, building up an array of ancestor nodes (including the current node)
+and passing the array to the callbacks as a third parameter.
+
+**recursive**`(node, state, functions, base)` does a 'recursive'
+walk, where the walker functions are responsible for continuing the
+walk on the child nodes of their target node. `state` is the start
+state, and `functions` should contain an object that maps node types
+to walker functions. Such functions are called with `(node, state, c)`
+arguments, and can cause the walk to continue on a sub-node by calling
+the `c` argument on it with `(node, state)` arguments. The optional
+`base` argument provides the fallback walker functions for node types
+that aren't handled in the `functions` object. If not given, the
+default walkers will be used.
+
+**make**`(functions, base)` builds a new walker object by using the
+walker functions in `functions` and filling in the missing ones by
+taking defaults from `base`.
+
+**findNodeAt**`(node, start, end, test, base, state)` tries to
+locate a node in a tree at the given start and/or end offsets, which
+satisfies the predicate `test`. `start` and `end` can be either `null`
+(as wildcard) or a number. `test` may be a string (indicating a node
+type) or a function that takes `(nodeType, node)` arguments and
+returns a boolean indicating whether this node is interesting. `base`
+and `state` are optional, and can be used to specify a custom walker.
+Nodes are tested from inner to outer, so if two nodes match the
+boundaries, the inner one will be preferred.
+
+**findNodeAround**`(node, pos, test, base, state)` is a lot like
+`findNodeAt`, but will match any node that exists 'around' (spanning)
+the given position.
+
+**findNodeAfter**`(node, pos, test, base, state)` is similar to
+`findNodeAround`, but will match all nodes *after* the given position
+(testing outer nodes before inner nodes).
+
+## Command line interface
+
+The `bin/acorn` utility can be used to parse a file from the command
+line. It accepts as arguments its input file and the following
+options:
+
+- `--ecma3|--ecma5|--ecma6|--ecma7`: Sets the ECMAScript version to parse. Default is
+ version 5.
+
+- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise.
+
+- `--locations`: Attaches a "loc" object to each node with "start" and
+ "end" subobjects, each of which contains the one-based line and
+ zero-based column numbers in `{line, column}` form.
+
+- `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment.
+
+- `--compact`: No whitespace is used in the AST output.
+
+- `--silent`: Do not output the AST, just return the exit status.
+
+- `--help`: Print the usage information and quit.
+
+The utility spits out the syntax tree as JSON data.
+
+## Build system
+
+Acorn is written in ECMAScript 6, as a set of small modules, in the
+project's `src` directory, and compiled down to bigger ECMAScript 3
+files in `dist` using [Browserify](http://browserify.org) and
+[Babel](http://babeljs.io/). If you are already using Babel, you can
+consider including the modules directly.
+
+The command-line test runner (`npm test`) uses the ES6 modules. The
+browser-based test page (`test/index.html`) uses the compiled modules.
+The `bin/build-acorn.js` script builds the latter from the former.
+
+If you are working on Acorn, you'll probably want to try the code out
+directly, without an intermediate build step. In your scripts, you can
+register the Babel require shim like this:
+
+ require("babel-core/register")
+
+That will allow you to directly `require` the ES6 modules.
+
+## Plugins
+
+Acorn is designed support allow plugins which, within reasonable
+bounds, redefine the way the parser works. Plugins can add new token
+types and new tokenizer contexts (if necessary), and extend methods in
+the parser object. This is not a clean, elegant API—using it requires
+an understanding of Acorn's internals, and plugins are likely to break
+whenever those internals are significantly changed. But still, it is
+_possible_, in this way, to create parsers for JavaScript dialects
+without forking all of Acorn. And in principle it is even possible to
+combine such plugins, so that if you have, for example, a plugin for
+parsing types and a plugin for parsing JSX-style XML literals, you
+could load them both and parse code with both JSX tags and types.
+
+A plugin should register itself by adding a property to
+`acorn.plugins`, which holds a function. Calling `acorn.parse`, a
+`plugins` option can be passed, holding an object mapping plugin names
+to configuration values (or just `true` for plugins that don't take
+options). After the parser object has been created, the initialization
+functions for the chosen plugins are called with `(parser,
+configValue)` arguments. They are expected to use the `parser.extend`
+method to extend parser methods. For example, the `readToken` method
+could be extended like this:
+
+```javascript
+parser.extend("readToken", function(nextMethod) {
+ return function(code) {
+ console.log("Reading a token!")
+ return nextMethod.call(this, code)
+ }
+})
+```
+
+The `nextMethod` argument passed to `extend`'s second argument is the
+previous value of this method, and should usually be called through to
+whenever the extended method does not handle the call itself.
+
+Similarly, the loose parser allows plugins to register themselves via
+`acorn.pluginsLoose`. The extension mechanism is the same as for the
+normal parser:
+
+```javascript
+looseParser.extend("readToken", function(nextMethod) {
+ return function() {
+ console.log("Reading a token in the loose parser!")
+ return nextMethod.call(this)
+ }
+})
+```
+
+### Existing plugins
+
+ - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx)
+ - [`acorn-es7-plugin`](https://github.com/MatAtBread/acorn-es7-plugin/): Parse [async/await syntax proposal](https://github.com/tc39/ecmascript-asyncawait)
+ - [`acorn-object-spread`](https://github.com/UXtemple/acorn-object-spread): Parse [object spread syntax proposal](https://github.com/sebmarkbage/ecmascript-rest-spread)
+ - [`acorn-es7`](https://www.npmjs.com/package/acorn-es7): Parse [decorator syntax proposal](https://github.com/wycats/javascript-decorators)
+ - [`acorn-objj`](https://www.npmjs.com/package/acorn-objj): [Objective-J](http://www.cappuccino-project.org/learn/objective-j.html) language parser built as Acorn plugin
diff --git a/node_modules/acorn/bin/acorn b/node_modules/acorn/bin/acorn
new file mode 100755
index 0000000..cf4acd5
--- /dev/null
+++ b/node_modules/acorn/bin/acorn
@@ -0,0 +1,65 @@
+#!/usr/bin/env node
+'use strict';
+
+var path = require('path');
+var fs = require('fs');
+var acorn = require('../dist/acorn.js');
+
+var infile;
+var forceFile;
+var silent = false;
+var compact = false;
+var tokenize = false;
+var options = {}
+
+function help(status) {
+ var print = (status == 0) ? console.log : console.error
+ print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7]")
+ print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]")
+ process.exit(status)
+}
+
+for (var i = 2; i < process.argv.length; ++i) {
+ var arg = process.argv[i]
+ if ((arg == "-" || arg[0] != "-") && !infile) infile = arg
+ else if (arg == "--" && !infile && i + 2 == process.argv.length) forceFile = infile = process.argv[++i]
+ else if (arg == "--ecma3") options.ecmaVersion = 3
+ else if (arg == "--ecma5") options.ecmaVersion = 5
+ else if (arg == "--ecma6") options.ecmaVersion = 6
+ else if (arg == "--ecma7") options.ecmaVersion = 7
+ else if (arg == "--locations") options.locations = true
+ else if (arg == "--allow-hash-bang") options.allowHashBang = true
+ else if (arg == "--silent") silent = true
+ else if (arg == "--compact") compact = true
+ else if (arg == "--help") help(0)
+ else if (arg == "--tokenize") tokenize = true
+ else if (arg == "--module") options.sourceType = 'module'
+ else help(1)
+}
+
+function run(code) {
+ var result
+ if (!tokenize) {
+ try { result = acorn.parse(code, options) }
+ catch(e) { console.error(e.message); process.exit(1) }
+ } else {
+ result = []
+ var tokenizer = acorn.tokenizer(code, options), token
+ while (true) {
+ try { token = tokenizer.getToken() }
+ catch(e) { console.error(e.message); process.exit(1) }
+ result.push(token)
+ if (token.type == acorn.tokTypes.eof) break
+ }
+ }
+ if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2))
+}
+
+if (forceFile || infile && infile != "-") {
+ run(fs.readFileSync(infile, "utf8"))
+} else {
+ var code = ""
+ process.stdin.resume()
+ process.stdin.on("data", function (chunk) { return code += chunk; })
+ process.stdin.on("end", function () { return run(code); })
+}
\ No newline at end of file
diff --git a/node_modules/acorn/bin/generate-identifier-regex.js b/node_modules/acorn/bin/generate-identifier-regex.js
new file mode 100644
index 0000000..100e8cf
--- /dev/null
+++ b/node_modules/acorn/bin/generate-identifier-regex.js
@@ -0,0 +1,55 @@
+'use strict';
+
+// Which Unicode version should be used?
+var version = '9.0.0';
+
+var start = require('unicode-' + version + '/Binary_Property/ID_Start/code-points.js')
+ .filter(function(ch) { return ch > 0x7f; });
+var last = -1;
+var cont = [0x200c, 0x200d].concat(require('unicode-' + version + '/Binary_Property/ID_Continue/code-points.js')
+ .filter(function(ch) { return ch > 0x7f && search(start, ch, last + 1) == -1; }));
+
+function search(arr, ch, starting) {
+ for (var i = starting; arr[i] <= ch && i < arr.length; last = i++)
+ if (arr[i] === ch)
+ return i;
+ return -1;
+}
+
+function pad(str, width) {
+ while (str.length < width) str = "0" + str;
+ return str;
+}
+
+function esc(code) {
+ var hex = code.toString(16);
+ if (hex.length <= 2) return "\\x" + pad(hex, 2);
+ else return "\\u" + pad(hex, 4);
+}
+
+function generate(chars) {
+ var astral = [], re = "";
+ for (var i = 0, at = 0x10000; i < chars.length; i++) {
+ var from = chars[i], to = from;
+ while (i < chars.length - 1 && chars[i + 1] == to + 1) {
+ i++;
+ to++;
+ }
+ if (to <= 0xffff) {
+ if (from == to) re += esc(from);
+ else if (from + 1 == to) re += esc(from) + esc(to);
+ else re += esc(from) + "-" + esc(to);
+ } else {
+ astral.push(from - at, to - from);
+ at = to;
+ }
+ }
+ return {nonASCII: re, astral: astral};
+}
+
+var startData = generate(start), contData = generate(cont);
+
+console.log("let nonASCIIidentifierStartChars = \"" + startData.nonASCII + "\"");
+console.log("let nonASCIIidentifierChars = \"" + contData.nonASCII + "\"");
+console.log("const astralIdentifierStartCodes = " + JSON.stringify(startData.astral));
+console.log("const astralIdentifierCodes = " + JSON.stringify(contData.astral));
diff --git a/node_modules/acorn/bin/update_authors.sh b/node_modules/acorn/bin/update_authors.sh
new file mode 100755
index 0000000..466c8db
--- /dev/null
+++ b/node_modules/acorn/bin/update_authors.sh
@@ -0,0 +1,6 @@
+# Combine existing list of authors with everyone known in git, sort, add header.
+tail --lines=+3 AUTHORS > AUTHORS.tmp
+git log --format='%aN' | grep -v abraidwood >> AUTHORS.tmp
+echo -e "List of Acorn contributors. Updated before every release.\n" > AUTHORS
+sort -u AUTHORS.tmp >> AUTHORS
+rm -f AUTHORS.tmp
diff --git a/node_modules/acorn/dist/.keep b/node_modules/acorn/dist/.keep
new file mode 100644
index 0000000..e69de29
diff --git a/node_modules/acorn/dist/acorn.es.js b/node_modules/acorn/dist/acorn.es.js
new file mode 100644
index 0000000..4460957
--- /dev/null
+++ b/node_modules/acorn/dist/acorn.es.js
@@ -0,0 +1,3112 @@
+// Reserved word lists for various dialects of the language
+
+var reservedWords = {
+ 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
+ 5: "class enum extends super const export import",
+ 6: "enum",
+ 7: "enum",
+ strict: "implements interface let package private protected public static yield",
+ strictBind: "eval arguments"
+}
+
+// And the keywords
+
+var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"
+
+var keywords = {
+ 5: ecma5AndLessKeywords,
+ 6: ecma5AndLessKeywords + " const class extends export import super"
+}
+
+// ## Character categories
+
+// Big ugly regular expressions that match characters in the
+// whitespace, identifier, and identifier-start categories. These
+// are only applied when a character is found to actually have a
+// code point above 128.
+// Generated by `bin/generate-identifier-regex.js`.
+
+var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fd5\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ae\ua7b0-\ua7b7\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"
+var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d4-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"
+
+var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]")
+var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]")
+
+nonASCIIidentifierStartChars = nonASCIIidentifierChars = null
+
+// These are a run-length and offset encoded representation of the
+// >0xffff code points that are a valid part of identifiers. The
+// offset starts at 0x10000, and each pair of numbers represents an
+// offset to the next range, and then a size of the range. They were
+// generated by bin/generate-identifier-regex.js
+var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,785,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,25,391,63,32,0,449,56,264,8,2,36,18,0,50,29,881,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,65,0,32,6124,20,754,9486,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,10591,541]
+var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,10,2,4,9,83,11,7,0,161,11,6,9,7,3,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,87,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,423,9,838,7,2,7,17,9,57,21,2,13,19882,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]
+
+// This has a complexity linear to the value of the code. The
+// assumption is that looking up astral identifier characters is
+// rare.
+function isInAstralSet(code, set) {
+ var pos = 0x10000
+ for (var i = 0; i < set.length; i += 2) {
+ pos += set[i]
+ if (pos > code) return false
+ pos += set[i + 1]
+ if (pos >= code) return true
+ }
+}
+
+// Test whether a given character code starts an identifier.
+
+function isIdentifierStart(code, astral) {
+ if (code < 65) return code === 36
+ if (code < 91) return true
+ if (code < 97) return code === 95
+ if (code < 123) return true
+ if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code))
+ if (astral === false) return false
+ return isInAstralSet(code, astralIdentifierStartCodes)
+}
+
+// Test whether a given character is part of an identifier.
+
+function isIdentifierChar(code, astral) {
+ if (code < 48) return code === 36
+ if (code < 58) return true
+ if (code < 65) return false
+ if (code < 91) return true
+ if (code < 97) return code === 95
+ if (code < 123) return true
+ if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code))
+ if (astral === false) return false
+ return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
+}
+
+// ## Token types
+
+// The assignment of fine-grained, information-carrying type objects
+// allows the tokenizer to store the information it has about a
+// token in a way that is very cheap for the parser to look up.
+
+// All token type variables start with an underscore, to make them
+// easy to recognize.
+
+// The `beforeExpr` property is used to disambiguate between regular
+// expressions and divisions. It is set on all token types that can
+// be followed by an expression (thus, a slash after them would be a
+// regular expression).
+//
+// The `startsExpr` property is used to check if the token ends a
+// `yield` expression. It is set on all token types that either can
+// directly start an expression (like a quotation mark) or can
+// continue an expression (like the body of a string).
+//
+// `isLoop` marks a keyword as starting a loop, which is important
+// to know when parsing a label, in order to allow or disallow
+// continue jumps to that label.
+
+var TokenType = function TokenType(label, conf) {
+ if ( conf === void 0 ) conf = {};
+
+ this.label = label
+ this.keyword = conf.keyword
+ this.beforeExpr = !!conf.beforeExpr
+ this.startsExpr = !!conf.startsExpr
+ this.isLoop = !!conf.isLoop
+ this.isAssign = !!conf.isAssign
+ this.prefix = !!conf.prefix
+ this.postfix = !!conf.postfix
+ this.binop = conf.binop || null
+ this.updateContext = null
+};
+
+function binop(name, prec) {
+ return new TokenType(name, {beforeExpr: true, binop: prec})
+}
+var beforeExpr = {beforeExpr: true};
+var startsExpr = {startsExpr: true};
+// Map keyword names to token types.
+
+var keywordTypes = {}
+
+// Succinct definitions of keyword token types
+function kw(name, options) {
+ if ( options === void 0 ) options = {};
+
+ options.keyword = name
+ return keywordTypes[name] = new TokenType(name, options)
+}
+
+var tt = {
+ num: new TokenType("num", startsExpr),
+ regexp: new TokenType("regexp", startsExpr),
+ string: new TokenType("string", startsExpr),
+ name: new TokenType("name", startsExpr),
+ eof: new TokenType("eof"),
+
+ // Punctuation token types.
+ bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
+ bracketR: new TokenType("]"),
+ braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
+ braceR: new TokenType("}"),
+ parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
+ parenR: new TokenType(")"),
+ comma: new TokenType(",", beforeExpr),
+ semi: new TokenType(";", beforeExpr),
+ colon: new TokenType(":", beforeExpr),
+ dot: new TokenType("."),
+ question: new TokenType("?", beforeExpr),
+ arrow: new TokenType("=>", beforeExpr),
+ template: new TokenType("template"),
+ ellipsis: new TokenType("...", beforeExpr),
+ backQuote: new TokenType("`", startsExpr),
+ dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
+
+ // Operators. These carry several kinds of properties to help the
+ // parser use them properly (the presence of these properties is
+ // what categorizes them as operators).
+ //
+ // `binop`, when present, specifies that this operator is a binary
+ // operator, and will refer to its precedence.
+ //
+ // `prefix` and `postfix` mark the operator as a prefix or postfix
+ // unary operator.
+ //
+ // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
+ // binary operators with a very low precedence, that should result
+ // in AssignmentExpression nodes.
+
+ eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
+ assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
+ incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
+ prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}),
+ logicalOR: binop("||", 1),
+ logicalAND: binop("&&", 2),
+ bitwiseOR: binop("|", 3),
+ bitwiseXOR: binop("^", 4),
+ bitwiseAND: binop("&", 5),
+ equality: binop("==/!=", 6),
+ relational: binop(">", 7),
+ bitShift: binop("<>>", 8),
+ plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
+ modulo: binop("%", 10),
+ star: binop("*", 10),
+ slash: binop("/", 10),
+ starstar: new TokenType("**", {beforeExpr: true}),
+
+ // Keyword token types.
+ _break: kw("break"),
+ _case: kw("case", beforeExpr),
+ _catch: kw("catch"),
+ _continue: kw("continue"),
+ _debugger: kw("debugger"),
+ _default: kw("default", beforeExpr),
+ _do: kw("do", {isLoop: true, beforeExpr: true}),
+ _else: kw("else", beforeExpr),
+ _finally: kw("finally"),
+ _for: kw("for", {isLoop: true}),
+ _function: kw("function", startsExpr),
+ _if: kw("if"),
+ _return: kw("return", beforeExpr),
+ _switch: kw("switch"),
+ _throw: kw("throw", beforeExpr),
+ _try: kw("try"),
+ _var: kw("var"),
+ _const: kw("const"),
+ _while: kw("while", {isLoop: true}),
+ _with: kw("with"),
+ _new: kw("new", {beforeExpr: true, startsExpr: true}),
+ _this: kw("this", startsExpr),
+ _super: kw("super", startsExpr),
+ _class: kw("class"),
+ _extends: kw("extends", beforeExpr),
+ _export: kw("export"),
+ _import: kw("import"),
+ _null: kw("null", startsExpr),
+ _true: kw("true", startsExpr),
+ _false: kw("false", startsExpr),
+ _in: kw("in", {beforeExpr: true, binop: 7}),
+ _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
+ _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
+ _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
+ _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
+}
+
+// Matches a whole line break (where CRLF is considered a single
+// line break). Used to count lines.
+
+var lineBreak = /\r\n?|\n|\u2028|\u2029/
+var lineBreakG = new RegExp(lineBreak.source, "g")
+
+function isNewLine(code) {
+ return code === 10 || code === 13 || code === 0x2028 || code == 0x2029
+}
+
+var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/
+
+var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g
+
+function isArray(obj) {
+ return Object.prototype.toString.call(obj) === "[object Array]"
+}
+
+// Checks if an object has a property.
+
+function has(obj, propName) {
+ return Object.prototype.hasOwnProperty.call(obj, propName)
+}
+
+// These are used when `options.locations` is on, for the
+// `startLoc` and `endLoc` properties.
+
+var Position = function Position(line, col) {
+ this.line = line
+ this.column = col
+};
+
+Position.prototype.offset = function offset (n) {
+ return new Position(this.line, this.column + n)
+};
+
+var SourceLocation = function SourceLocation(p, start, end) {
+ this.start = start
+ this.end = end
+ if (p.sourceFile !== null) this.source = p.sourceFile
+};
+
+// The `getLineInfo` function is mostly useful when the
+// `locations` option is off (for performance reasons) and you
+// want to find the line/column position for a given character
+// offset. `input` should be the code string that the offset refers
+// into.
+
+function getLineInfo(input, offset) {
+ for (var line = 1, cur = 0;;) {
+ lineBreakG.lastIndex = cur
+ var match = lineBreakG.exec(input)
+ if (match && match.index < offset) {
+ ++line
+ cur = match.index + match[0].length
+ } else {
+ return new Position(line, offset - cur)
+ }
+ }
+}
+
+// A second optional argument can be given to further configure
+// the parser process. These options are recognized:
+
+var defaultOptions = {
+ // `ecmaVersion` indicates the ECMAScript version to parse. Must
+ // be either 3, or 5, or 6. This influences support for strict
+ // mode, the set of reserved words, support for getters and
+ // setters and other features. The default is 6.
+ ecmaVersion: 6,
+ // Source type ("script" or "module") for different semantics
+ sourceType: "script",
+ // `onInsertedSemicolon` can be a callback that will be called
+ // when a semicolon is automatically inserted. It will be passed
+ // th position of the comma as an offset, and if `locations` is
+ // enabled, it is given the location as a `{line, column}` object
+ // as second argument.
+ onInsertedSemicolon: null,
+ // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
+ // trailing commas.
+ onTrailingComma: null,
+ // By default, reserved words are only enforced if ecmaVersion >= 5.
+ // Set `allowReserved` to a boolean value to explicitly turn this on
+ // an off. When this option has the value "never", reserved words
+ // and keywords can also not be used as property names.
+ allowReserved: null,
+ // When enabled, a return at the top level is not considered an
+ // error.
+ allowReturnOutsideFunction: false,
+ // When enabled, import/export statements are not constrained to
+ // appearing at the top of the program.
+ allowImportExportEverywhere: false,
+ // When enabled, hashbang directive in the beginning of file
+ // is allowed and treated as a line comment.
+ allowHashBang: false,
+ // When `locations` is on, `loc` properties holding objects with
+ // `start` and `end` properties in `{line, column}` form (with
+ // line being 1-based and column 0-based) will be attached to the
+ // nodes.
+ locations: false,
+ // A function can be passed as `onToken` option, which will
+ // cause Acorn to call that function with object in the same
+ // format as tokens returned from `tokenizer().getToken()`. Note
+ // that you are not allowed to call the parser from the
+ // callback—that will corrupt its internal state.
+ onToken: null,
+ // A function can be passed as `onComment` option, which will
+ // cause Acorn to call that function with `(block, text, start,
+ // end)` parameters whenever a comment is skipped. `block` is a
+ // boolean indicating whether this is a block (`/* */`) comment,
+ // `text` is the content of the comment, and `start` and `end` are
+ // character offsets that denote the start and end of the comment.
+ // When the `locations` option is on, two more parameters are
+ // passed, the full `{line, column}` locations of the start and
+ // end of the comments. Note that you are not allowed to call the
+ // parser from the callback—that will corrupt its internal state.
+ onComment: null,
+ // Nodes have their start and end characters offsets recorded in
+ // `start` and `end` properties (directly on the node, rather than
+ // the `loc` object, which holds line/column data. To also add a
+ // [semi-standardized][range] `range` property holding a `[start,
+ // end]` array with the same numbers, set the `ranges` option to
+ // `true`.
+ //
+ // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
+ ranges: false,
+ // It is possible to parse multiple files into a single AST by
+ // passing the tree produced by parsing the first file as
+ // `program` option in subsequent parses. This will add the
+ // toplevel forms of the parsed file to the `Program` (top) node
+ // of an existing parse tree.
+ program: null,
+ // When `locations` is on, you can pass this to record the source
+ // file in every node's `loc` object.
+ sourceFile: null,
+ // This value, if given, is stored in every node, whether
+ // `locations` is on or off.
+ directSourceFile: null,
+ // When enabled, parenthesized expressions are represented by
+ // (non-standard) ParenthesizedExpression nodes
+ preserveParens: false,
+ plugins: {}
+}
+
+// Interpret and default an options object
+
+function getOptions(opts) {
+ var options = {}
+ for (var opt in defaultOptions)
+ options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]
+ if (options.allowReserved == null)
+ options.allowReserved = options.ecmaVersion < 5
+
+ if (isArray(options.onToken)) {
+ var tokens = options.onToken
+ options.onToken = function (token) { return tokens.push(token); }
+ }
+ if (isArray(options.onComment))
+ options.onComment = pushComment(options, options.onComment)
+
+ return options
+}
+
+function pushComment(options, array) {
+ return function (block, text, start, end, startLoc, endLoc) {
+ var comment = {
+ type: block ? 'Block' : 'Line',
+ value: text,
+ start: start,
+ end: end
+ }
+ if (options.locations)
+ comment.loc = new SourceLocation(this, startLoc, endLoc)
+ if (options.ranges)
+ comment.range = [start, end]
+ array.push(comment)
+ }
+}
+
+// Registered plugins
+var plugins = {}
+
+function keywordRegexp(words) {
+ return new RegExp("^(" + words.replace(/ /g, "|") + ")$")
+}
+
+var Parser = function Parser(options, input, startPos) {
+ this.options = options = getOptions(options)
+ this.sourceFile = options.sourceFile
+ this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5])
+ var reserved = options.allowReserved ? "" :
+ reservedWords[options.ecmaVersion] + (options.sourceType == "module" ? " await" : "")
+ this.reservedWords = keywordRegexp(reserved)
+ var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict
+ this.reservedWordsStrict = keywordRegexp(reservedStrict)
+ this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind)
+ this.input = String(input)
+
+ // Used to signal to callers of `readWord1` whether the word
+ // contained any escape sequences. This is needed because words with
+ // escape sequences must not be interpreted as keywords.
+ this.containsEsc = false
+
+ // Load plugins
+ this.loadPlugins(options.plugins)
+
+ // Set up token state
+
+ // The current position of the tokenizer in the input.
+ if (startPos) {
+ this.pos = startPos
+ this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos))
+ this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length
+ } else {
+ this.pos = this.lineStart = 0
+ this.curLine = 1
+ }
+
+ // Properties of the current token:
+ // Its type
+ this.type = tt.eof
+ // For tokens that include more information than their type, the value
+ this.value = null
+ // Its start and end offset
+ this.start = this.end = this.pos
+ // And, if locations are used, the {line, column} object
+ // corresponding to those offsets
+ this.startLoc = this.endLoc = this.curPosition()
+
+ // Position information for the previous token
+ this.lastTokEndLoc = this.lastTokStartLoc = null
+ this.lastTokStart = this.lastTokEnd = this.pos
+
+ // The context stack is used to superficially track syntactic
+ // context to predict whether a regular expression is allowed in a
+ // given position.
+ this.context = this.initialContext()
+ this.exprAllowed = true
+
+ // Figure out if it's a module code.
+ this.strict = this.inModule = options.sourceType === "module"
+
+ // Used to signify the start of a potential arrow function
+ this.potentialArrowAt = -1
+
+ // Flags to track whether we are in a function, a generator.
+ this.inFunction = this.inGenerator = false
+ // Labels in scope.
+ this.labels = []
+
+ // If enabled, skip leading hashbang line.
+ if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!')
+ this.skipLineComment(2)
+};
+
+// DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
+Parser.prototype.isKeyword = function isKeyword (word) { return this.keywords.test(word) };
+Parser.prototype.isReservedWord = function isReservedWord (word) { return this.reservedWords.test(word) };
+
+Parser.prototype.extend = function extend (name, f) {
+ this[name] = f(this[name])
+};
+
+Parser.prototype.loadPlugins = function loadPlugins (pluginConfigs) {
+ var this$1 = this;
+
+ for (var name in pluginConfigs) {
+ var plugin = plugins[name]
+ if (!plugin) throw new Error("Plugin '" + name + "' not found")
+ plugin(this$1, pluginConfigs[name])
+ }
+};
+
+Parser.prototype.parse = function parse () {
+ var node = this.options.program || this.startNode()
+ this.nextToken()
+ return this.parseTopLevel(node)
+};
+
+var pp = Parser.prototype
+
+// ## Parser utilities
+
+// Test whether a statement node is the string literal `"use strict"`.
+
+pp.isUseStrict = function(stmt) {
+ return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
+ stmt.expression.type === "Literal" &&
+ stmt.expression.raw.slice(1, -1) === "use strict"
+}
+
+// Predicate that tests whether the next token is of the given
+// type, and if yes, consumes it as a side effect.
+
+pp.eat = function(type) {
+ if (this.type === type) {
+ this.next()
+ return true
+ } else {
+ return false
+ }
+}
+
+// Tests whether parsed token is a contextual keyword.
+
+pp.isContextual = function(name) {
+ return this.type === tt.name && this.value === name
+}
+
+// Consumes contextual keyword if possible.
+
+pp.eatContextual = function(name) {
+ return this.value === name && this.eat(tt.name)
+}
+
+// Asserts that following token is given contextual keyword.
+
+pp.expectContextual = function(name) {
+ if (!this.eatContextual(name)) this.unexpected()
+}
+
+// Test whether a semicolon can be inserted at the current position.
+
+pp.canInsertSemicolon = function() {
+ return this.type === tt.eof ||
+ this.type === tt.braceR ||
+ lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
+}
+
+pp.insertSemicolon = function() {
+ if (this.canInsertSemicolon()) {
+ if (this.options.onInsertedSemicolon)
+ this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc)
+ return true
+ }
+}
+
+// Consume a semicolon, or, failing that, see if we are allowed to
+// pretend that there is a semicolon at this position.
+
+pp.semicolon = function() {
+ if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected()
+}
+
+pp.afterTrailingComma = function(tokType) {
+ if (this.type == tokType) {
+ if (this.options.onTrailingComma)
+ this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc)
+ this.next()
+ return true
+ }
+}
+
+// Expect a token of a given type. If found, consume it, otherwise,
+// raise an unexpected token error.
+
+pp.expect = function(type) {
+ this.eat(type) || this.unexpected()
+}
+
+// Raise an unexpected token error.
+
+pp.unexpected = function(pos) {
+ this.raise(pos != null ? pos : this.start, "Unexpected token")
+}
+
+var DestructuringErrors = function DestructuringErrors() {
+ this.shorthandAssign = 0
+ this.trailingComma = 0
+};
+
+pp.checkPatternErrors = function(refDestructuringErrors, andThrow) {
+ var trailing = refDestructuringErrors && refDestructuringErrors.trailingComma
+ if (!andThrow) return !!trailing
+ if (trailing) this.raise(trailing, "Comma is not permitted after the rest element")
+}
+
+pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
+ var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign
+ if (!andThrow) return !!pos
+ if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns")
+}
+
+var pp$1 = Parser.prototype
+
+// ### Statement parsing
+
+// Parse a program. Initializes the parser, reads any number of
+// statements, and wraps them in a Program node. Optionally takes a
+// `program` argument. If present, the statements will be appended
+// to its body instead of creating a new node.
+
+pp$1.parseTopLevel = function(node) {
+ var this$1 = this;
+
+ var first = true
+ if (!node.body) node.body = []
+ while (this.type !== tt.eof) {
+ var stmt = this$1.parseStatement(true, true)
+ node.body.push(stmt)
+ if (first) {
+ if (this$1.isUseStrict(stmt)) this$1.setStrict(true)
+ first = false
+ }
+ }
+ this.next()
+ if (this.options.ecmaVersion >= 6) {
+ node.sourceType = this.options.sourceType
+ }
+ return this.finishNode(node, "Program")
+}
+
+var loopLabel = {kind: "loop"};
+var switchLabel = {kind: "switch"};
+pp$1.isLet = function() {
+ if (this.type !== tt.name || this.options.ecmaVersion < 6 || this.value != "let") return false
+ skipWhiteSpace.lastIndex = this.pos
+ var skip = skipWhiteSpace.exec(this.input)
+ var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next)
+ if (nextCh === 91 || nextCh == 123) return true // '{' and '['
+ if (isIdentifierStart(nextCh, true)) {
+ for (var pos = next + 1; isIdentifierChar(this.input.charCodeAt(pos), true); ++pos) {}
+ var ident = this.input.slice(next, pos)
+ if (!this.isKeyword(ident)) return true
+ }
+ return false
+}
+
+// Parse a single statement.
+//
+// If expecting a statement and finding a slash operator, parse a
+// regular expression literal. This is to handle cases like
+// `if (foo) /blah/.exec(foo)`, where looking at the previous token
+// does not help.
+
+pp$1.parseStatement = function(declaration, topLevel) {
+ var starttype = this.type, node = this.startNode(), kind
+
+ if (this.isLet()) {
+ starttype = tt._var
+ kind = "let"
+ }
+
+ // Most types of statements are recognized by the keyword they
+ // start with. Many are trivial to parse, some require a bit of
+ // complexity.
+
+ switch (starttype) {
+ case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
+ case tt._debugger: return this.parseDebuggerStatement(node)
+ case tt._do: return this.parseDoStatement(node)
+ case tt._for: return this.parseForStatement(node)
+ case tt._function:
+ if (!declaration && this.options.ecmaVersion >= 6) this.unexpected()
+ return this.parseFunctionStatement(node)
+ case tt._class:
+ if (!declaration) this.unexpected()
+ return this.parseClass(node, true)
+ case tt._if: return this.parseIfStatement(node)
+ case tt._return: return this.parseReturnStatement(node)
+ case tt._switch: return this.parseSwitchStatement(node)
+ case tt._throw: return this.parseThrowStatement(node)
+ case tt._try: return this.parseTryStatement(node)
+ case tt._const: case tt._var:
+ kind = kind || this.value
+ if (!declaration && kind != "var") this.unexpected()
+ return this.parseVarStatement(node, kind)
+ case tt._while: return this.parseWhileStatement(node)
+ case tt._with: return this.parseWithStatement(node)
+ case tt.braceL: return this.parseBlock()
+ case tt.semi: return this.parseEmptyStatement(node)
+ case tt._export:
+ case tt._import:
+ if (!this.options.allowImportExportEverywhere) {
+ if (!topLevel)
+ this.raise(this.start, "'import' and 'export' may only appear at the top level")
+ if (!this.inModule)
+ this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'")
+ }
+ return starttype === tt._import ? this.parseImport(node) : this.parseExport(node)
+
+ // If the statement does not start with a statement keyword or a
+ // brace, it's an ExpressionStatement or LabeledStatement. We
+ // simply start parsing an expression, and afterwards, if the
+ // next token is a colon and the expression was a simple
+ // Identifier node, we switch to interpreting it as a label.
+ default:
+ var maybeName = this.value, expr = this.parseExpression()
+ if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon))
+ return this.parseLabeledStatement(node, maybeName, expr)
+ else return this.parseExpressionStatement(node, expr)
+ }
+}
+
+pp$1.parseBreakContinueStatement = function(node, keyword) {
+ var this$1 = this;
+
+ var isBreak = keyword == "break"
+ this.next()
+ if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null
+ else if (this.type !== tt.name) this.unexpected()
+ else {
+ node.label = this.parseIdent()
+ this.semicolon()
+ }
+
+ // Verify that there is an actual destination to break or
+ // continue to.
+ for (var i = 0; i < this.labels.length; ++i) {
+ var lab = this$1.labels[i]
+ if (node.label == null || lab.name === node.label.name) {
+ if (lab.kind != null && (isBreak || lab.kind === "loop")) break
+ if (node.label && isBreak) break
+ }
+ }
+ if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword)
+ return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
+}
+
+pp$1.parseDebuggerStatement = function(node) {
+ this.next()
+ this.semicolon()
+ return this.finishNode(node, "DebuggerStatement")
+}
+
+pp$1.parseDoStatement = function(node) {
+ this.next()
+ this.labels.push(loopLabel)
+ node.body = this.parseStatement(false)
+ this.labels.pop()
+ this.expect(tt._while)
+ node.test = this.parseParenExpression()
+ if (this.options.ecmaVersion >= 6)
+ this.eat(tt.semi)
+ else
+ this.semicolon()
+ return this.finishNode(node, "DoWhileStatement")
+}
+
+// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
+// loop is non-trivial. Basically, we have to parse the init `var`
+// statement or expression, disallowing the `in` operator (see
+// the second parameter to `parseExpression`), and then check
+// whether the next token is `in` or `of`. When there is no init
+// part (semicolon immediately after the opening parenthesis), it
+// is a regular `for` loop.
+
+pp$1.parseForStatement = function(node) {
+ this.next()
+ this.labels.push(loopLabel)
+ this.expect(tt.parenL)
+ if (this.type === tt.semi) return this.parseFor(node, null)
+ var isLet = this.isLet()
+ if (this.type === tt._var || this.type === tt._const || isLet) {
+ var init$1 = this.startNode(), kind = isLet ? "let" : this.value
+ this.next()
+ this.parseVar(init$1, true, kind)
+ this.finishNode(init$1, "VariableDeclaration")
+ if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 &&
+ !(kind !== "var" && init$1.declarations[0].init))
+ return this.parseForIn(node, init$1)
+ return this.parseFor(node, init$1)
+ }
+ var refDestructuringErrors = new DestructuringErrors
+ var init = this.parseExpression(true, refDestructuringErrors)
+ if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
+ this.checkPatternErrors(refDestructuringErrors, true)
+ this.toAssignable(init)
+ this.checkLVal(init)
+ return this.parseForIn(node, init)
+ } else {
+ this.checkExpressionErrors(refDestructuringErrors, true)
+ }
+ return this.parseFor(node, init)
+}
+
+pp$1.parseFunctionStatement = function(node) {
+ this.next()
+ return this.parseFunction(node, true)
+}
+
+pp$1.parseIfStatement = function(node) {
+ this.next()
+ node.test = this.parseParenExpression()
+ node.consequent = this.parseStatement(false)
+ node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null
+ return this.finishNode(node, "IfStatement")
+}
+
+pp$1.parseReturnStatement = function(node) {
+ if (!this.inFunction && !this.options.allowReturnOutsideFunction)
+ this.raise(this.start, "'return' outside of function")
+ this.next()
+
+ // In `return` (and `break`/`continue`), the keywords with
+ // optional arguments, we eagerly look for a semicolon or the
+ // possibility to insert one.
+
+ if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null
+ else { node.argument = this.parseExpression(); this.semicolon() }
+ return this.finishNode(node, "ReturnStatement")
+}
+
+pp$1.parseSwitchStatement = function(node) {
+ var this$1 = this;
+
+ this.next()
+ node.discriminant = this.parseParenExpression()
+ node.cases = []
+ this.expect(tt.braceL)
+ this.labels.push(switchLabel)
+
+ // Statements under must be grouped (by label) in SwitchCase
+ // nodes. `cur` is used to keep the node that we are currently
+ // adding statements to.
+
+ for (var cur, sawDefault = false; this.type != tt.braceR;) {
+ if (this$1.type === tt._case || this$1.type === tt._default) {
+ var isCase = this$1.type === tt._case
+ if (cur) this$1.finishNode(cur, "SwitchCase")
+ node.cases.push(cur = this$1.startNode())
+ cur.consequent = []
+ this$1.next()
+ if (isCase) {
+ cur.test = this$1.parseExpression()
+ } else {
+ if (sawDefault) this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses")
+ sawDefault = true
+ cur.test = null
+ }
+ this$1.expect(tt.colon)
+ } else {
+ if (!cur) this$1.unexpected()
+ cur.consequent.push(this$1.parseStatement(true))
+ }
+ }
+ if (cur) this.finishNode(cur, "SwitchCase")
+ this.next() // Closing brace
+ this.labels.pop()
+ return this.finishNode(node, "SwitchStatement")
+}
+
+pp$1.parseThrowStatement = function(node) {
+ this.next()
+ if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
+ this.raise(this.lastTokEnd, "Illegal newline after throw")
+ node.argument = this.parseExpression()
+ this.semicolon()
+ return this.finishNode(node, "ThrowStatement")
+}
+
+// Reused empty array added for node fields that are always empty.
+
+var empty = []
+
+pp$1.parseTryStatement = function(node) {
+ this.next()
+ node.block = this.parseBlock()
+ node.handler = null
+ if (this.type === tt._catch) {
+ var clause = this.startNode()
+ this.next()
+ this.expect(tt.parenL)
+ clause.param = this.parseBindingAtom()
+ this.checkLVal(clause.param, true)
+ this.expect(tt.parenR)
+ clause.body = this.parseBlock()
+ node.handler = this.finishNode(clause, "CatchClause")
+ }
+ node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null
+ if (!node.handler && !node.finalizer)
+ this.raise(node.start, "Missing catch or finally clause")
+ return this.finishNode(node, "TryStatement")
+}
+
+pp$1.parseVarStatement = function(node, kind) {
+ this.next()
+ this.parseVar(node, false, kind)
+ this.semicolon()
+ return this.finishNode(node, "VariableDeclaration")
+}
+
+pp$1.parseWhileStatement = function(node) {
+ this.next()
+ node.test = this.parseParenExpression()
+ this.labels.push(loopLabel)
+ node.body = this.parseStatement(false)
+ this.labels.pop()
+ return this.finishNode(node, "WhileStatement")
+}
+
+pp$1.parseWithStatement = function(node) {
+ if (this.strict) this.raise(this.start, "'with' in strict mode")
+ this.next()
+ node.object = this.parseParenExpression()
+ node.body = this.parseStatement(false)
+ return this.finishNode(node, "WithStatement")
+}
+
+pp$1.parseEmptyStatement = function(node) {
+ this.next()
+ return this.finishNode(node, "EmptyStatement")
+}
+
+pp$1.parseLabeledStatement = function(node, maybeName, expr) {
+ var this$1 = this;
+
+ for (var i = 0; i < this.labels.length; ++i)
+ if (this$1.labels[i].name === maybeName) this$1.raise(expr.start, "Label '" + maybeName + "' is already declared")
+ var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null
+ for (var i$1 = this.labels.length - 1; i$1 >= 0; i$1--) {
+ var label = this$1.labels[i$1]
+ if (label.statementStart == node.start) {
+ label.statementStart = this$1.start
+ label.kind = kind
+ } else break
+ }
+ this.labels.push({name: maybeName, kind: kind, statementStart: this.start})
+ node.body = this.parseStatement(true)
+ this.labels.pop()
+ node.label = expr
+ return this.finishNode(node, "LabeledStatement")
+}
+
+pp$1.parseExpressionStatement = function(node, expr) {
+ node.expression = expr
+ this.semicolon()
+ return this.finishNode(node, "ExpressionStatement")
+}
+
+// Parse a semicolon-enclosed block of statements, handling `"use
+// strict"` declarations when `allowStrict` is true (used for
+// function bodies).
+
+pp$1.parseBlock = function(allowStrict) {
+ var this$1 = this;
+
+ var node = this.startNode(), first = true, oldStrict
+ node.body = []
+ this.expect(tt.braceL)
+ while (!this.eat(tt.braceR)) {
+ var stmt = this$1.parseStatement(true)
+ node.body.push(stmt)
+ if (first && allowStrict && this$1.isUseStrict(stmt)) {
+ oldStrict = this$1.strict
+ this$1.setStrict(this$1.strict = true)
+ }
+ first = false
+ }
+ if (oldStrict === false) this.setStrict(false)
+ return this.finishNode(node, "BlockStatement")
+}
+
+// Parse a regular `for` loop. The disambiguation code in
+// `parseStatement` will already have parsed the init statement or
+// expression.
+
+pp$1.parseFor = function(node, init) {
+ node.init = init
+ this.expect(tt.semi)
+ node.test = this.type === tt.semi ? null : this.parseExpression()
+ this.expect(tt.semi)
+ node.update = this.type === tt.parenR ? null : this.parseExpression()
+ this.expect(tt.parenR)
+ node.body = this.parseStatement(false)
+ this.labels.pop()
+ return this.finishNode(node, "ForStatement")
+}
+
+// Parse a `for`/`in` and `for`/`of` loop, which are almost
+// same from parser's perspective.
+
+pp$1.parseForIn = function(node, init) {
+ var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement"
+ this.next()
+ node.left = init
+ node.right = this.parseExpression()
+ this.expect(tt.parenR)
+ node.body = this.parseStatement(false)
+ this.labels.pop()
+ return this.finishNode(node, type)
+}
+
+// Parse a list of variable declarations.
+
+pp$1.parseVar = function(node, isFor, kind) {
+ var this$1 = this;
+
+ node.declarations = []
+ node.kind = kind
+ for (;;) {
+ var decl = this$1.startNode()
+ this$1.parseVarId(decl)
+ if (this$1.eat(tt.eq)) {
+ decl.init = this$1.parseMaybeAssign(isFor)
+ } else if (kind === "const" && !(this$1.type === tt._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) {
+ this$1.unexpected()
+ } else if (decl.id.type != "Identifier" && !(isFor && (this$1.type === tt._in || this$1.isContextual("of")))) {
+ this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value")
+ } else {
+ decl.init = null
+ }
+ node.declarations.push(this$1.finishNode(decl, "VariableDeclarator"))
+ if (!this$1.eat(tt.comma)) break
+ }
+ return node
+}
+
+pp$1.parseVarId = function(decl) {
+ decl.id = this.parseBindingAtom()
+ this.checkLVal(decl.id, true)
+}
+
+// Parse a function declaration or literal (depending on the
+// `isStatement` parameter).
+
+pp$1.parseFunction = function(node, isStatement, allowExpressionBody) {
+ this.initFunction(node)
+ if (this.options.ecmaVersion >= 6)
+ node.generator = this.eat(tt.star)
+ var oldInGen = this.inGenerator
+ this.inGenerator = node.generator
+ if (isStatement || this.type === tt.name)
+ node.id = this.parseIdent()
+ this.parseFunctionParams(node)
+ this.parseFunctionBody(node, allowExpressionBody)
+ this.inGenerator = oldInGen
+ return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression")
+}
+
+pp$1.parseFunctionParams = function(node) {
+ this.expect(tt.parenL)
+ node.params = this.parseBindingList(tt.parenR, false, false, true)
+}
+
+// Parse a class declaration or literal (depending on the
+// `isStatement` parameter).
+
+pp$1.parseClass = function(node, isStatement) {
+ var this$1 = this;
+
+ this.next()
+ this.parseClassId(node, isStatement)
+ this.parseClassSuper(node)
+ var classBody = this.startNode()
+ var hadConstructor = false
+ classBody.body = []
+ this.expect(tt.braceL)
+ while (!this.eat(tt.braceR)) {
+ if (this$1.eat(tt.semi)) continue
+ var method = this$1.startNode()
+ var isGenerator = this$1.eat(tt.star)
+ var isMaybeStatic = this$1.type === tt.name && this$1.value === "static"
+ this$1.parsePropertyName(method)
+ method.static = isMaybeStatic && this$1.type !== tt.parenL
+ if (method.static) {
+ if (isGenerator) this$1.unexpected()
+ isGenerator = this$1.eat(tt.star)
+ this$1.parsePropertyName(method)
+ }
+ method.kind = "method"
+ var isGetSet = false
+ if (!method.computed) {
+ var key = method.key;
+ if (!isGenerator && key.type === "Identifier" && this$1.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
+ isGetSet = true
+ method.kind = key.name
+ key = this$1.parsePropertyName(method)
+ }
+ if (!method.static && (key.type === "Identifier" && key.name === "constructor" ||
+ key.type === "Literal" && key.value === "constructor")) {
+ if (hadConstructor) this$1.raise(key.start, "Duplicate constructor in the same class")
+ if (isGetSet) this$1.raise(key.start, "Constructor can't have get/set modifier")
+ if (isGenerator) this$1.raise(key.start, "Constructor can't be a generator")
+ method.kind = "constructor"
+ hadConstructor = true
+ }
+ }
+ this$1.parseClassMethod(classBody, method, isGenerator)
+ if (isGetSet) {
+ var paramCount = method.kind === "get" ? 0 : 1
+ if (method.value.params.length !== paramCount) {
+ var start = method.value.start
+ if (method.kind === "get")
+ this$1.raiseRecoverable(start, "getter should have no params")
+ else
+ this$1.raiseRecoverable(start, "setter should have exactly one param")
+ }
+ if (method.kind === "set" && method.value.params[0].type === "RestElement")
+ this$1.raise(method.value.params[0].start, "Setter cannot use rest params")
+ }
+ }
+ node.body = this.finishNode(classBody, "ClassBody")
+ return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
+}
+
+pp$1.parseClassMethod = function(classBody, method, isGenerator) {
+ method.value = this.parseMethod(isGenerator)
+ classBody.body.push(this.finishNode(method, "MethodDefinition"))
+}
+
+pp$1.parseClassId = function(node, isStatement) {
+ node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null
+}
+
+pp$1.parseClassSuper = function(node) {
+ node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null
+}
+
+// Parses module export declaration.
+
+pp$1.parseExport = function(node) {
+ var this$1 = this;
+
+ this.next()
+ // export * from '...'
+ if (this.eat(tt.star)) {
+ this.expectContextual("from")
+ node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
+ this.semicolon()
+ return this.finishNode(node, "ExportAllDeclaration")
+ }
+ if (this.eat(tt._default)) { // export default ...
+ var parens = this.type == tt.parenL
+ var expr = this.parseMaybeAssign()
+ var needsSemi = true
+ if (!parens && (expr.type == "FunctionExpression" ||
+ expr.type == "ClassExpression")) {
+ needsSemi = false
+ if (expr.id) {
+ expr.type = expr.type == "FunctionExpression"
+ ? "FunctionDeclaration"
+ : "ClassDeclaration"
+ }
+ }
+ node.declaration = expr
+ if (needsSemi) this.semicolon()
+ return this.finishNode(node, "ExportDefaultDeclaration")
+ }
+ // export var|const|let|function|class ...
+ if (this.shouldParseExportStatement()) {
+ node.declaration = this.parseStatement(true)
+ node.specifiers = []
+ node.source = null
+ } else { // export { x, y as z } [from '...']
+ node.declaration = null
+ node.specifiers = this.parseExportSpecifiers()
+ if (this.eatContextual("from")) {
+ node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
+ } else {
+ // check for keywords used as local names
+ for (var i = 0; i < node.specifiers.length; i++) {
+ if (this$1.keywords.test(node.specifiers[i].local.name) || this$1.reservedWords.test(node.specifiers[i].local.name)) {
+ this$1.unexpected(node.specifiers[i].local.start)
+ }
+ }
+
+ node.source = null
+ }
+ this.semicolon()
+ }
+ return this.finishNode(node, "ExportNamedDeclaration")
+}
+
+pp$1.shouldParseExportStatement = function() {
+ return this.type.keyword || this.isLet()
+}
+
+// Parses a comma-separated list of module exports.
+
+pp$1.parseExportSpecifiers = function() {
+ var this$1 = this;
+
+ var nodes = [], first = true
+ // export { x, y as z } [from '...']
+ this.expect(tt.braceL)
+ while (!this.eat(tt.braceR)) {
+ if (!first) {
+ this$1.expect(tt.comma)
+ if (this$1.afterTrailingComma(tt.braceR)) break
+ } else first = false
+
+ var node = this$1.startNode()
+ node.local = this$1.parseIdent(this$1.type === tt._default)
+ node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local
+ nodes.push(this$1.finishNode(node, "ExportSpecifier"))
+ }
+ return nodes
+}
+
+// Parses import declaration.
+
+pp$1.parseImport = function(node) {
+ this.next()
+ // import '...'
+ if (this.type === tt.string) {
+ node.specifiers = empty
+ node.source = this.parseExprAtom()
+ } else {
+ node.specifiers = this.parseImportSpecifiers()
+ this.expectContextual("from")
+ node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
+ }
+ this.semicolon()
+ return this.finishNode(node, "ImportDeclaration")
+}
+
+// Parses a comma-separated list of module imports.
+
+pp$1.parseImportSpecifiers = function() {
+ var this$1 = this;
+
+ var nodes = [], first = true
+ if (this.type === tt.name) {
+ // import defaultObj, { x, y as z } from '...'
+ var node = this.startNode()
+ node.local = this.parseIdent()
+ this.checkLVal(node.local, true)
+ nodes.push(this.finishNode(node, "ImportDefaultSpecifier"))
+ if (!this.eat(tt.comma)) return nodes
+ }
+ if (this.type === tt.star) {
+ var node$1 = this.startNode()
+ this.next()
+ this.expectContextual("as")
+ node$1.local = this.parseIdent()
+ this.checkLVal(node$1.local, true)
+ nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"))
+ return nodes
+ }
+ this.expect(tt.braceL)
+ while (!this.eat(tt.braceR)) {
+ if (!first) {
+ this$1.expect(tt.comma)
+ if (this$1.afterTrailingComma(tt.braceR)) break
+ } else first = false
+
+ var node$2 = this$1.startNode()
+ node$2.imported = this$1.parseIdent(true)
+ if (this$1.eatContextual("as")) {
+ node$2.local = this$1.parseIdent()
+ } else {
+ node$2.local = node$2.imported
+ if (this$1.isKeyword(node$2.local.name)) this$1.unexpected(node$2.local.start)
+ if (this$1.reservedWordsStrict.test(node$2.local.name)) this$1.raise(node$2.local.start, "The keyword '" + node$2.local.name + "' is reserved")
+ }
+ this$1.checkLVal(node$2.local, true)
+ nodes.push(this$1.finishNode(node$2, "ImportSpecifier"))
+ }
+ return nodes
+}
+
+var pp$2 = Parser.prototype
+
+// Convert existing expression atom to assignable pattern
+// if possible.
+
+pp$2.toAssignable = function(node, isBinding) {
+ var this$1 = this;
+
+ if (this.options.ecmaVersion >= 6 && node) {
+ switch (node.type) {
+ case "Identifier":
+ case "ObjectPattern":
+ case "ArrayPattern":
+ break
+
+ case "ObjectExpression":
+ node.type = "ObjectPattern"
+ for (var i = 0; i < node.properties.length; i++) {
+ var prop = node.properties[i]
+ if (prop.kind !== "init") this$1.raise(prop.key.start, "Object pattern can't contain getter or setter")
+ this$1.toAssignable(prop.value, isBinding)
+ }
+ break
+
+ case "ArrayExpression":
+ node.type = "ArrayPattern"
+ this.toAssignableList(node.elements, isBinding)
+ break
+
+ case "AssignmentExpression":
+ if (node.operator === "=") {
+ node.type = "AssignmentPattern"
+ delete node.operator
+ // falls through to AssignmentPattern
+ } else {
+ this.raise(node.left.end, "Only '=' operator can be used for specifying default value.")
+ break
+ }
+
+ case "AssignmentPattern":
+ if (node.right.type === "YieldExpression")
+ this.raise(node.right.start, "Yield expression cannot be a default value")
+ break
+
+ case "ParenthesizedExpression":
+ node.expression = this.toAssignable(node.expression, isBinding)
+ break
+
+ case "MemberExpression":
+ if (!isBinding) break
+
+ default:
+ this.raise(node.start, "Assigning to rvalue")
+ }
+ }
+ return node
+}
+
+// Convert list of expression atoms to binding list.
+
+pp$2.toAssignableList = function(exprList, isBinding) {
+ var this$1 = this;
+
+ var end = exprList.length
+ if (end) {
+ var last = exprList[end - 1]
+ if (last && last.type == "RestElement") {
+ --end
+ } else if (last && last.type == "SpreadElement") {
+ last.type = "RestElement"
+ var arg = last.argument
+ this.toAssignable(arg, isBinding)
+ if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern")
+ this.unexpected(arg.start)
+ --end
+ }
+
+ if (isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
+ this.unexpected(last.argument.start)
+ }
+ for (var i = 0; i < end; i++) {
+ var elt = exprList[i]
+ if (elt) this$1.toAssignable(elt, isBinding)
+ }
+ return exprList
+}
+
+// Parses spread element.
+
+pp$2.parseSpread = function(refDestructuringErrors) {
+ var node = this.startNode()
+ this.next()
+ node.argument = this.parseMaybeAssign(false, refDestructuringErrors)
+ return this.finishNode(node, "SpreadElement")
+}
+
+pp$2.parseRest = function(allowNonIdent) {
+ var node = this.startNode()
+ this.next()
+
+ // RestElement inside of a function parameter must be an identifier
+ if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected()
+ else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected()
+
+ return this.finishNode(node, "RestElement")
+}
+
+// Parses lvalue (assignable) atom.
+
+pp$2.parseBindingAtom = function() {
+ if (this.options.ecmaVersion < 6) return this.parseIdent()
+ switch (this.type) {
+ case tt.name:
+ return this.parseIdent()
+
+ case tt.bracketL:
+ var node = this.startNode()
+ this.next()
+ node.elements = this.parseBindingList(tt.bracketR, true, true)
+ return this.finishNode(node, "ArrayPattern")
+
+ case tt.braceL:
+ return this.parseObj(true)
+
+ default:
+ this.unexpected()
+ }
+}
+
+pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) {
+ var this$1 = this;
+
+ var elts = [], first = true
+ while (!this.eat(close)) {
+ if (first) first = false
+ else this$1.expect(tt.comma)
+ if (allowEmpty && this$1.type === tt.comma) {
+ elts.push(null)
+ } else if (allowTrailingComma && this$1.afterTrailingComma(close)) {
+ break
+ } else if (this$1.type === tt.ellipsis) {
+ var rest = this$1.parseRest(allowNonIdent)
+ this$1.parseBindingListItem(rest)
+ elts.push(rest)
+ if (this$1.type === tt.comma) this$1.raise(this$1.start, "Comma is not permitted after the rest element")
+ this$1.expect(close)
+ break
+ } else {
+ var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc)
+ this$1.parseBindingListItem(elem)
+ elts.push(elem)
+ }
+ }
+ return elts
+}
+
+pp$2.parseBindingListItem = function(param) {
+ return param
+}
+
+// Parses assignment pattern around given atom if possible.
+
+pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
+ left = left || this.parseBindingAtom()
+ if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left
+ var node = this.startNodeAt(startPos, startLoc)
+ node.left = left
+ node.right = this.parseMaybeAssign()
+ return this.finishNode(node, "AssignmentPattern")
+}
+
+// Verify that a node is an lval — something that can be assigned
+// to.
+
+pp$2.checkLVal = function(expr, isBinding, checkClashes) {
+ var this$1 = this;
+
+ switch (expr.type) {
+ case "Identifier":
+ if (this.strict && this.reservedWordsStrictBind.test(expr.name))
+ this.raiseRecoverable(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode")
+ if (checkClashes) {
+ if (has(checkClashes, expr.name))
+ this.raiseRecoverable(expr.start, "Argument name clash")
+ checkClashes[expr.name] = true
+ }
+ break
+
+ case "MemberExpression":
+ if (isBinding) this.raiseRecoverable(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression")
+ break
+
+ case "ObjectPattern":
+ for (var i = 0; i < expr.properties.length; i++)
+ this$1.checkLVal(expr.properties[i].value, isBinding, checkClashes)
+ break
+
+ case "ArrayPattern":
+ for (var i$1 = 0; i$1 < expr.elements.length; i$1++) {
+ var elem = expr.elements[i$1]
+ if (elem) this$1.checkLVal(elem, isBinding, checkClashes)
+ }
+ break
+
+ case "AssignmentPattern":
+ this.checkLVal(expr.left, isBinding, checkClashes)
+ break
+
+ case "RestElement":
+ this.checkLVal(expr.argument, isBinding, checkClashes)
+ break
+
+ case "ParenthesizedExpression":
+ this.checkLVal(expr.expression, isBinding, checkClashes)
+ break
+
+ default:
+ this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue")
+ }
+}
+
+var pp$3 = Parser.prototype
+
+// Check if property name clashes with already added.
+// Object/class getters and setters are not allowed to clash —
+// either with each other or with an init property — and in
+// strict mode, init properties are also not allowed to be repeated.
+
+pp$3.checkPropClash = function(prop, propHash) {
+ if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
+ return
+ var key = prop.key;
+ var name
+ switch (key.type) {
+ case "Identifier": name = key.name; break
+ case "Literal": name = String(key.value); break
+ default: return
+ }
+ var kind = prop.kind;
+ if (this.options.ecmaVersion >= 6) {
+ if (name === "__proto__" && kind === "init") {
+ if (propHash.proto) this.raiseRecoverable(key.start, "Redefinition of __proto__ property")
+ propHash.proto = true
+ }
+ return
+ }
+ name = "$" + name
+ var other = propHash[name]
+ if (other) {
+ var isGetSet = kind !== "init"
+ if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init))
+ this.raiseRecoverable(key.start, "Redefinition of property")
+ } else {
+ other = propHash[name] = {
+ init: false,
+ get: false,
+ set: false
+ }
+ }
+ other[kind] = true
+}
+
+// ### Expression parsing
+
+// These nest, from the most general expression type at the top to
+// 'atomic', nondivisible expression types at the bottom. Most of
+// the functions will simply let the function(s) below them parse,
+// and, *if* the syntactic construct they handle is present, wrap
+// the AST node that the inner parser gave them in another node.
+
+// Parse a full expression. The optional arguments are used to
+// forbid the `in` operator (in for loops initalization expressions)
+// and provide reference for storing '=' operator inside shorthand
+// property assignment in contexts where both object expression
+// and object pattern might appear (so it's possible to raise
+// delayed syntax error at correct position).
+
+pp$3.parseExpression = function(noIn, refDestructuringErrors) {
+ var this$1 = this;
+
+ var startPos = this.start, startLoc = this.startLoc
+ var expr = this.parseMaybeAssign(noIn, refDestructuringErrors)
+ if (this.type === tt.comma) {
+ var node = this.startNodeAt(startPos, startLoc)
+ node.expressions = [expr]
+ while (this.eat(tt.comma)) node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors))
+ return this.finishNode(node, "SequenceExpression")
+ }
+ return expr
+}
+
+// Parse an assignment expression. This includes applications of
+// operators like `+=`.
+
+pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
+ if (this.inGenerator && this.isContextual("yield")) return this.parseYield()
+
+ var ownDestructuringErrors = false
+ if (!refDestructuringErrors) {
+ refDestructuringErrors = new DestructuringErrors
+ ownDestructuringErrors = true
+ }
+ var startPos = this.start, startLoc = this.startLoc
+ if (this.type == tt.parenL || this.type == tt.name)
+ this.potentialArrowAt = this.start
+ var left = this.parseMaybeConditional(noIn, refDestructuringErrors)
+ if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc)
+ if (this.type.isAssign) {
+ this.checkPatternErrors(refDestructuringErrors, true)
+ if (!ownDestructuringErrors) DestructuringErrors.call(refDestructuringErrors)
+ var node = this.startNodeAt(startPos, startLoc)
+ node.operator = this.value
+ node.left = this.type === tt.eq ? this.toAssignable(left) : left
+ refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly
+ this.checkLVal(left)
+ this.next()
+ node.right = this.parseMaybeAssign(noIn)
+ return this.finishNode(node, "AssignmentExpression")
+ } else {
+ if (ownDestructuringErrors) this.checkExpressionErrors(refDestructuringErrors, true)
+ }
+ return left
+}
+
+// Parse a ternary conditional (`?:`) operator.
+
+pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
+ var startPos = this.start, startLoc = this.startLoc
+ var expr = this.parseExprOps(noIn, refDestructuringErrors)
+ if (this.checkExpressionErrors(refDestructuringErrors)) return expr
+ if (this.eat(tt.question)) {
+ var node = this.startNodeAt(startPos, startLoc)
+ node.test = expr
+ node.consequent = this.parseMaybeAssign()
+ this.expect(tt.colon)
+ node.alternate = this.parseMaybeAssign(noIn)
+ return this.finishNode(node, "ConditionalExpression")
+ }
+ return expr
+}
+
+// Start the precedence parser.
+
+pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
+ var startPos = this.start, startLoc = this.startLoc
+ var expr = this.parseMaybeUnary(refDestructuringErrors, false)
+ if (this.checkExpressionErrors(refDestructuringErrors)) return expr
+ return this.parseExprOp(expr, startPos, startLoc, -1, noIn)
+}
+
+// Parse binary operators with the operator precedence parsing
+// algorithm. `left` is the left-hand side of the operator.
+// `minPrec` provides context that allows the function to stop and
+// defer further parser to one of its callers when it encounters an
+// operator that has a lower precedence than the set it is parsing.
+
+pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
+ var prec = this.type.binop
+ if (prec != null && (!noIn || this.type !== tt._in)) {
+ if (prec > minPrec) {
+ var logical = this.type === tt.logicalOR || this.type === tt.logicalAND
+ var op = this.value
+ this.next()
+ var startPos = this.start, startLoc = this.startLoc
+ var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn)
+ var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical)
+ return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
+ }
+ }
+ return left
+}
+
+pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
+ var node = this.startNodeAt(startPos, startLoc)
+ node.left = left
+ node.operator = op
+ node.right = right
+ return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
+}
+
+// Parse unary operators, both prefix and postfix.
+
+pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
+ var this$1 = this;
+
+ var startPos = this.start, startLoc = this.startLoc, expr
+ if (this.type.prefix) {
+ var node = this.startNode(), update = this.type === tt.incDec
+ node.operator = this.value
+ node.prefix = true
+ this.next()
+ node.argument = this.parseMaybeUnary(null, true)
+ this.checkExpressionErrors(refDestructuringErrors, true)
+ if (update) this.checkLVal(node.argument)
+ else if (this.strict && node.operator === "delete" &&
+ node.argument.type === "Identifier")
+ this.raiseRecoverable(node.start, "Deleting local variable in strict mode")
+ else sawUnary = true
+ expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression")
+ } else {
+ expr = this.parseExprSubscripts(refDestructuringErrors)
+ if (this.checkExpressionErrors(refDestructuringErrors)) return expr
+ while (this.type.postfix && !this.canInsertSemicolon()) {
+ var node$1 = this$1.startNodeAt(startPos, startLoc)
+ node$1.operator = this$1.value
+ node$1.prefix = false
+ node$1.argument = expr
+ this$1.checkLVal(expr)
+ this$1.next()
+ expr = this$1.finishNode(node$1, "UpdateExpression")
+ }
+ }
+
+ if (!sawUnary && this.eat(tt.starstar))
+ return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false)
+ else
+ return expr
+}
+
+// Parse call, dot, and `[]`-subscript expressions.
+
+pp$3.parseExprSubscripts = function(refDestructuringErrors) {
+ var startPos = this.start, startLoc = this.startLoc
+ var expr = this.parseExprAtom(refDestructuringErrors)
+ var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"
+ if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr
+ return this.parseSubscripts(expr, startPos, startLoc)
+}
+
+pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
+ var this$1 = this;
+
+ for (;;) {
+ if (this$1.eat(tt.dot)) {
+ var node = this$1.startNodeAt(startPos, startLoc)
+ node.object = base
+ node.property = this$1.parseIdent(true)
+ node.computed = false
+ base = this$1.finishNode(node, "MemberExpression")
+ } else if (this$1.eat(tt.bracketL)) {
+ var node$1 = this$1.startNodeAt(startPos, startLoc)
+ node$1.object = base
+ node$1.property = this$1.parseExpression()
+ node$1.computed = true
+ this$1.expect(tt.bracketR)
+ base = this$1.finishNode(node$1, "MemberExpression")
+ } else if (!noCalls && this$1.eat(tt.parenL)) {
+ var node$2 = this$1.startNodeAt(startPos, startLoc)
+ node$2.callee = base
+ node$2.arguments = this$1.parseExprList(tt.parenR, false)
+ base = this$1.finishNode(node$2, "CallExpression")
+ } else if (this$1.type === tt.backQuote) {
+ var node$3 = this$1.startNodeAt(startPos, startLoc)
+ node$3.tag = base
+ node$3.quasi = this$1.parseTemplate()
+ base = this$1.finishNode(node$3, "TaggedTemplateExpression")
+ } else {
+ return base
+ }
+ }
+}
+
+// Parse an atomic expression — either a single token that is an
+// expression, an expression started by a keyword like `function` or
+// `new`, or an expression wrapped in punctuation like `()`, `[]`,
+// or `{}`.
+
+pp$3.parseExprAtom = function(refDestructuringErrors) {
+ var node, canBeArrow = this.potentialArrowAt == this.start
+ switch (this.type) {
+ case tt._super:
+ if (!this.inFunction)
+ this.raise(this.start, "'super' outside of function or class")
+
+ case tt._this:
+ var type = this.type === tt._this ? "ThisExpression" : "Super"
+ node = this.startNode()
+ this.next()
+ return this.finishNode(node, type)
+
+ case tt.name:
+ var startPos = this.start, startLoc = this.startLoc
+ var id = this.parseIdent(this.type !== tt.name)
+ if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow))
+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id])
+ return id
+
+ case tt.regexp:
+ var value = this.value
+ node = this.parseLiteral(value.value)
+ node.regex = {pattern: value.pattern, flags: value.flags}
+ return node
+
+ case tt.num: case tt.string:
+ return this.parseLiteral(this.value)
+
+ case tt._null: case tt._true: case tt._false:
+ node = this.startNode()
+ node.value = this.type === tt._null ? null : this.type === tt._true
+ node.raw = this.type.keyword
+ this.next()
+ return this.finishNode(node, "Literal")
+
+ case tt.parenL:
+ return this.parseParenAndDistinguishExpression(canBeArrow)
+
+ case tt.bracketL:
+ node = this.startNode()
+ this.next()
+ node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors)
+ return this.finishNode(node, "ArrayExpression")
+
+ case tt.braceL:
+ return this.parseObj(false, refDestructuringErrors)
+
+ case tt._function:
+ node = this.startNode()
+ this.next()
+ return this.parseFunction(node, false)
+
+ case tt._class:
+ return this.parseClass(this.startNode(), false)
+
+ case tt._new:
+ return this.parseNew()
+
+ case tt.backQuote:
+ return this.parseTemplate()
+
+ default:
+ this.unexpected()
+ }
+}
+
+pp$3.parseLiteral = function(value) {
+ var node = this.startNode()
+ node.value = value
+ node.raw = this.input.slice(this.start, this.end)
+ this.next()
+ return this.finishNode(node, "Literal")
+}
+
+pp$3.parseParenExpression = function() {
+ this.expect(tt.parenL)
+ var val = this.parseExpression()
+ this.expect(tt.parenR)
+ return val
+}
+
+pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
+ var this$1 = this;
+
+ var startPos = this.start, startLoc = this.startLoc, val
+ if (this.options.ecmaVersion >= 6) {
+ this.next()
+
+ var innerStartPos = this.start, innerStartLoc = this.startLoc
+ var exprList = [], first = true
+ var refDestructuringErrors = new DestructuringErrors, spreadStart, innerParenStart
+ while (this.type !== tt.parenR) {
+ first ? first = false : this$1.expect(tt.comma)
+ if (this$1.type === tt.ellipsis) {
+ spreadStart = this$1.start
+ exprList.push(this$1.parseParenItem(this$1.parseRest()))
+ break
+ } else {
+ if (this$1.type === tt.parenL && !innerParenStart) {
+ innerParenStart = this$1.start
+ }
+ exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem))
+ }
+ }
+ var innerEndPos = this.start, innerEndLoc = this.startLoc
+ this.expect(tt.parenR)
+
+ if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
+ this.checkPatternErrors(refDestructuringErrors, true)
+ if (innerParenStart) this.unexpected(innerParenStart)
+ return this.parseParenArrowList(startPos, startLoc, exprList)
+ }
+
+ if (!exprList.length) this.unexpected(this.lastTokStart)
+ if (spreadStart) this.unexpected(spreadStart)
+ this.checkExpressionErrors(refDestructuringErrors, true)
+
+ if (exprList.length > 1) {
+ val = this.startNodeAt(innerStartPos, innerStartLoc)
+ val.expressions = exprList
+ this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc)
+ } else {
+ val = exprList[0]
+ }
+ } else {
+ val = this.parseParenExpression()
+ }
+
+ if (this.options.preserveParens) {
+ var par = this.startNodeAt(startPos, startLoc)
+ par.expression = val
+ return this.finishNode(par, "ParenthesizedExpression")
+ } else {
+ return val
+ }
+}
+
+pp$3.parseParenItem = function(item) {
+ return item
+}
+
+pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
+ return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
+}
+
+// New's precedence is slightly tricky. It must allow its argument to
+// be a `[]` or dot subscript expression, but not a call — at least,
+// not without wrapping it in parentheses. Thus, it uses the noCalls
+// argument to parseSubscripts to prevent it from consuming the
+// argument list.
+
+var empty$1 = []
+
+pp$3.parseNew = function() {
+ var node = this.startNode()
+ var meta = this.parseIdent(true)
+ if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
+ node.meta = meta
+ node.property = this.parseIdent(true)
+ if (node.property.name !== "target")
+ this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target")
+ if (!this.inFunction)
+ this.raiseRecoverable(node.start, "new.target can only be used in functions")
+ return this.finishNode(node, "MetaProperty")
+ }
+ var startPos = this.start, startLoc = this.startLoc
+ node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true)
+ if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false)
+ else node.arguments = empty$1
+ return this.finishNode(node, "NewExpression")
+}
+
+// Parse template expression.
+
+pp$3.parseTemplateElement = function() {
+ var elem = this.startNode()
+ elem.value = {
+ raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
+ cooked: this.value
+ }
+ this.next()
+ elem.tail = this.type === tt.backQuote
+ return this.finishNode(elem, "TemplateElement")
+}
+
+pp$3.parseTemplate = function() {
+ var this$1 = this;
+
+ var node = this.startNode()
+ this.next()
+ node.expressions = []
+ var curElt = this.parseTemplateElement()
+ node.quasis = [curElt]
+ while (!curElt.tail) {
+ this$1.expect(tt.dollarBraceL)
+ node.expressions.push(this$1.parseExpression())
+ this$1.expect(tt.braceR)
+ node.quasis.push(curElt = this$1.parseTemplateElement())
+ }
+ this.next()
+ return this.finishNode(node, "TemplateLiteral")
+}
+
+// Parse an object literal or binding pattern.
+
+pp$3.parseObj = function(isPattern, refDestructuringErrors) {
+ var this$1 = this;
+
+ var node = this.startNode(), first = true, propHash = {}
+ node.properties = []
+ this.next()
+ while (!this.eat(tt.braceR)) {
+ if (!first) {
+ this$1.expect(tt.comma)
+ if (this$1.afterTrailingComma(tt.braceR)) break
+ } else first = false
+
+ var prop = this$1.startNode(), isGenerator, startPos, startLoc
+ if (this$1.options.ecmaVersion >= 6) {
+ prop.method = false
+ prop.shorthand = false
+ if (isPattern || refDestructuringErrors) {
+ startPos = this$1.start
+ startLoc = this$1.startLoc
+ }
+ if (!isPattern)
+ isGenerator = this$1.eat(tt.star)
+ }
+ this$1.parsePropertyName(prop)
+ this$1.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors)
+ this$1.checkPropClash(prop, propHash)
+ node.properties.push(this$1.finishNode(prop, "Property"))
+ }
+ return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
+}
+
+pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) {
+ if (this.eat(tt.colon)) {
+ prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors)
+ prop.kind = "init"
+ } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
+ if (isPattern) this.unexpected()
+ prop.kind = "init"
+ prop.method = true
+ prop.value = this.parseMethod(isGenerator)
+ } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
+ (prop.key.name === "get" || prop.key.name === "set") &&
+ (this.type != tt.comma && this.type != tt.braceR)) {
+ if (isGenerator || isPattern) this.unexpected()
+ prop.kind = prop.key.name
+ this.parsePropertyName(prop)
+ prop.value = this.parseMethod(false)
+ var paramCount = prop.kind === "get" ? 0 : 1
+ if (prop.value.params.length !== paramCount) {
+ var start = prop.value.start
+ if (prop.kind === "get")
+ this.raiseRecoverable(start, "getter should have no params")
+ else
+ this.raiseRecoverable(start, "setter should have exactly one param")
+ }
+ if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
+ this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params")
+ } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
+ if (this.keywords.test(prop.key.name) ||
+ (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name) ||
+ (this.inGenerator && prop.key.name == "yield"))
+ this.raiseRecoverable(prop.key.start, "'" + prop.key.name + "' can not be used as shorthand property")
+ prop.kind = "init"
+ if (isPattern) {
+ prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
+ } else if (this.type === tt.eq && refDestructuringErrors) {
+ if (!refDestructuringErrors.shorthandAssign)
+ refDestructuringErrors.shorthandAssign = this.start
+ prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key)
+ } else {
+ prop.value = prop.key
+ }
+ prop.shorthand = true
+ } else this.unexpected()
+}
+
+pp$3.parsePropertyName = function(prop) {
+ if (this.options.ecmaVersion >= 6) {
+ if (this.eat(tt.bracketL)) {
+ prop.computed = true
+ prop.key = this.parseMaybeAssign()
+ this.expect(tt.bracketR)
+ return prop.key
+ } else {
+ prop.computed = false
+ }
+ }
+ return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true)
+}
+
+// Initialize empty function node.
+
+pp$3.initFunction = function(node) {
+ node.id = null
+ if (this.options.ecmaVersion >= 6) {
+ node.generator = false
+ node.expression = false
+ }
+}
+
+// Parse object or class method.
+
+pp$3.parseMethod = function(isGenerator) {
+ var node = this.startNode(), oldInGen = this.inGenerator
+ this.inGenerator = isGenerator
+ this.initFunction(node)
+ this.expect(tt.parenL)
+ node.params = this.parseBindingList(tt.parenR, false, false)
+ if (this.options.ecmaVersion >= 6)
+ node.generator = isGenerator
+ this.parseFunctionBody(node, false)
+ this.inGenerator = oldInGen
+ return this.finishNode(node, "FunctionExpression")
+}
+
+// Parse arrow function expression with given parameters.
+
+pp$3.parseArrowExpression = function(node, params) {
+ var oldInGen = this.inGenerator
+ this.inGenerator = false
+ this.initFunction(node)
+ node.params = this.toAssignableList(params, true)
+ this.parseFunctionBody(node, true)
+ this.inGenerator = oldInGen
+ return this.finishNode(node, "ArrowFunctionExpression")
+}
+
+// Parse function body and check parameters.
+
+pp$3.parseFunctionBody = function(node, isArrowFunction) {
+ var isExpression = isArrowFunction && this.type !== tt.braceL
+
+ if (isExpression) {
+ node.body = this.parseMaybeAssign()
+ node.expression = true
+ } else {
+ // Start a new scope with regard to labels and the `inFunction`
+ // flag (restore them to their old value afterwards).
+ var oldInFunc = this.inFunction, oldLabels = this.labels
+ this.inFunction = true; this.labels = []
+ node.body = this.parseBlock(true)
+ node.expression = false
+ this.inFunction = oldInFunc; this.labels = oldLabels
+ }
+
+ // If this is a strict mode function, verify that argument names
+ // are not repeated, and it does not try to bind the words `eval`
+ // or `arguments`.
+ var useStrict = (!isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) ? node.body.body[0] : null;
+ if (this.strict || useStrict) {
+ var oldStrict = this.strict
+ this.strict = true
+ if (node.id)
+ this.checkLVal(node.id, true)
+ this.checkParams(node, useStrict)
+ this.strict = oldStrict
+ } else if (isArrowFunction) {
+ this.checkParams(node, useStrict)
+ }
+}
+
+// Checks function params for various disallowed patterns such as using "eval"
+// or "arguments" and duplicate parameters.
+
+pp$3.checkParams = function(node, useStrict) {
+ var this$1 = this;
+
+ var nameHash = {}
+ for (var i = 0; i < node.params.length; i++) {
+ if (useStrict && this$1.options.ecmaVersion >= 7 && node.params[i].type !== "Identifier")
+ this$1.raiseRecoverable(useStrict.start, "Illegal 'use strict' directive in function with non-simple parameter list");
+ this$1.checkLVal(node.params[i], true, nameHash)
+ }
+}
+
+// Parses a comma-separated list of expressions, and returns them as
+// an array. `close` is the token type that ends the list, and
+// `allowEmpty` can be turned on to allow subsequent commas with
+// nothing in between them to be parsed as `null` (which is needed
+// for array literals).
+
+pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
+ var this$1 = this;
+
+ var elts = [], first = true
+ while (!this.eat(close)) {
+ if (!first) {
+ this$1.expect(tt.comma)
+ if (allowTrailingComma && this$1.afterTrailingComma(close)) break
+ } else first = false
+
+ var elt
+ if (allowEmpty && this$1.type === tt.comma)
+ elt = null
+ else if (this$1.type === tt.ellipsis) {
+ elt = this$1.parseSpread(refDestructuringErrors)
+ if (this$1.type === tt.comma && refDestructuringErrors && !refDestructuringErrors.trailingComma) {
+ refDestructuringErrors.trailingComma = this$1.lastTokStart
+ }
+ } else
+ elt = this$1.parseMaybeAssign(false, refDestructuringErrors)
+ elts.push(elt)
+ }
+ return elts
+}
+
+// Parse the next token as an identifier. If `liberal` is true (used
+// when parsing properties), it will also convert keywords into
+// identifiers.
+
+pp$3.parseIdent = function(liberal) {
+ var node = this.startNode()
+ if (liberal && this.options.allowReserved == "never") liberal = false
+ if (this.type === tt.name) {
+ if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) &&
+ (this.options.ecmaVersion >= 6 ||
+ this.input.slice(this.start, this.end).indexOf("\\") == -1))
+ this.raiseRecoverable(this.start, "The keyword '" + this.value + "' is reserved")
+ if (!liberal && this.inGenerator && this.value === "yield")
+ this.raiseRecoverable(this.start, "Can not use 'yield' as identifier inside a generator")
+ node.name = this.value
+ } else if (liberal && this.type.keyword) {
+ node.name = this.type.keyword
+ } else {
+ this.unexpected()
+ }
+ this.next()
+ return this.finishNode(node, "Identifier")
+}
+
+// Parses yield expression inside generator.
+
+pp$3.parseYield = function() {
+ var node = this.startNode()
+ this.next()
+ if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) {
+ node.delegate = false
+ node.argument = null
+ } else {
+ node.delegate = this.eat(tt.star)
+ node.argument = this.parseMaybeAssign()
+ }
+ return this.finishNode(node, "YieldExpression")
+}
+
+var pp$4 = Parser.prototype
+
+// This function is used to raise exceptions on parse errors. It
+// takes an offset integer (into the current `input`) to indicate
+// the location of the error, attaches the position to the end
+// of the error message, and then raises a `SyntaxError` with that
+// message.
+
+pp$4.raise = function(pos, message) {
+ var loc = getLineInfo(this.input, pos)
+ message += " (" + loc.line + ":" + loc.column + ")"
+ var err = new SyntaxError(message)
+ err.pos = pos; err.loc = loc; err.raisedAt = this.pos
+ throw err
+}
+
+pp$4.raiseRecoverable = pp$4.raise
+
+pp$4.curPosition = function() {
+ if (this.options.locations) {
+ return new Position(this.curLine, this.pos - this.lineStart)
+ }
+}
+
+var Node = function Node(parser, pos, loc) {
+ this.type = ""
+ this.start = pos
+ this.end = 0
+ if (parser.options.locations)
+ this.loc = new SourceLocation(parser, loc)
+ if (parser.options.directSourceFile)
+ this.sourceFile = parser.options.directSourceFile
+ if (parser.options.ranges)
+ this.range = [pos, 0]
+};
+
+// Start an AST node, attaching a start offset.
+
+var pp$5 = Parser.prototype
+
+pp$5.startNode = function() {
+ return new Node(this, this.start, this.startLoc)
+}
+
+pp$5.startNodeAt = function(pos, loc) {
+ return new Node(this, pos, loc)
+}
+
+// Finish an AST node, adding `type` and `end` properties.
+
+function finishNodeAt(node, type, pos, loc) {
+ node.type = type
+ node.end = pos
+ if (this.options.locations)
+ node.loc.end = loc
+ if (this.options.ranges)
+ node.range[1] = pos
+ return node
+}
+
+pp$5.finishNode = function(node, type) {
+ return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
+}
+
+// Finish node at given position
+
+pp$5.finishNodeAt = function(node, type, pos, loc) {
+ return finishNodeAt.call(this, node, type, pos, loc)
+}
+
+var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
+ this.token = token
+ this.isExpr = !!isExpr
+ this.preserveSpace = !!preserveSpace
+ this.override = override
+};
+
+var types = {
+ b_stat: new TokContext("{", false),
+ b_expr: new TokContext("{", true),
+ b_tmpl: new TokContext("${", true),
+ p_stat: new TokContext("(", false),
+ p_expr: new TokContext("(", true),
+ q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }),
+ f_expr: new TokContext("function", true)
+}
+
+var pp$6 = Parser.prototype
+
+pp$6.initialContext = function() {
+ return [types.b_stat]
+}
+
+pp$6.braceIsBlock = function(prevType) {
+ if (prevType === tt.colon) {
+ var parent = this.curContext()
+ if (parent === types.b_stat || parent === types.b_expr)
+ return !parent.isExpr
+ }
+ if (prevType === tt._return)
+ return lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
+ if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR)
+ return true
+ if (prevType == tt.braceL)
+ return this.curContext() === types.b_stat
+ return !this.exprAllowed
+}
+
+pp$6.updateContext = function(prevType) {
+ var update, type = this.type
+ if (type.keyword && prevType == tt.dot)
+ this.exprAllowed = false
+ else if (update = type.updateContext)
+ update.call(this, prevType)
+ else
+ this.exprAllowed = type.beforeExpr
+}
+
+// Token-specific context update code
+
+tt.parenR.updateContext = tt.braceR.updateContext = function() {
+ if (this.context.length == 1) {
+ this.exprAllowed = true
+ return
+ }
+ var out = this.context.pop()
+ if (out === types.b_stat && this.curContext() === types.f_expr) {
+ this.context.pop()
+ this.exprAllowed = false
+ } else if (out === types.b_tmpl) {
+ this.exprAllowed = true
+ } else {
+ this.exprAllowed = !out.isExpr
+ }
+}
+
+tt.braceL.updateContext = function(prevType) {
+ this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr)
+ this.exprAllowed = true
+}
+
+tt.dollarBraceL.updateContext = function() {
+ this.context.push(types.b_tmpl)
+ this.exprAllowed = true
+}
+
+tt.parenL.updateContext = function(prevType) {
+ var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while
+ this.context.push(statementParens ? types.p_stat : types.p_expr)
+ this.exprAllowed = true
+}
+
+tt.incDec.updateContext = function() {
+ // tokExprAllowed stays unchanged
+}
+
+tt._function.updateContext = function(prevType) {
+ if (prevType.beforeExpr && prevType !== tt.semi && prevType !== tt._else &&
+ !((prevType === tt.colon || prevType === tt.braceL) && this.curContext() === types.b_stat))
+ this.context.push(types.f_expr)
+ this.exprAllowed = false
+}
+
+tt.backQuote.updateContext = function() {
+ if (this.curContext() === types.q_tmpl)
+ this.context.pop()
+ else
+ this.context.push(types.q_tmpl)
+ this.exprAllowed = false
+}
+
+// Object type used to represent tokens. Note that normally, tokens
+// simply exist as properties on the parser object. This is only
+// used for the onToken callback and the external tokenizer.
+
+var Token = function Token(p) {
+ this.type = p.type
+ this.value = p.value
+ this.start = p.start
+ this.end = p.end
+ if (p.options.locations)
+ this.loc = new SourceLocation(p, p.startLoc, p.endLoc)
+ if (p.options.ranges)
+ this.range = [p.start, p.end]
+};
+
+// ## Tokenizer
+
+var pp$7 = Parser.prototype
+
+// Are we running under Rhino?
+var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"
+
+// Move to the next token
+
+pp$7.next = function() {
+ if (this.options.onToken)
+ this.options.onToken(new Token(this))
+
+ this.lastTokEnd = this.end
+ this.lastTokStart = this.start
+ this.lastTokEndLoc = this.endLoc
+ this.lastTokStartLoc = this.startLoc
+ this.nextToken()
+}
+
+pp$7.getToken = function() {
+ this.next()
+ return new Token(this)
+}
+
+// If we're in an ES6 environment, make parsers iterable
+if (typeof Symbol !== "undefined")
+ pp$7[Symbol.iterator] = function () {
+ var self = this
+ return {next: function () {
+ var token = self.getToken()
+ return {
+ done: token.type === tt.eof,
+ value: token
+ }
+ }}
+ }
+
+// Toggle strict mode. Re-reads the next number or string to please
+// pedantic tests (`"use strict"; 010;` should fail).
+
+pp$7.setStrict = function(strict) {
+ var this$1 = this;
+
+ this.strict = strict
+ if (this.type !== tt.num && this.type !== tt.string) return
+ this.pos = this.start
+ if (this.options.locations) {
+ while (this.pos < this.lineStart) {
+ this$1.lineStart = this$1.input.lastIndexOf("\n", this$1.lineStart - 2) + 1
+ --this$1.curLine
+ }
+ }
+ this.nextToken()
+}
+
+pp$7.curContext = function() {
+ return this.context[this.context.length - 1]
+}
+
+// Read a single token, updating the parser object's token-related
+// properties.
+
+pp$7.nextToken = function() {
+ var curContext = this.curContext()
+ if (!curContext || !curContext.preserveSpace) this.skipSpace()
+
+ this.start = this.pos
+ if (this.options.locations) this.startLoc = this.curPosition()
+ if (this.pos >= this.input.length) return this.finishToken(tt.eof)
+
+ if (curContext.override) return curContext.override(this)
+ else this.readToken(this.fullCharCodeAtPos())
+}
+
+pp$7.readToken = function(code) {
+ // Identifier or keyword. '\uXXXX' sequences are allowed in
+ // identifiers, so '\' also dispatches to that.
+ if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
+ return this.readWord()
+
+ return this.getTokenFromCode(code)
+}
+
+pp$7.fullCharCodeAtPos = function() {
+ var code = this.input.charCodeAt(this.pos)
+ if (code <= 0xd7ff || code >= 0xe000) return code
+ var next = this.input.charCodeAt(this.pos + 1)
+ return (code << 10) + next - 0x35fdc00
+}
+
+pp$7.skipBlockComment = function() {
+ var this$1 = this;
+
+ var startLoc = this.options.onComment && this.curPosition()
+ var start = this.pos, end = this.input.indexOf("*/", this.pos += 2)
+ if (end === -1) this.raise(this.pos - 2, "Unterminated comment")
+ this.pos = end + 2
+ if (this.options.locations) {
+ lineBreakG.lastIndex = start
+ var match
+ while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
+ ++this$1.curLine
+ this$1.lineStart = match.index + match[0].length
+ }
+ }
+ if (this.options.onComment)
+ this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
+ startLoc, this.curPosition())
+}
+
+pp$7.skipLineComment = function(startSkip) {
+ var this$1 = this;
+
+ var start = this.pos
+ var startLoc = this.options.onComment && this.curPosition()
+ var ch = this.input.charCodeAt(this.pos+=startSkip)
+ while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
+ ++this$1.pos
+ ch = this$1.input.charCodeAt(this$1.pos)
+ }
+ if (this.options.onComment)
+ this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
+ startLoc, this.curPosition())
+}
+
+// Called at the start of the parse and after every token. Skips
+// whitespace and comments, and.
+
+pp$7.skipSpace = function() {
+ var this$1 = this;
+
+ loop: while (this.pos < this.input.length) {
+ var ch = this$1.input.charCodeAt(this$1.pos)
+ switch (ch) {
+ case 32: case 160: // ' '
+ ++this$1.pos
+ break
+ case 13:
+ if (this$1.input.charCodeAt(this$1.pos + 1) === 10) {
+ ++this$1.pos
+ }
+ case 10: case 8232: case 8233:
+ ++this$1.pos
+ if (this$1.options.locations) {
+ ++this$1.curLine
+ this$1.lineStart = this$1.pos
+ }
+ break
+ case 47: // '/'
+ switch (this$1.input.charCodeAt(this$1.pos + 1)) {
+ case 42: // '*'
+ this$1.skipBlockComment()
+ break
+ case 47:
+ this$1.skipLineComment(2)
+ break
+ default:
+ break loop
+ }
+ break
+ default:
+ if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
+ ++this$1.pos
+ } else {
+ break loop
+ }
+ }
+ }
+}
+
+// Called at the end of every token. Sets `end`, `val`, and
+// maintains `context` and `exprAllowed`, and skips the space after
+// the token, so that the next one's `start` will point at the
+// right position.
+
+pp$7.finishToken = function(type, val) {
+ this.end = this.pos
+ if (this.options.locations) this.endLoc = this.curPosition()
+ var prevType = this.type
+ this.type = type
+ this.value = val
+
+ this.updateContext(prevType)
+}
+
+// ### Token reading
+
+// This is the function that is called to fetch the next token. It
+// is somewhat obscure, because it works in character codes rather
+// than characters, and because operator parsing has been inlined
+// into it.
+//
+// All in the name of speed.
+//
+pp$7.readToken_dot = function() {
+ var next = this.input.charCodeAt(this.pos + 1)
+ if (next >= 48 && next <= 57) return this.readNumber(true)
+ var next2 = this.input.charCodeAt(this.pos + 2)
+ if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
+ this.pos += 3
+ return this.finishToken(tt.ellipsis)
+ } else {
+ ++this.pos
+ return this.finishToken(tt.dot)
+ }
+}
+
+pp$7.readToken_slash = function() { // '/'
+ var next = this.input.charCodeAt(this.pos + 1)
+ if (this.exprAllowed) {++this.pos; return this.readRegexp()}
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(tt.slash, 1)
+}
+
+pp$7.readToken_mult_modulo_exp = function(code) { // '%*'
+ var next = this.input.charCodeAt(this.pos + 1)
+ var size = 1
+ var tokentype = code === 42 ? tt.star : tt.modulo
+
+ // exponentiation operator ** and **=
+ if (this.options.ecmaVersion >= 7 && next === 42) {
+ ++size
+ tokentype = tt.starstar
+ next = this.input.charCodeAt(this.pos + 2)
+ }
+
+ if (next === 61) return this.finishOp(tt.assign, size + 1)
+ return this.finishOp(tokentype, size)
+}
+
+pp$7.readToken_pipe_amp = function(code) { // '|&'
+ var next = this.input.charCodeAt(this.pos + 1)
+ if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2)
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1)
+}
+
+pp$7.readToken_caret = function() { // '^'
+ var next = this.input.charCodeAt(this.pos + 1)
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(tt.bitwiseXOR, 1)
+}
+
+pp$7.readToken_plus_min = function(code) { // '+-'
+ var next = this.input.charCodeAt(this.pos + 1)
+ if (next === code) {
+ if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 &&
+ lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
+ // A `-->` line comment
+ this.skipLineComment(3)
+ this.skipSpace()
+ return this.nextToken()
+ }
+ return this.finishOp(tt.incDec, 2)
+ }
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(tt.plusMin, 1)
+}
+
+pp$7.readToken_lt_gt = function(code) { // '<>'
+ var next = this.input.charCodeAt(this.pos + 1)
+ var size = 1
+ if (next === code) {
+ size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
+ if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
+ return this.finishOp(tt.bitShift, size)
+ }
+ if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
+ this.input.charCodeAt(this.pos + 3) == 45) {
+ if (this.inModule) this.unexpected()
+ // `` line comment
+ this.skipLineComment(3)
+ this.skipSpace()
+ return this.nextToken()
+ }
+ return this.finishOp(tt.incDec, 2)
+ }
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(tt.plusMin, 1)
+ }
+
+ pp$7.readToken_lt_gt = function(code) { // '<>'
+ var next = this.input.charCodeAt(this.pos + 1)
+ var size = 1
+ if (next === code) {
+ size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
+ if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
+ return this.finishOp(tt.bitShift, size)
+ }
+ if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
+ this.input.charCodeAt(this.pos + 3) == 45) {
+ if (this.inModule) this.unexpected()
+ // `` line comment
+ this.skipLineComment(3)
+ this.skipSpace()
+ return this.nextToken()
+ }
+ return this.finishOp(tt.incDec, 2)
+ }
+ if (next === 61) return this.finishOp(tt.assign, 2)
+ return this.finishOp(tt.plusMin, 1)
+}
+
+pp.readToken_lt_gt = function(code) { // '<>'
+ let next = this.input.charCodeAt(this.pos + 1)
+ let size = 1
+ if (next === code) {
+ size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2
+ if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1)
+ return this.finishOp(tt.bitShift, size)
+ }
+ if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 &&
+ this.input.charCodeAt(this.pos + 3) == 45) {
+ if (this.inModule) this.unexpected()
+ // `
+
+Both [Writable][] and [Readable][] streams will store data in an internal
+buffer that can be retrieved using `writable._writableState.getBuffer()` or
+`readable._readableState.buffer`, respectively.
+
+The amount of data potentially buffered depends on the `highWaterMark` option
+passed into the streams constructor. For normal streams, the `highWaterMark`
+option specifies a total number of bytes. For streams operating in object mode,
+the `highWaterMark` specifies a total number of objects.
+
+Data is buffered in Readable streams when the implementation calls
+[`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not
+call [`stream.read()`][stream-read], the data will sit in the internal
+queue until it is consumed.
+
+Once the total size of the internal read buffer reaches the threshold specified
+by `highWaterMark`, the stream will temporarily stop reading data from the
+underlying resource until the data currently buffered can be consumed (that is,
+the stream will stop calling the internal `readable._read()` method that is
+used to fill the read buffer).
+
+Data is buffered in Writable streams when the
+[`writable.write(chunk)`][stream-write] method is called repeatedly. While the
+total size of the internal write buffer is below the threshold set by
+`highWaterMark`, calls to `writable.write()` will return `true`. Once the
+the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
+will be returned.
+
+A key goal of the `stream` API, and in particular the [`stream.pipe()`] method,
+is to limit the buffering of data to acceptable levels such that sources and
+destinations of differing speeds will not overwhelm the available memory.
+
+Because [Duplex][] and [Transform][] streams are both Readable and Writable,
+each maintain *two* separate internal buffers used for reading and writing,
+allowing each side to operate independently of the other while maintaining an
+appropriate and efficient flow of data. For example, [`net.Socket`][] instances
+are [Duplex][] streams whose Readable side allows consumption of data received
+*from* the socket and whose Writable side allows writing data *to* the socket.
+Because data may be written to the socket at a faster or slower rate than data
+is received, it is important each side operate (and buffer) independently of
+the other.
+
+## API for Stream Consumers
+
+
+
+Almost all Node.js applications, no matter how simple, use streams in some
+manner. The following is an example of using streams in a Node.js application
+that implements an HTTP server:
+
+```js
+const http = require('http');
+
+const server = http.createServer( (req, res) => {
+ // req is an http.IncomingMessage, which is a Readable Stream
+ // res is an http.ServerResponse, which is a Writable Stream
+
+ let body = '';
+ // Get the data as utf8 strings.
+ // If an encoding is not set, Buffer objects will be received.
+ req.setEncoding('utf8');
+
+ // Readable streams emit 'data' events once a listener is added
+ req.on('data', (chunk) => {
+ body += chunk;
+ });
+
+ // the end event indicates that the entire body has been received
+ req.on('end', () => {
+ try {
+ const data = JSON.parse(body);
+ } catch (er) {
+ // uh oh! bad json!
+ res.statusCode = 400;
+ return res.end(`error: ${er.message}`);
+ }
+
+ // write back something interesting to the user:
+ res.write(typeof data);
+ res.end();
+ });
+});
+
+server.listen(1337);
+
+// $ curl localhost:1337 -d '{}'
+// object
+// $ curl localhost:1337 -d '"foo"'
+// string
+// $ curl localhost:1337 -d 'not json'
+// error: Unexpected token o
+```
+
+[Writable][] streams (such as `res` in the example) expose methods such as
+`write()` and `end()` that are used to write data onto the stream.
+
+[Readable][] streams use the [`EventEmitter`][] API for notifying application
+code when data is available to be read off the stream. That available data can
+be read from the stream in multiple ways.
+
+Both [Writable][] and [Readable][] streams use the [`EventEmitter`][] API in
+various ways to communicate the current state of the stream.
+
+[Duplex][] and [Transform][] streams are both [Writable][] and [Readable][].
+
+Applications that are either writing data to or consuming data from a stream
+are not required to implement the stream interfaces directly and will generally
+have no reason to call `require('stream')`.
+
+Developers wishing to implement new types of streams should refer to the
+section [API for Stream Implementers][].
+
+### Writable Streams
+
+Writable streams are an abstraction for a *destination* to which data is
+written.
+
+Examples of [Writable][] streams include:
+
+* [HTTP requests, on the client][]
+* [HTTP responses, on the server][]
+* [fs write streams][]
+* [zlib streams][zlib]
+* [crypto streams][crypto]
+* [TCP sockets][]
+* [child process stdin][]
+* [`process.stdout`][], [`process.stderr`][]
+
+*Note*: Some of these examples are actually [Duplex][] streams that implement
+the [Writable][] interface.
+
+All [Writable][] streams implement the interface defined by the
+`stream.Writable` class.
+
+While specific instances of [Writable][] streams may differ in various ways,
+all Writable streams follow the same fundamental usage pattern as illustrated
+in the example below:
+
+```js
+const myStream = getWritableStreamSomehow();
+myStream.write('some data');
+myStream.write('some more data');
+myStream.end('done writing data');
+```
+
+#### Class: stream.Writable
+
+
+
+
+##### Event: 'close'
+
+
+The `'close'` event is emitted when the stream and any of its underlying
+resources (a file descriptor, for example) have been closed. The event indicates
+that no more events will be emitted, and no further computation will occur.
+
+Not all Writable streams will emit the `'close'` event.
+
+##### Event: 'drain'
+
+
+If a call to [`stream.write(chunk)`][stream-write] returns `false`, the
+`'drain'` event will be emitted when it is appropriate to resume writing data
+to the stream.
+
+```js
+// Write the data to the supplied writable stream one million times.
+// Be attentive to back-pressure.
+function writeOneMillionTimes(writer, data, encoding, callback) {
+ let i = 1000000;
+ write();
+ function write() {
+ var ok = true;
+ do {
+ i--;
+ if (i === 0) {
+ // last time!
+ writer.write(data, encoding, callback);
+ } else {
+ // see if we should continue, or wait
+ // don't pass the callback, because we're not done yet.
+ ok = writer.write(data, encoding);
+ }
+ } while (i > 0 && ok);
+ if (i > 0) {
+ // had to stop early!
+ // write some more once it drains
+ writer.once('drain', write);
+ }
+ }
+}
+```
+
+##### Event: 'error'
+
+
+* {Error}
+
+The `'error'` event is emitted if an error occurred while writing or piping
+data. The listener callback is passed a single `Error` argument when called.
+
+*Note*: The stream is not closed when the `'error'` event is emitted.
+
+##### Event: 'finish'
+
+
+The `'finish'` event is emitted after the [`stream.end()`][stream-end] method
+has been called, and all data has been flushed to the underlying system.
+
+```js
+const writer = getWritableStreamSomehow();
+for (var i = 0; i < 100; i ++) {
+ writer.write('hello, #${i}!\n');
+}
+writer.end('This is the end\n');
+writer.on('finish', () => {
+ console.error('All writes are now complete.');
+});
+```
+
+##### Event: 'pipe'
+
+
+* `src` {stream.Readable} source stream that is piping to this writable
+
+The `'pipe'` event is emitted when the [`stream.pipe()`][] method is called on
+a readable stream, adding this writable to its set of destinations.
+
+```js
+const writer = getWritableStreamSomehow();
+const reader = getReadableStreamSomehow();
+writer.on('pipe', (src) => {
+ console.error('something is piping into the writer');
+ assert.equal(src, reader);
+});
+reader.pipe(writer);
+```
+
+##### Event: 'unpipe'
+
+
+* `src` {[Readable][] Stream} The source stream that
+ [unpiped][`stream.unpipe()`] this writable
+
+The `'unpipe'` event is emitted when the [`stream.unpipe()`][] method is called
+on a [Readable][] stream, removing this [Writable][] from its set of
+destinations.
+
+```js
+const writer = getWritableStreamSomehow();
+const reader = getReadableStreamSomehow();
+writer.on('unpipe', (src) => {
+ console.error('Something has stopped piping into the writer.');
+ assert.equal(src, reader);
+});
+reader.pipe(writer);
+reader.unpipe(writer);
+```
+
+##### writable.cork()
+
+
+The `writable.cork()` method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the [`stream.uncork()`][] or
+[`stream.end()`][stream-end] methods are called.
+
+The primary intent of `writable.cork()` is to avoid a situation where writing
+many small chunks of data to a stream do not cause an backup in the internal
+buffer that would have an adverse impact on performance. In such situations,
+implementations that implement the `writable._writev()` method can perform
+buffered writes in a more optimized manner.
+
+##### writable.end([chunk][, encoding][, callback])
+
+
+* `chunk` {String|Buffer|any} Optional data to write. For streams not operating
+ in object mode, `chunk` must be a string or a `Buffer`. For object mode
+ streams, `chunk` may be any JavaScript value other than `null`.
+* `encoding` {String} The encoding, if `chunk` is a String
+* `callback` {Function} Optional callback for when the stream is finished
+
+Calling the `writable.end()` method signals that no more data will be written
+to the [Writable][]. The optional `chunk` and `encoding` arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream. If provided, the optional `callback` function is attached as a listener
+for the [`'finish'`][] event.
+
+Calling the [`stream.write()`][stream-write] method after calling
+[`stream.end()`][stream-end] will raise an error.
+
+```js
+// write 'hello, ' and then end with 'world!'
+const file = fs.createWriteStream('example.txt');
+file.write('hello, ');
+file.end('world!');
+// writing more now is not allowed!
+```
+
+##### writable.setDefaultEncoding(encoding)
+
+
+* `encoding` {String} The new default encoding
+* Return: `this`
+
+The `writable.setDefaultEncoding()` method sets the default `encoding` for a
+[Writable][] stream.
+
+##### writable.uncork()
+
+
+The `writable.uncork()` method flushes all data buffered since
+[`stream.cork()`][] was called.
+
+When using `writable.cork()` and `writable.uncork()` to manage the buffering
+of writes to a stream, it is recommended that calls to `writable.uncork()` be
+deferred using `process.nextTick()`. Doing so allows batching of all
+`writable.write()` calls that occur within a given Node.js event loop phase.
+
+```js
+stream.cork();
+stream.write('some ');
+stream.write('data ');
+process.nextTick(() => stream.uncork());
+```
+
+If the `writable.cork()` method is called multiple times on a stream, the same
+number of calls to `writable.uncork()` must be called to flush the buffered
+data.
+
+```
+stream.cork();
+stream.write('some ');
+stream.cork();
+stream.write('data ');
+process.nextTick(() => {
+ stream.uncork();
+ // The data will not be flushed until uncork() is called a second time.
+ stream.uncork();
+});
+```
+
+##### writable.write(chunk[, encoding][, callback])
+
+
+* `chunk` {String|Buffer} The data to write
+* `encoding` {String} The encoding, if `chunk` is a String
+* `callback` {Function} Callback for when this chunk of data is flushed
+* Returns: {Boolean} `false` if the stream wishes for the calling code to
+ wait for the `'drain'` event to be emitted before continuing to write
+ additional data; otherwise `true`.
+
+The `writable.write()` method writes some data to the stream, and calls the
+supplied `callback` once the data has been fully handled. If an error
+occurs, the `callback` *may or may not* be called with the error as its
+first argument. To reliably detect write errors, add a listener for the
+`'error'` event.
+
+The return value indicates whether the written `chunk` was buffered internally
+and the buffer has exceeded the `highWaterMark` configured when the stream was
+created. If `false` is returned, further attempts to write data to the stream
+should be paused until the `'drain'` event is emitted.
+
+A Writable stream in object mode will always ignore the `encoding` argument.
+
+### Readable Streams
+
+Readable streams are an abstraction for a *source* from which data is
+consumed.
+
+Examples of Readable streams include:
+
+* [HTTP responses, on the client][http-incoming-message]
+* [HTTP requests, on the server][http-incoming-message]
+* [fs read streams][]
+* [zlib streams][zlib]
+* [crypto streams][crypto]
+* [TCP sockets][]
+* [child process stdout and stderr][]
+* [`process.stdin`][]
+
+All [Readable][] streams implement the interface defined by the
+`stream.Readable` class.
+
+#### Two Modes
+
+Readable streams effectively operate in one of two modes: flowing and paused.
+
+When in flowing mode, data is read from the underlying system automatically
+and provided to an application as quickly as possible using events via the
+[`EventEmitter`][] interface.
+
+In paused mode, the [`stream.read()`][stream-read] method must be called
+explicitly to read chunks of data from the stream.
+
+All [Readable][] streams begin in paused mode but can be switched to flowing
+mode in one of the following ways:
+
+* Adding a [`'data'`][] event handler.
+* Calling the [`stream.resume()`][stream-resume] method.
+* Calling the [`stream.pipe()`][] method to send the data to a [Writable][].
+
+The Readable can switch back to paused mode using one of the following:
+
+* If there are no pipe destinations, by calling the
+ [`stream.pause()`][stream-pause] method.
+* If there are pipe destinations, by removing any [`'data'`][] event
+ handlers, and removing all pipe destinations by calling the
+ [`stream.unpipe()`][] method.
+
+The important concept to remember is that a Readable will not generate data
+until a mechanism for either consuming or ignoring that data is provided. If
+the consuming mechanism is disabled or taken away, the Readable will *attempt*
+to stop generating the data.
+
+*Note*: For backwards compatibility reasons, removing [`'data'`][] event
+handlers will **not** automatically pause the stream. Also, if there are piped
+destinations, then calling [`stream.pause()`][stream-pause] will not guarantee
+that the stream will *remain* paused once those destinations drain and ask for
+more data.
+
+*Note*: If a [Readable][] is switched into flowing mode and there are no
+consumers available handle the data, that data will be lost. This can occur,
+for instance, when the `readable.resume()` method is called without a listener
+attached to the `'data'` event, or when a `'data'` event handler is removed
+from the stream.
+
+#### Three States
+
+The "two modes" of operation for a Readable stream are a simplified abstraction
+for the more complicated internal state management that is happening within the
+Readable stream implementation.
+
+Specifically, at any given point in time, every Readable is in one of three
+possible states:
+
+* `readable._readableState.flowing = null`
+* `readable._readableState.flowing = false`
+* `readable._readableState.flowing = true`
+
+When `readable._readableState.flowing` is `null`, no mechanism for consuming the
+streams data is provided so the stream will not generate its data.
+
+Attaching a listener for the `'data'` event, calling the `readable.pipe()`
+method, or calling the `readable.resume()` method will switch
+`readable._readableState.flowing` to `true`, causing the Readable to begin
+actively emitting events as data is generated.
+
+Calling `readable.pause()`, `readable.unpipe()`, or receiving "back pressure"
+will cause the `readable._readableState.flowing` to be set as `false`,
+temporarily halting the flowing of events but *not* halting the generation of
+data.
+
+While `readable._readableState.flowing` is `false`, data may be accumulating
+within the streams internal buffer.
+
+#### Choose One
+
+The Readable stream API evolved across multiple Node.js versions and provides
+multiple methods of consuming stream data. In general, developers should choose
+*one* of the methods of consuming data and *should never* use multiple methods
+to consume data from a single stream.
+
+Use of the `readable.pipe()` method is recommended for most users as it has been
+implemented to provide the easiest way of consuming stream data. Developers that
+require more fine-grained control over the transfer and generation of data can
+use the [`EventEmitter`][] and `readable.pause()`/`readable.resume()` APIs.
+
+#### Class: stream.Readable
+
+
+
+
+##### Event: 'close'
+
+
+The `'close'` event is emitted when the stream and any of its underlying
+resources (a file descriptor, for example) have been closed. The event indicates
+that no more events will be emitted, and no further computation will occur.
+
+Not all [Readable][] streams will emit the `'close'` event.
+
+##### Event: 'data'
+
+
+* `chunk` {Buffer|String|any} The chunk of data. For streams that are not
+ operating in object mode, the chunk will be either a string or `Buffer`.
+ For streams that are in object mode, the chunk can be any JavaScript value
+ other than `null`.
+
+The `'data'` event is emitted whenever the stream is relinquishing ownership of
+a chunk of data to a consumer. This may occur whenever the stream is switched
+in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
+attaching a listener callback to the `'data'` event. The `'data'` event will
+also be emitted whenever the `readable.read()` method is called and a chunk of
+data is available to be returned.
+
+Attaching a `'data'` event listener to a stream that has not been explicitly
+paused will switch the stream into flowing mode. Data will then be passed as
+soon as it is available.
+
+The listener callback will be passed the chunk of data as a string if a default
+encoding has been specified for the stream using the
+`readable.setEncoding()` method; otherwise the data will be passed as a
+`Buffer`.
+
+```js
+const readable = getReadableStreamSomehow();
+readable.on('data', (chunk) => {
+ console.log(`Received ${chunk.length} bytes of data.`);
+});
+```
+
+##### Event: 'end'
+
+
+The `'end'` event is emitted when there is no more data to be consumed from
+the stream.
+
+*Note*: The `'end'` event **will not be emitted** unless the data is
+completely consumed. This can be accomplished by switching the stream into
+flowing mode, or by calling [`stream.read()`][stream-read] repeatedly until
+all data has been consumed.
+
+```js
+const readable = getReadableStreamSomehow();
+readable.on('data', (chunk) => {
+ console.log(`Received ${chunk.length} bytes of data.`);
+});
+readable.on('end', () => {
+ console.log('There will be no more data.');
+});
+```
+
+##### Event: 'error'
+
+
+* {Error}
+
+The `'error'` event may be emitted by a Readable implementation at any time.
+Typically, this may occur if the underlying stream in unable to generate data
+due to an underlying internal failure, or when a stream implementation attempts
+to push an invalid chunk of data.
+
+The listener callback will be passed a single `Error` object.
+
+##### Event: 'readable'
+
+
+The `'readable'` event is emitted when there is data available to be read from
+the stream. In some cases, attaching a listener for the `'readable'` event will
+cause some amount of data to be read into an internal buffer.
+
+```javascript
+const readable = getReadableStreamSomehow();
+readable.on('readable', () => {
+ // there is some data to read now
+});
+```
+The `'readable'` event will also be emitted once the end of the stream data
+has been reached but before the `'end'` event is emitted.
+
+Effectively, the `'readable'` event indicates that the stream has new
+information: either new data is available or the end of the stream has been
+reached. In the former case, [`stream.read()`][stream-read] will return the
+available data. In the latter case, [`stream.read()`][stream-read] will return
+`null`. For instance, in the following example, `foo.txt` is an empty file:
+
+```js
+const fs = require('fs');
+const rr = fs.createReadStream('foo.txt');
+rr.on('readable', () => {
+ console.log('readable:', rr.read());
+});
+rr.on('end', () => {
+ console.log('end');
+});
+```
+
+The output of running this script is:
+
+```
+$ node test.js
+readable: null
+end
+```
+
+*Note*: In general, the `readable.pipe()` and `'data'` event mechanisms are
+preferred over the use of the `'readable'` event.
+
+##### readable.isPaused()
+
+
+* Return: {Boolean}
+
+The `readable.isPaused()` method returns the current operating state of the
+Readable. This is used primarily by the mechanism that underlies the
+`readable.pipe()` method. In most typical cases, there will be no reason to
+use this method directly.
+
+```js
+const readable = new stream.Readable
+
+readable.isPaused() // === false
+readable.pause()
+readable.isPaused() // === true
+readable.resume()
+readable.isPaused() // === false
+```
+
+##### readable.pause()
+
+
+* Return: `this`
+
+The `readable.pause()` method will cause a stream in flowing mode to stop
+emitting [`'data'`][] events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
+
+```js
+const readable = getReadableStreamSomehow();
+readable.on('data', (chunk) => {
+ console.log(`Received ${chunk.length} bytes of data.`);
+ readable.pause();
+ console.log('There will be no additional data for 1 second.');
+ setTimeout(() => {
+ console.log('Now data will start flowing again.');
+ readable.resume();
+ }, 1000);
+});
+```
+
+##### readable.pipe(destination[, options])
+
+
+* `destination` {stream.Writable} The destination for writing data
+* `options` {Object} Pipe options
+ * `end` {Boolean} End the writer when the reader ends. Defaults to `true`.
+
+The `readable.pipe()` method attaches a [Writable][] stream to the `readable`,
+causing it to switch automatically into flowing mode and push all of its data
+to the attached [Writable][]. The flow of data will be automatically managed so
+that the destination Writable stream is not overwhelmed by a faster Readable
+stream.
+
+The following example pipes all of the data from the `readable` into a file
+named `file.txt`:
+
+```js
+const readable = getReadableStreamSomehow();
+const writable = fs.createWriteStream('file.txt');
+// All the data from readable goes into 'file.txt'
+readable.pipe(writable);
+```
+It is possible to attach multiple Writable streams to a single Readable stream.
+
+The `readable.pipe()` method returns a reference to the *destination* stream
+making it possible to set up chains of piped streams:
+
+```js
+const r = fs.createReadStream('file.txt');
+const z = zlib.createGzip();
+const w = fs.createWriteStream('file.txt.gz');
+r.pipe(z).pipe(w);
+```
+
+By default, [`stream.end()`][stream-end] is called on the destination Writable
+stream when the source Readable stream emits [`'end'`][], so that the
+destination is no longer writable. To disable this default behavior, the `end`
+option can be passed as `false`, causing the destination stream to remain open,
+as illustrated in the following example:
+
+```js
+reader.pipe(writer, { end: false });
+reader.on('end', () => {
+ writer.end('Goodbye\n');
+});
+```
+
+One important caveat is that if the Readable stream emits an error during
+processing, the Writable destination *is not closed* automatically. If an
+error occurs, it will be necessary to *manually* close each stream in order
+to prevent memory leaks.
+
+*Note*: The [`process.stderr`][] and [`process.stdout`][] Writable streams are
+never closed until the Node.js process exits, regardless of the specified
+options.
+
+##### readable.read([size])
+
+
+* `size` {Number} Optional argument to specify how much data to read.
+* Return {String|Buffer|Null}
+
+The `readable.read()` method pulls some data out of the internal buffer and
+returns it. If no data available to be read, `null` is returned. By default,
+the data will be returned as a `Buffer` object unless an encoding has been
+specified using the `readable.setEncoding()` method or the stream is operating
+in object mode.
+
+The optional `size` argument specifies a specific number of bytes to read. If
+`size` bytes are not available to be read, `null` will be returned *unless*
+the stream has ended, in which case all of the data remaining in the internal
+buffer will be returned (*even if it exceeds `size` bytes*).
+
+If the `size` argument is not specified, all of the data contained in the
+internal buffer will be returned.
+
+The `readable.read()` method should only be called on Readable streams operating
+in paused mode. In flowing mode, `readable.read()` is called automatically until
+the internal buffer is fully drained.
+
+```js
+const readable = getReadableStreamSomehow();
+readable.on('readable', () => {
+ var chunk;
+ while (null !== (chunk = readable.read())) {
+ console.log(`Received ${chunk.length} bytes of data.`);
+ }
+});
+```
+
+In general, it is recommended that developers avoid the use of the `'readable'`
+event and the `readable.read()` method in favor of using either
+`readable.pipe()` or the `'data'` event.
+
+A Readable stream in object mode will always return a single item from
+a call to [`readable.read(size)`][stream-read], regardless of the value of the
+`size` argument.
+
+*Note:* If the `readable.read()` method returns a chunk of data, a `'data'`
+event will also be emitted.
+
+*Note*: Calling [`stream.read([size])`][stream-read] after the [`'end'`][]
+event has been emitted will return `null`. No runtime error will be raised.
+
+##### readable.resume()
+
+
+* Return: `this`
+
+The `readable.resume()` method causes an explicitly paused Readable stream to
+resume emitting [`'data'`][] events, switching the stream into flowing mode.
+
+The `readable.resume()` method can be used to fully consume the data from a
+stream without actually processing any of that data as illustrated in the
+following example:
+
+```js
+getReadableStreamSomehow()
+ .resume()
+ .on('end', () => {
+ console.log('Reached the end, but did not read anything.');
+ });
+```
+
+##### readable.setEncoding(encoding)
+
+
+* `encoding` {String} The encoding to use.
+* Return: `this`
+
+The `readable.setEncoding()` method sets the default character encoding for
+data read from the Readable stream.
+
+Setting an encoding causes the stream data
+to be returned as string of the specified encoding rather than as `Buffer`
+objects. For instance, calling `readable.setEncoding('utf8')` will cause the
+output data will be interpreted as UTF-8 data, and passed as strings. Calling
+`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal
+string format.
+
+The Readable stream will properly handle multi-byte characters delivered through
+the stream that would otherwise become improperly decoded if simply pulled from
+the stream as `Buffer` objects.
+
+Encoding can be disabled by calling `readable.setEncoding(null)`. This approach
+is useful when working with binary data or with large multi-byte strings spread
+out over multiple chunks.
+
+```js
+const readable = getReadableStreamSomehow();
+readable.setEncoding('utf8');
+readable.on('data', (chunk) => {
+ assert.equal(typeof chunk, 'string');
+ console.log('got %d characters of string data', chunk.length);
+});
+```
+
+##### readable.unpipe([destination])
+
+
+* `destination` {stream.Writable} Optional specific stream to unpipe
+
+The `readable.unpipe()` method detaches a Writable stream previously attached
+using the [`stream.pipe()`][] method.
+
+If the `destination` is not specified, then *all* pipes are detached.
+
+If the `destination` is specified, but no pipe is set up for it, then
+the method does nothing.
+
+```js
+const readable = getReadableStreamSomehow();
+const writable = fs.createWriteStream('file.txt');
+// All the data from readable goes into 'file.txt',
+// but only for the first second
+readable.pipe(writable);
+setTimeout(() => {
+ console.log('Stop writing to file.txt');
+ readable.unpipe(writable);
+ console.log('Manually close the file stream');
+ writable.end();
+}, 1000);
+```
+
+##### readable.unshift(chunk)
+
+
+* `chunk` {Buffer|String} Chunk of data to unshift onto the read queue
+
+The `readable.unshift()` method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
+
+*Note*: The `stream.unshift(chunk)` method cannot be called after the
+[`'end'`][] event has been emitted or a runtime error will be thrown.
+
+Developers using `stream.unshift()` often should consider switching to
+use of a [Transform][] stream instead. See the [API for Stream Implementers][]
+section for more information.
+
+```js
+// Pull off a header delimited by \n\n
+// use unshift() if we get too much
+// Call the callback with (error, header, stream)
+const StringDecoder = require('string_decoder').StringDecoder;
+function parseHeader(stream, callback) {
+ stream.on('error', callback);
+ stream.on('readable', onReadable);
+ const decoder = new StringDecoder('utf8');
+ var header = '';
+ function onReadable() {
+ var chunk;
+ while (null !== (chunk = stream.read())) {
+ var str = decoder.write(chunk);
+ if (str.match(/\n\n/)) {
+ // found the header boundary
+ var split = str.split(/\n\n/);
+ header += split.shift();
+ const remaining = split.join('\n\n');
+ const buf = Buffer.from(remaining, 'utf8');
+ if (buf.length)
+ stream.unshift(buf);
+ stream.removeListener('error', callback);
+ stream.removeListener('readable', onReadable);
+ // now the body of the message can be read from the stream.
+ callback(null, header, stream);
+ } else {
+ // still reading the header.
+ header += str;
+ }
+ }
+ }
+}
+```
+
+*Note*: Unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)`
+will not end the reading process by resetting the internal reading state of the
+stream. This can cause unexpected results if `readable.unshift()` is called
+during a read (i.e. from within a [`stream._read()`][stream-_read]
+implementation on a custom stream). Following the call to `readable.unshift()`
+with an immediate [`stream.push('')`][stream-push] will reset the reading state
+appropriately, however it is best to simply avoid calling `readable.unshift()`
+while in the process of performing a read.
+
+##### readable.wrap(stream)
+
+
+* `stream` {Stream} An "old style" readable stream
+
+Versions of Node.js prior to v0.10 had streams that did not implement the
+entire `stream` module API as it is currently defined. (See [Compatibility][]
+for more information.)
+
+When using an older Node.js library that emits [`'data'`][] events and has a
+[`stream.pause()`][stream-pause] method that is advisory only, the
+`readable.wrap()` method can be used to create a [Readable][] stream that uses
+the old stream as its data source.
+
+It will rarely be necessary to use `readable.wrap()` but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
+
+For example:
+
+```js
+const OldReader = require('./old-api-module.js').OldReader;
+const Readable = require('stream').Readable;
+const oreader = new OldReader;
+const myReader = new Readable().wrap(oreader);
+
+myReader.on('readable', () => {
+ myReader.read(); // etc.
+});
+```
+
+### Duplex and Transform Streams
+
+#### Class: stream.Duplex
+
+
+
+
+Duplex streams are streams that implement both the [Readable][] and
+[Writable][] interfaces.
+
+Examples of Duplex streams include:
+
+* [TCP sockets][]
+* [zlib streams][zlib]
+* [crypto streams][crypto]
+
+#### Class: stream.Transform
+
+
+
+
+Transform streams are [Duplex][] streams where the output is in some way
+related to the input. Like all [Duplex][] streams, Transform streams
+implement both the [Readable][] and [Writable][] interfaces.
+
+Examples of Transform streams include:
+
+* [zlib streams][zlib]
+* [crypto streams][crypto]
+
+
+## API for Stream Implementers
+
+
+
+The `stream` module API has been designed to make it possible to easily
+implement streams using JavaScript's prototypical inheritance model.
+
+First, a stream developer would declare a new JavaScript class that extends one
+of the four basic stream classes (`stream.Writable`, `stream.Readable`,
+`stream.Duplex`, or `stream.Transform`), making sure the call the appropriate
+parent class constructor:
+
+```js
+const Writable = require('stream').Writable;
+
+class MyWritable extends Writable {
+ constructor(options) {
+ super(options);
+ }
+}
+```
+
+The new stream class must then implement one or more specific methods, depending
+on the type of stream being created, as detailed in the chart below:
+
+
+
+
+
+ Use-case
+ |
+
+ Class
+ |
+
+ Method(s) to implement
+ |
+
+
+
+
+ Reading only
+ |
+
+ [Readable](#stream_class_stream_readable)
+ |
+
+ [_read][stream-_read]
+ |
+
+
+
+ Writing only
+ |
+
+ [Writable](#stream_class_stream_writable)
+ |
+
+ [_write][stream-_write] , [_writev][stream-_writev]
+ |
+
+
+
+ Reading and writing
+ |
+
+ [Duplex](#stream_class_stream_duplex)
+ |
+
+ [_read][stream-_read] , [_write][stream-_write] , [_writev][stream-_writev]
+ |
+
+
+
+ Operate on written data, then read the result
+ |
+
+ [Transform](#stream_class_stream_transform)
+ |
+
+ [_transform][stream-_transform] , [_flush][stream-_flush]
+ |
+
+
+
+*Note*: The implementation code for a stream should *never* call the "public"
+methods of a stream that are intended for use by consumers (as described in
+the [API for Stream Consumers][] section). Doing so may lead to adverse
+side effects in application code consuming the stream.
+
+### Simplified Construction
+
+For many simple cases, it is possible to construct a stream without relying on
+inheritance. This can be accomplished by directly creating instances of the
+`stream.Writable`, `stream.Readable`, `stream.Duplex` or `stream.Transform`
+objects and passing appropriate methods as constructor options.
+
+For example:
+
+```js
+const Writable = require('stream').Writable;
+
+const myWritable = new Writable({
+ write(chunk, encoding, callback) {
+ // ...
+ }
+});
+```
+
+### Implementing a Writable Stream
+
+The `stream.Writable` class is extended to implement a [Writable][] stream.
+
+Custom Writable streams *must* call the `new stream.Writable([options])`
+constructor and implement the `writable._write()` method. The
+`writable._writev()` method *may* also be implemented.
+
+#### Constructor: new stream.Writable([options])
+
+* `options` {Object}
+ * `highWaterMark` {Number} Buffer level when
+ [`stream.write()`][stream-write] starts returning `false`. Defaults to
+ `16384` (16kb), or `16` for `objectMode` streams.
+ * `decodeStrings` {Boolean} Whether or not to decode strings into
+ Buffers before passing them to [`stream._write()`][stream-_write].
+ Defaults to `true`
+ * `objectMode` {Boolean} Whether or not the
+ [`stream.write(anyObj)`][stream-write] is a valid operation. When set,
+ it becomes possible to write JavaScript values other than string or
+ `Buffer` if supported by the stream implementation. Defaults to `false`
+ * `write` {Function} Implementation for the
+ [`stream._write()`][stream-_write] method.
+ * `writev` {Function} Implementation for the
+ [`stream._writev()`][stream-_writev] method.
+
+For example:
+
+```js
+const Writable = require('stream').Writable;
+
+class MyWritable extends Writable {
+ constructor(options) {
+ // Calls the stream.Writable() constructor
+ super(options);
+ }
+}
+```
+
+Or, when using pre-ES6 style constructors:
+
+```js
+const Writable = require('stream').Writable;
+const util = require('util');
+
+function MyWritable(options) {
+ if (!(this instanceof MyWritable))
+ return new MyWritable(options);
+ Writable.call(this, options);
+}
+util.inherits(MyWritable, Writable);
+```
+
+Or, using the Simplified Constructor approach:
+
+```js
+const Writable = require('stream').Writable;
+
+const myWritable = new Writable({
+ write(chunk, encoding, callback) {
+ // ...
+ },
+ writev(chunks, callback) {
+ // ...
+ }
+});
+```
+
+#### writable.\_write(chunk, encoding, callback)
+
+* `chunk` {Buffer|String} The chunk to be written. Will **always**
+ be a buffer unless the `decodeStrings` option was set to `false`.
+* `encoding` {String} If the chunk is a string, then `encoding` is the
+ character encoding of that string. If chunk is a `Buffer`, or if the
+ stream is operating in object mode, `encoding` may be ignored.
+* `callback` {Function} Call this function (optionally with an error
+ argument) when processing is complete for the supplied chunk.
+
+All Writable stream implementations must provide a
+[`writable._write()`][stream-_write] method to send data to the underlying
+resource.
+
+*Note*: [Transform][] streams provide their own implementation of the
+[`writable._write()`][stream-_write].
+
+*Note*: **This function MUST NOT be called by application code directly.** It
+should be implemented by child classes, and called only by the internal Writable
+class methods only.
+
+The `callback` method must be called to signal either that the write completed
+successfully or failed with an error. The first argument passed to the
+`callback` must be the `Error` object if the call failed or `null` if the
+write succeeded.
+
+It is important to note that all calls to `writable.write()` that occur between
+the time `writable._write()` is called and the `callback` is called will cause
+the written data to be buffered. Once the `callback` is invoked, the stream will
+emit a `'drain'` event. If a stream implementation is capable of processing
+multiple chunks of data at once, the `writable._writev()` method should be
+implemented.
+
+If the `decodeStrings` property is set in the constructor options, then
+`chunk` may be a string rather than a Buffer, and `encoding` will
+indicate the character encoding of the string. This is to support
+implementations that have an optimized handling for certain string
+data encodings. If the `decodeStrings` property is explicitly set to `false`,
+the `encoding` argument can be safely ignored, and `chunk` will always be a
+`Buffer`.
+
+The `writable._write()` method is prefixed with an underscore because it is
+internal to the class that defines it, and should never be called directly by
+user programs.
+
+#### writable.\_writev(chunks, callback)
+
+* `chunks` {Array} The chunks to be written. Each chunk has following
+ format: `{ chunk: ..., encoding: ... }`.
+* `callback` {Function} A callback function (optionally with an error
+ argument) to be invoked when processing is complete for the supplied chunks.
+
+*Note*: **This function MUST NOT be called by application code directly.** It
+should be implemented by child classes, and called only by the internal Writable
+class methods only.
+
+The `writable._writev()` method may be implemented in addition to
+`writable._write()` in stream implementations that are capable of processing
+multiple chunks of data at once. If implemented, the method will be called with
+all chunks of data currently buffered in the write queue.
+
+The `writable._writev()` method is prefixed with an underscore because it is
+internal to the class that defines it, and should never be called directly by
+user programs.
+
+#### Errors While Writing
+
+It is recommended that errors occurring during the processing of the
+`writable._write()` and `writable._writev()` methods are reported by invoking
+the callback and passing the error as the first argument. This will cause an
+`'error'` event to be emitted by the Writable. Throwing an Error from within
+`writable._write()` can result in expected and inconsistent behavior depending
+on how the stream is being used. Using the callback ensures consistent and
+predictable handling of errors.
+
+```js
+const Writable = require('stream').Writable;
+
+const myWritable = new Writable({
+ write(chunk, encoding, callback) {
+ if (chunk.toString().indexOf('a') >= 0) {
+ callback(new Error('chunk is invalid'));
+ } else {
+ callback();
+ }
+ }
+});
+```
+
+#### An Example Writable Stream
+
+The following illustrates a rather simplistic (and somewhat pointless) custom
+Writable stream implementation. While this specific Writable stream instance
+is not of any real particular usefulness, the example illustrates each of the
+required elements of a custom [Writable][] stream instance:
+
+```js
+const Writable = require('stream').Writable;
+
+class MyWritable extends Writable {
+ constructor(options) {
+ super(options);
+ }
+
+ _write(chunk, encoding, callback) {
+ if (chunk.toString().indexOf('a') >= 0) {
+ callback(new Error('chunk is invalid'));
+ } else {
+ callback();
+ }
+ }
+}
+```
+
+### Implementing a Readable Stream
+
+The `stream.Readable` class is extended to implement a [Readable][] stream.
+
+Custom Readable streams *must* call the `new stream.Readable([options])`
+constructor and implement the `readable._read()` method.
+
+#### new stream.Readable([options])
+
+* `options` {Object}
+ * `highWaterMark` {Number} The maximum number of bytes to store in
+ the internal buffer before ceasing to read from the underlying
+ resource. Defaults to `16384` (16kb), or `16` for `objectMode` streams
+ * `encoding` {String} If specified, then buffers will be decoded to
+ strings using the specified encoding. Defaults to `null`
+ * `objectMode` {Boolean} Whether this stream should behave
+ as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns
+ a single value instead of a Buffer of size n. Defaults to `false`
+ * `read` {Function} Implementation for the [`stream._read()`][stream-_read]
+ method.
+
+For example:
+
+```js
+const Readable = require('stream').Readable;
+
+class MyReadable extends Readable {
+ constructor(options) {
+ // Calls the stream.Readable(options) constructor
+ super(options);
+ }
+}
+```
+
+Or, when using pre-ES6 style constructors:
+
+```js
+const Readable = require('stream').Readable;
+const util = require('util');
+
+function MyReadable(options) {
+ if (!(this instanceof MyReadable))
+ return new MyReadable(options);
+ Readable.call(this, options);
+}
+util.inherits(MyReadable, Readable);
+```
+
+Or, using the Simplified Constructor approach:
+
+```js
+const Readable = require('stream').Readable;
+
+const myReadable = new Readable({
+ read(size) {
+ // ...
+ }
+});
+```
+
+#### readable.\_read(size)
+
+* `size` {Number} Number of bytes to read asynchronously
+
+*Note*: **This function MUST NOT be called by application code directly.** It
+should be implemented by child classes, and called only by the internal Readable
+class methods only.
+
+All Readable stream implementations must provide an implementation of the
+`readable._read()` method to fetch data from the underlying resource.
+
+When `readable._read()` is called, if data is available from the resource, the
+implementation should begin pushing that data into the read queue using the
+[`this.push(dataChunk)`][stream-push] method. `_read()` should continue reading
+from the resource and pushing data until `readable.push()` returns `false`. Only
+when `_read()` is called again after it has stopped should it resume pushing
+additional data onto the queue.
+
+*Note*: Once the `readable._read()` method has been called, it will not be
+called again until the [`readable.push()`][stream-push] method is called.
+
+The `size` argument is advisory. For implementations where a "read" is a
+single operation that returns data can use the `size` argument to determine how
+much data to fetch. Other implementations may ignore this argument and simply
+provide data whenever it becomes available. There is no need to "wait" until
+`size` bytes are available before calling [`stream.push(chunk)`][stream-push].
+
+The `readable._read()` method is prefixed with an underscore because it is
+internal to the class that defines it, and should never be called directly by
+user programs.
+
+#### readable.push(chunk[, encoding])
+
+* `chunk` {Buffer|Null|String} Chunk of data to push into the read queue
+* `encoding` {String} Encoding of String chunks. Must be a valid
+ Buffer encoding, such as `'utf8'` or `'ascii'`
+* Returns {Boolean} `true` if additional chunks of data may continued to be
+ pushed; `false` otherwise.
+
+When `chunk` is a `Buffer` or `string`, the `chunk` of data will be added to the
+internal queue for users of the stream to consume. Passing `chunk` as `null`
+signals the end of the stream (EOF), after which no more data can be written.
+
+When the Readable is operating in paused mode, the data added with
+`readable.push()` can be read out by calling the
+[`readable.read()`][stream-read] method when the [`'readable'`][] event is
+emitted.
+
+When the Readable is operating in flowing mode, the data added with
+`readable.push()` will be delivered by emitting a `'data'` event.
+
+The `readable.push()` method is designed to be as flexible as possible. For
+example, when wrapping a lower-level source that provides some form of
+pause/resume mechanism, and a data callback, the low-level source can be wrapped
+by the custom Readable instance as illustrated in the following example:
+
+```js
+// source is an object with readStop() and readStart() methods,
+// and an `ondata` member that gets called when it has data, and
+// an `onend` member that gets called when the data is over.
+
+class SourceWrapper extends Readable {
+ constructor(options) {
+ super(options);
+
+ this._source = getLowlevelSourceObject();
+
+ // Every time there's data, push it into the internal buffer.
+ this._source.ondata = (chunk) => {
+ // if push() returns false, then stop reading from source
+ if (!this.push(chunk))
+ this._source.readStop();
+ };
+
+ // When the source ends, push the EOF-signaling `null` chunk
+ this._source.onend = () => {
+ this.push(null);
+ };
+ }
+ // _read will be called when the stream wants to pull more data in
+ // the advisory size argument is ignored in this case.
+ _read(size) {
+ this._source.readStart();
+ }
+}
+```
+*Note*: The `readable.push()` method is intended be called only by Readable
+Implementers, and only from within the `readable._read()` method.
+
+#### Errors While Reading
+
+It is recommended that errors occurring during the processing of the
+`readable._read()` method are emitted using the `'error'` event rather than
+being thrown. Throwing an Error from within `readable._read()` can result in
+expected and inconsistent behavior depending on whether the stream is operating
+in flowing or paused mode. Using the `'error'` event ensures consistent and
+predictable handling of errors.
+
+```js
+const Readable = require('stream').Readable;
+
+const myReadable = new Readable({
+ read(size) {
+ if (checkSomeErrorCondition()) {
+ process.nextTick(() => this.emit('error', err));
+ return;
+ }
+ // do some work
+ }
+});
+```
+
+#### An Example Counting Stream
+
+
+
+The following is a basic example of a Readable stream that emits the numerals
+from 1 to 1,000,000 in ascending order, and then ends.
+
+```js
+const Readable = require('stream').Readable;
+
+class Counter extends Readable {
+ constructor(opt) {
+ super(opt);
+ this._max = 1000000;
+ this._index = 1;
+ }
+
+ _read() {
+ var i = this._index++;
+ if (i > this._max)
+ this.push(null);
+ else {
+ var str = '' + i;
+ var buf = Buffer.from(str, 'ascii');
+ this.push(buf);
+ }
+ }
+}
+```
+
+### Implementing a Duplex Stream
+
+A [Duplex][] stream is one that implements both [Readable][] and [Writable][],
+such as a TCP socket connection.
+
+Because Javascript does not have support for multiple inheritance, the
+`stream.Duplex` class is extended to implement a [Duplex][] stream (as opposed
+to extending the `stream.Readable` *and* `stream.Writable` classes).
+
+*Note*: The `stream.Duplex` class prototypically inherits from `stream.Readable`
+and parasitically from `stream.Writable`.
+
+Custom Duplex streams *must* call the `new stream.Duplex([options])`
+constructor and implement *both* the `readable._read()` and
+`writable._write()` methods.
+
+#### new stream.Duplex(options)
+
+* `options` {Object} Passed to both Writable and Readable
+ constructors. Also has the following fields:
+ * `allowHalfOpen` {Boolean} Defaults to `true`. If set to `false`, then
+ the stream will automatically end the readable side when the
+ writable side ends and vice versa.
+ * `readableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode`
+ for readable side of the stream. Has no effect if `objectMode`
+ is `true`.
+ * `writableObjectMode` {Boolean} Defaults to `false`. Sets `objectMode`
+ for writable side of the stream. Has no effect if `objectMode`
+ is `true`.
+
+For example:
+
+```js
+const Duplex = require('stream').Duplex;
+
+class MyDuplex extends Duplex {
+ constructor(options) {
+ super(options);
+ }
+}
+```
+
+Or, when using pre-ES6 style constructors:
+
+```js
+const Duplex = require('stream').Duplex;
+const util = require('util');
+
+function MyDuplex(options) {
+ if (!(this instanceof MyDuplex))
+ return new MyDuplex(options);
+ Duplex.call(this, options);
+}
+util.inherits(MyDuplex, Duplex);
+```
+
+Or, using the Simplified Constructor approach:
+
+```js
+const Duplex = require('stream').Duplex;
+
+const myDuplex = new Duplex({
+ read(size) {
+ // ...
+ },
+ write(chunk, encoding, callback) {
+ // ...
+ }
+});
+```
+
+#### An Example Duplex Stream
+
+The following illustrates a simple example of a Duplex stream that wraps a
+hypothetical lower-level source object to which data can be written, and
+from which data can be read, albeit using an API that is not compatible with
+Node.js streams.
+The following illustrates a simple example of a Duplex stream that buffers
+incoming written data via the [Writable][] interface that is read back out
+via the [Readable][] interface.
+
+```js
+const Duplex = require('stream').Duplex;
+const kSource = Symbol('source');
+
+class MyDuplex extends Duplex {
+ constructor(source, options) {
+ super(options);
+ this[kSource] = source;
+ }
+
+ _write(chunk, encoding, callback) {
+ // The underlying source only deals with strings
+ if (Buffer.isBuffer(chunk))
+ chunk = chunk.toString(encoding);
+ this[kSource].writeSomeData(chunk, encoding);
+ callback();
+ }
+
+ _read(size) {
+ this[kSource].fetchSomeData(size, (data, encoding) => {
+ this.push(Buffer.from(data, encoding));
+ });
+ }
+}
+```
+
+The most important aspect of a Duplex stream is that the Readable and Writable
+sides operate independently of one another despite co-existing within a single
+object instance.
+
+#### Object Mode Duplex Streams
+
+For Duplex streams, `objectMode` can be set exclusively for either the Readable
+or Writable side using the `readableObjectMode` and `writableObjectMode` options
+respectively.
+
+In the following example, for instance, a new Transform stream (which is a
+type of [Duplex][] stream) is created that has an object mode Writable side
+that accepts JavaScript numbers that are converted to hexidecimal strings on
+the Readable side.
+
+```js
+const Transform = require('stream').Transform;
+
+// All Transform streams are also Duplex Streams
+const myTransform = new Transform({
+ writableObjectMode: true,
+
+ transform(chunk, encoding, callback) {
+ // Coerce the chunk to a number if necessary
+ chunk |= 0;
+
+ // Transform the chunk into something else.
+ const data = chunk.toString(16);
+
+ // Push the data onto the readable queue.
+ callback(null, '0'.repeat(data.length % 2) + data);
+ }
+});
+
+myTransform.setEncoding('ascii');
+myTransform.on('data', (chunk) => console.log(chunk));
+
+myTransform.write(1);
+ // Prints: 01
+myTransform.write(10);
+ // Prints: 0a
+myTransform.write(100);
+ // Prints: 64
+```
+
+### Implementing a Transform Stream
+
+A [Transform][] stream is a [Duplex][] stream where the output is computed
+in some way from the input. Examples include [zlib][] streams or [crypto][]
+streams that compress, encrypt, or decrypt data.
+
+*Note*: There is no requirement that the output be the same size as the input,
+the same number of chunks, or arrive at the same time. For example, a
+Hash stream will only ever have a single chunk of output which is
+provided when the input is ended. A `zlib` stream will produce output
+that is either much smaller or much larger than its input.
+
+The `stream.Transform` class is extended to implement a [Transform][] stream.
+
+The `stream.Transform` class prototypically inherits from `stream.Duplex` and
+implements its own versions of the `writable._write()` and `readable._read()`
+methods. Custom Transform implementations *must* implement the
+[`transform._transform()`][stream-_transform] method and *may* also implement
+the [`transform._flush()`][stream-_flush] method.
+
+*Note*: Care must be taken when using Transform streams in that data written
+to the stream can cause the Writable side of the stream to become paused if
+the output on the Readable side is not consumed.
+
+#### new stream.Transform([options])
+
+* `options` {Object} Passed to both Writable and Readable
+ constructors. Also has the following fields:
+ * `transform` {Function} Implementation for the
+ [`stream._transform()`][stream-_transform] method.
+ * `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush]
+ method.
+
+For example:
+
+```js
+const Transform = require('stream').Transform;
+
+class MyTransform extends Transform {
+ constructor(options) {
+ super(options);
+ }
+}
+```
+
+Or, when using pre-ES6 style constructors:
+
+```js
+const Transform = require('stream').Transform;
+const util = require('util');
+
+function MyTransform(options) {
+ if (!(this instanceof MyTransform))
+ return new MyTransform(options);
+ Transform.call(this, options);
+}
+util.inherits(MyTransform, Transform);
+```
+
+Or, using the Simplified Constructor approach:
+
+```js
+const Transform = require('stream').Transform;
+
+const myTransform = new Transform({
+ transform(chunk, encoding, callback) {
+ // ...
+ }
+});
+```
+
+#### Events: 'finish' and 'end'
+
+The [`'finish'`][] and [`'end'`][] events are from the `stream.Writable`
+and `stream.Readable` classes, respectively. The `'finish'` event is emitted
+after [`stream.end()`][stream-end] is called and all chunks have been processed
+by [`stream._transform()`][stream-_transform]. The `'end'` event is emitted
+after all data has been output, which occurs after the callback in
+[`transform._flush()`][stream-_flush] has been called.
+
+#### transform.\_flush(callback)
+
+* `callback` {Function} A callback function (optionally with an error
+ argument) to be called when remaining data has been flushed.
+
+*Note*: **This function MUST NOT be called by application code directly.** It
+should be implemented by child classes, and called only by the internal Readable
+class methods only.
+
+In some cases, a transform operation may need to emit an additional bit of
+data at the end of the stream. For example, a `zlib` compression stream will
+store an amount of internal state used to optimally compress the output. When
+the stream ends, however, that additional data needs to be flushed so that the
+compressed data will be complete.
+
+Custom [Transform][] implementations *may* implement the `transform._flush()`
+method. This will be called when there is no more written data to be consumed,
+but before the [`'end'`][] event is emitted signaling the end of the
+[Readable][] stream.
+
+Within the `transform._flush()` implementation, the `readable.push()` method
+may be called zero or more times, as appropriate. The `callback` function must
+be called when the flush operation is complete.
+
+The `transform._flush()` method is prefixed with an underscore because it is
+internal to the class that defines it, and should never be called directly by
+user programs.
+
+#### transform.\_transform(chunk, encoding, callback)
+
+* `chunk` {Buffer|String} The chunk to be transformed. Will **always**
+ be a buffer unless the `decodeStrings` option was set to `false`.
+* `encoding` {String} If the chunk is a string, then this is the
+ encoding type. If chunk is a buffer, then this is the special
+ value - 'buffer', ignore it in this case.
+* `callback` {Function} A callback function (optionally with an error
+ argument and data) to be called after the supplied `chunk` has been
+ processed.
+
+*Note*: **This function MUST NOT be called by application code directly.** It
+should be implemented by child classes, and called only by the internal Readable
+class methods only.
+
+All Transform stream implementations must provide a `_transform()`
+method to accept input and produce output. The `transform._transform()`
+implementation handles the bytes being written, computes an output, then passes
+that output off to the readable portion using the `readable.push()` method.
+
+The `transform.push()` method may be called zero or more times to generate
+output from a single input chunk, depending on how much is to be output
+as a result of the chunk.
+
+It is possible that no output is generated from any given chunk of input data.
+
+The `callback` function must be called only when the current chunk is completely
+consumed. The first argument passed to the `callback` must be an `Error` object
+if an error occurred while processing the input or `null` otherwise. If a second
+argument is passed to the `callback`, it will be forwarded on to the
+`readable.push()` method. In other words the following are equivalent:
+
+```js
+transform.prototype._transform = function (data, encoding, callback) {
+ this.push(data);
+ callback();
+};
+
+transform.prototype._transform = function (data, encoding, callback) {
+ callback(null, data);
+};
+```
+
+The `transform._transform()` method is prefixed with an underscore because it
+is internal to the class that defines it, and should never be called directly by
+user programs.
+
+#### Class: stream.PassThrough
+
+The `stream.PassThrough` class is a trivial implementation of a [Transform][]
+stream that simply passes the input bytes across to the output. Its purpose is
+primarily for examples and testing, but there are some use cases where
+`stream.PassThrough` is useful as a building block for novel sorts of streams.
+
+## Additional Notes
+
+
+
+### Compatibility with Older Node.js Versions
+
+
+
+In versions of Node.js prior to v0.10, the Readable stream interface was
+simpler, but also less powerful and less useful.
+
+* Rather than waiting for calls the [`stream.read()`][stream-read] method,
+ [`'data'`][] events would begin emitting immediately. Applications that
+ would need to perform some amount of work to decide how to handle data
+ were required to store read data into buffers so the data would not be lost.
+* The [`stream.pause()`][stream-pause] method was advisory, rather than
+ guaranteed. This meant that it was still necessary to be prepared to receive
+ [`'data'`][] events *even when the stream was in a paused state*.
+
+In Node.js v0.10, the [Readable][] class was added. For backwards compatibility
+with older Node.js programs, Readable streams switch into "flowing mode" when a
+[`'data'`][] event handler is added, or when the
+[`stream.resume()`][stream-resume] method is called. The effect is that, even
+when not using the new [`stream.read()`][stream-read] method and
+[`'readable'`][] event, it is no longer necessary to worry about losing
+[`'data'`][] chunks.
+
+While most applications will continue to function normally, this introduces an
+edge case in the following conditions:
+
+* No [`'data'`][] event listener is added.
+* The [`stream.resume()`][stream-resume] method is never called.
+* The stream is not piped to any writable destination.
+
+For example, consider the following code:
+
+```js
+// WARNING! BROKEN!
+net.createServer((socket) => {
+
+ // we add an 'end' method, but never consume the data
+ socket.on('end', () => {
+ // It will never get here.
+ socket.end('The message was received but was not processed.\n');
+ });
+
+}).listen(1337);
+```
+
+In versions of Node.js prior to v0.10, the incoming message data would be
+simply discarded. However, in Node.js v0.10 and beyond, the socket remains
+paused forever.
+
+The workaround in this situation is to call the
+[`stream.resume()`][stream-resume] method to begin the flow of data:
+
+```js
+// Workaround
+net.createServer((socket) => {
+
+ socket.on('end', () => {
+ socket.end('The message was received but was not processed.\n');
+ });
+
+ // start the flow of data, discarding it.
+ socket.resume();
+
+}).listen(1337);
+```
+
+In addition to new Readable streams switching into flowing mode,
+pre-v0.10 style streams can be wrapped in a Readable class using the
+[`readable.wrap()`][`stream.wrap()`] method.
+
+
+### `readable.read(0)`
+
+There are some cases where it is necessary to trigger a refresh of the
+underlying readable stream mechanisms, without actually consuming any
+data. In such cases, it is possible to call `readable.read(0)`, which will
+always return `null`.
+
+If the internal read buffer is below the `highWaterMark`, and the
+stream is not currently reading, then calling `stream.read(0)` will trigger
+a low-level [`stream._read()`][stream-_read] call.
+
+While most applications will almost never need to do this, there are
+situations within Node.js where this is done, particularly in the
+Readable stream class internals.
+
+### `readable.push('')`
+
+Use of `readable.push('')` is not recommended.
+
+Pushing a zero-byte string or `Buffer` to a stream that is not in object mode
+has an interesting side effect. Because it *is* a call to
+[`readable.push()`][stream-push], the call will end the reading process.
+However, because the argument is an empty string, no data is added to the
+readable buffer so there is nothing for a user to consume.
+
+[`'data'`]: #stream_event_data
+[`'drain'`]: #stream_event_drain
+[`'end'`]: #stream_event_end
+[`'finish'`]: #stream_event_finish
+[`'readable'`]: #stream_event_readable
+[`buf.toString(encoding)`]: https://nodejs.org/docs/v6.3.1/api/buffer.html#buffer_buf_tostring_encoding_start_end
+[`EventEmitter`]: https://nodejs.org/docs/v6.3.1/api/events.html#events_class_eventemitter
+[`process.stderr`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stderr
+[`process.stdin`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdin
+[`process.stdout`]: https://nodejs.org/docs/v6.3.1/api/process.html#process_process_stdout
+[`stream.cork()`]: #stream_writable_cork
+[`stream.pipe()`]: #stream_readable_pipe_destination_options
+[`stream.uncork()`]: #stream_writable_uncork
+[`stream.unpipe()`]: #stream_readable_unpipe_destination
+[`stream.wrap()`]: #stream_readable_wrap_stream
+[`tls.CryptoStream`]: https://nodejs.org/docs/v6.3.1/api/tls.html#tls_class_cryptostream
+[API for Stream Consumers]: #stream_api_for_stream_consumers
+[API for Stream Implementers]: #stream_api_for_stream_implementers
+[child process stdin]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdin
+[child process stdout and stderr]: https://nodejs.org/docs/v6.3.1/api/child_process.html#child_process_child_stdout
+[Compatibility]: #stream_compatibility_with_older_node_js_versions
+[crypto]: crypto.html
+[Duplex]: #stream_class_stream_duplex
+[fs read streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_readstream
+[fs write streams]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_class_fs_writestream
+[`fs.createReadStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createreadstream_path_options
+[`fs.createWriteStream()`]: https://nodejs.org/docs/v6.3.1/api/fs.html#fs_fs_createwritestream_path_options
+[`net.Socket`]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket
+[`zlib.createDeflate()`]: https://nodejs.org/docs/v6.3.1/api/zlib.html#zlib_zlib_createdeflate_options
+[HTTP requests, on the client]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_clientrequest
+[HTTP responses, on the server]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_serverresponse
+[http-incoming-message]: https://nodejs.org/docs/v6.3.1/api/http.html#http_class_http_incomingmessage
+[Object mode]: #stream_object_mode
+[Readable]: #stream_class_stream_readable
+[SimpleProtocol v2]: #stream_example_simpleprotocol_parser_v2
+[stream-_flush]: #stream_transform_flush_callback
+[stream-_read]: #stream_readable_read_size_1
+[stream-_transform]: #stream_transform_transform_chunk_encoding_callback
+[stream-_write]: #stream_writable_write_chunk_encoding_callback_1
+[stream-_writev]: #stream_writable_writev_chunks_callback
+[stream-end]: #stream_writable_end_chunk_encoding_callback
+[stream-pause]: #stream_readable_pause
+[stream-push]: #stream_readable_push_chunk_encoding
+[stream-read]: #stream_readable_read_size
+[stream-resume]: #stream_readable_resume
+[stream-write]: #stream_writable_write_chunk_encoding_callback
+[TCP sockets]: https://nodejs.org/docs/v6.3.1/api/net.html#net_class_net_socket
+[Transform]: #stream_class_stream_transform
+[Writable]: #stream_class_stream_writable
+[zlib]: zlib.html
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md b/node_modules/are-we-there-yet/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md
new file mode 100644
index 0000000..83275f1
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/doc/wg-meetings/2015-01-30.md
@@ -0,0 +1,60 @@
+# streams WG Meeting 2015-01-30
+
+## Links
+
+* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg
+* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106
+* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/
+
+## Agenda
+
+Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting.
+
+* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105)
+* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101)
+* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102)
+* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99)
+
+## Minutes
+
+### adopt a charter
+
+* group: +1's all around
+
+### What versioning scheme should be adopted?
+* group: +1’s 3.0.0
+* domenic+group: pulling in patches from other sources where appropriate
+* mikeal: version independently, suggesting versions for io.js
+* mikeal+domenic: work with TC to notify in advance of changes
+simpler stream creation
+
+### streamline creation of streams
+* sam: streamline creation of streams
+* domenic: nice simple solution posted
+ but, we lose the opportunity to change the model
+ may not be backwards incompatible (double check keys)
+
+ **action item:** domenic will check
+
+### remove implicit flowing of streams on(‘data’)
+* add isFlowing / isPaused
+* mikeal: worrying that we’re documenting polyfill methods – confuses users
+* domenic: more reflective API is probably good, with warning labels for users
+* new section for mad scientists (reflective stream access)
+* calvin: name the “third state”
+* mikeal: maybe borrow the name from whatwg?
+* domenic: we’re missing the “third state”
+* consensus: kind of difficult to name the third state
+* mikeal: figure out differences in states / compat
+* mathias: always flow on data – eliminates third state
+ * explore what it breaks
+
+**action items:**
+* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream)
+* ask rod/build for infrastructure
+* **chris**: explore the “flow on data” approach
+* add isPaused/isFlowing
+* add new docs section
+* move isPaused to that section
+
+
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js b/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js
new file mode 100644
index 0000000..ca807af
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/duplex.js
@@ -0,0 +1 @@
+module.exports = require("./lib/_stream_duplex.js")
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js
new file mode 100644
index 0000000..736693b
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js
@@ -0,0 +1,75 @@
+// a duplex stream is just a stream that is both readable and writable.
+// Since JS doesn't have multiple prototypal inheritance, this class
+// prototypally inherits from Readable, and then parasitically from
+// Writable.
+
+'use strict';
+
+/**/
+
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ keys.push(key);
+ }return keys;
+};
+/**/
+
+module.exports = Duplex;
+
+/**/
+var processNextTick = require('process-nextick-args');
+/**/
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+var Readable = require('./_stream_readable');
+var Writable = require('./_stream_writable');
+
+util.inherits(Duplex, Readable);
+
+var keys = objectKeys(Writable.prototype);
+for (var v = 0; v < keys.length; v++) {
+ var method = keys[v];
+ if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
+}
+
+function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
+
+ Readable.call(this, options);
+ Writable.call(this, options);
+
+ if (options && options.readable === false) this.readable = false;
+
+ if (options && options.writable === false) this.writable = false;
+
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
+
+ this.once('end', onend);
+}
+
+// the no-half-open enforcer
+function onend() {
+ // if we allow half-open state, or if the writable side ended,
+ // then we're ok.
+ if (this.allowHalfOpen || this._writableState.ended) return;
+
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ processNextTick(onEndNT, this);
+}
+
+function onEndNT(self) {
+ self.end();
+}
+
+function forEach(xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
+ }
+}
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js
new file mode 100644
index 0000000..d06f71f
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js
@@ -0,0 +1,26 @@
+// a passthrough stream.
+// basically just the most minimal sort of Transform stream.
+// Every written chunk gets output as-is.
+
+'use strict';
+
+module.exports = PassThrough;
+
+var Transform = require('./_stream_transform');
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+util.inherits(PassThrough, Transform);
+
+function PassThrough(options) {
+ if (!(this instanceof PassThrough)) return new PassThrough(options);
+
+ Transform.call(this, options);
+}
+
+PassThrough.prototype._transform = function (chunk, encoding, cb) {
+ cb(null, chunk);
+};
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js
new file mode 100644
index 0000000..208cc65
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js
@@ -0,0 +1,937 @@
+'use strict';
+
+module.exports = Readable;
+
+/**/
+var processNextTick = require('process-nextick-args');
+/**/
+
+/**/
+var isArray = require('isarray');
+/**/
+
+Readable.ReadableState = ReadableState;
+
+/**/
+var EE = require('events').EventEmitter;
+
+var EElistenerCount = function (emitter, type) {
+ return emitter.listeners(type).length;
+};
+/**/
+
+/**/
+var Stream;
+(function () {
+ try {
+ Stream = require('st' + 'ream');
+ } catch (_) {} finally {
+ if (!Stream) Stream = require('events').EventEmitter;
+ }
+})();
+/**/
+
+var Buffer = require('buffer').Buffer;
+/**/
+var bufferShim = require('buffer-shims');
+/**/
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+/**/
+var debugUtil = require('util');
+var debug = void 0;
+if (debugUtil && debugUtil.debuglog) {
+ debug = debugUtil.debuglog('stream');
+} else {
+ debug = function () {};
+}
+/**/
+
+var BufferList = require('./internal/streams/BufferList');
+var StringDecoder;
+
+util.inherits(Readable, Stream);
+
+function prependListener(emitter, event, fn) {
+ if (typeof emitter.prependListener === 'function') {
+ return emitter.prependListener(event, fn);
+ } else {
+ // This is a hack to make sure that our error handler is attached before any
+ // userland ones. NEVER DO THIS. This is here only because this code needs
+ // to continue to work with older versions of Node.js that do not include
+ // the prependListener() method. The goal is to eventually remove this hack.
+ if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
+ }
+}
+
+var Duplex;
+function ReadableState(options, stream) {
+ Duplex = Duplex || require('./_stream_duplex');
+
+ options = options || {};
+
+ // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+ this.objectMode = !!options.objectMode;
+
+ if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
+
+ // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+ var hwm = options.highWaterMark;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
+
+ // cast to ints.
+ this.highWaterMark = ~ ~this.highWaterMark;
+
+ // A linked list is used to store data chunks instead of an array because the
+ // linked list can remove elements from the beginning faster than
+ // array.shift()
+ this.buffer = new BufferList();
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false;
+
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
+
+ // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
+ this.resumeScheduled = false;
+
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
+
+ // when piping, we only care about 'readable' events that happen
+ // after read()ing all the bytes and not getting any pushback.
+ this.ranOut = false;
+
+ // the number of writers that are awaiting a drain event in .pipe()s
+ this.awaitDrain = 0;
+
+ // if true, a maybeReadMore has been scheduled
+ this.readingMore = false;
+
+ this.decoder = null;
+ this.encoding = null;
+ if (options.encoding) {
+ if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
+ }
+}
+
+var Duplex;
+function Readable(options) {
+ Duplex = Duplex || require('./_stream_duplex');
+
+ if (!(this instanceof Readable)) return new Readable(options);
+
+ this._readableState = new ReadableState(options, this);
+
+ // legacy
+ this.readable = true;
+
+ if (options && typeof options.read === 'function') this._read = options.read;
+
+ Stream.call(this);
+}
+
+// Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+Readable.prototype.push = function (chunk, encoding) {
+ var state = this._readableState;
+
+ if (!state.objectMode && typeof chunk === 'string') {
+ encoding = encoding || state.defaultEncoding;
+ if (encoding !== state.encoding) {
+ chunk = bufferShim.from(chunk, encoding);
+ encoding = '';
+ }
+ }
+
+ return readableAddChunk(this, state, chunk, encoding, false);
+};
+
+// Unshift should *always* be something directly out of read()
+Readable.prototype.unshift = function (chunk) {
+ var state = this._readableState;
+ return readableAddChunk(this, state, chunk, '', true);
+};
+
+Readable.prototype.isPaused = function () {
+ return this._readableState.flowing === false;
+};
+
+function readableAddChunk(stream, state, chunk, encoding, addToFront) {
+ var er = chunkInvalid(state, chunk);
+ if (er) {
+ stream.emit('error', er);
+ } else if (chunk === null) {
+ state.reading = false;
+ onEofChunk(stream, state);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (state.ended && !addToFront) {
+ var e = new Error('stream.push() after EOF');
+ stream.emit('error', e);
+ } else if (state.endEmitted && addToFront) {
+ var _e = new Error('stream.unshift() after end event');
+ stream.emit('error', _e);
+ } else {
+ var skipAdd;
+ if (state.decoder && !addToFront && !encoding) {
+ chunk = state.decoder.write(chunk);
+ skipAdd = !state.objectMode && chunk.length === 0;
+ }
+
+ if (!addToFront) state.reading = false;
+
+ // Don't add to the buffer if we've decoded to an empty string chunk and
+ // we're not in object mode
+ if (!skipAdd) {
+ // if we want the data now, just emit it.
+ if (state.flowing && state.length === 0 && !state.sync) {
+ stream.emit('data', chunk);
+ stream.read(0);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
+
+ if (state.needReadable) emitReadable(stream);
+ }
+ }
+
+ maybeReadMore(stream, state);
+ }
+ } else if (!addToFront) {
+ state.reading = false;
+ }
+
+ return needMoreData(state);
+}
+
+// if it's past the high water mark, we can push in some more.
+// Also, if we have no data yet, we can stand some
+// more bytes. This is to work around cases where hwm=0,
+// such as the repl. Also, if the push() triggered a
+// readable event, and the user called read(largeNumber) such that
+// needReadable was set, then we ought to push more, so that another
+// 'readable' event will be triggered.
+function needMoreData(state) {
+ return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
+}
+
+// backwards compatibility.
+Readable.prototype.setEncoding = function (enc) {
+ if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
+ this._readableState.decoder = new StringDecoder(enc);
+ this._readableState.encoding = enc;
+ return this;
+};
+
+// Don't raise the hwm > 8MB
+var MAX_HWM = 0x800000;
+function computeNewHighWaterMark(n) {
+ if (n >= MAX_HWM) {
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2 to prevent increasing hwm excessively in
+ // tiny amounts
+ n--;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ n++;
+ }
+ return n;
+}
+
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function howMuchToRead(n, state) {
+ if (n <= 0 || state.length === 0 && state.ended) return 0;
+ if (state.objectMode) return 1;
+ if (n !== n) {
+ // Only flow one buffer at a time
+ if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
+ }
+ // If we're asking for more than the current hwm, then raise the hwm.
+ if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
+ if (n <= state.length) return n;
+ // Don't have enough
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ }
+ return state.length;
+}
+
+// you can override either this method, or the async _read(n) below.
+Readable.prototype.read = function (n) {
+ debug('read', n);
+ n = parseInt(n, 10);
+ var state = this._readableState;
+ var nOrig = n;
+
+ if (n !== 0) state.emittedReadable = false;
+
+ // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+ if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
+ debug('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
+ return null;
+ }
+
+ n = howMuchToRead(n, state);
+
+ // if we've ended, and we're now clear, then finish it up.
+ if (n === 0 && state.ended) {
+ if (state.length === 0) endReadable(this);
+ return null;
+ }
+
+ // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
+
+ // if we need a readable event, then we need to do some reading.
+ var doRead = state.needReadable;
+ debug('need readable', doRead);
+
+ // if we currently have less than the highWaterMark, then also read some
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug('length less than watermark', doRead);
+ }
+
+ // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug('reading or ended', doRead);
+ } else if (doRead) {
+ debug('do read');
+ state.reading = true;
+ state.sync = true;
+ // if the length is currently zero, then we *need* a readable event.
+ if (state.length === 0) state.needReadable = true;
+ // call internal read method
+ this._read(state.highWaterMark);
+ state.sync = false;
+ // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+ if (!state.reading) n = howMuchToRead(nOrig, state);
+ }
+
+ var ret;
+ if (n > 0) ret = fromList(n, state);else ret = null;
+
+ if (ret === null) {
+ state.needReadable = true;
+ n = 0;
+ } else {
+ state.length -= n;
+ }
+
+ if (state.length === 0) {
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (!state.ended) state.needReadable = true;
+
+ // If we tried to read() past the EOF, then emit end on the next tick.
+ if (nOrig !== n && state.ended) endReadable(this);
+ }
+
+ if (ret !== null) this.emit('data', ret);
+
+ return ret;
+};
+
+function chunkInvalid(state, chunk) {
+ var er = null;
+ if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+ return er;
+}
+
+function onEofChunk(stream, state) {
+ if (state.ended) return;
+ if (state.decoder) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+ state.ended = true;
+
+ // emit 'readable' now to make sure it gets picked up.
+ emitReadable(stream);
+}
+
+// Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+function emitReadable(stream) {
+ var state = stream._readableState;
+ state.needReadable = false;
+ if (!state.emittedReadable) {
+ debug('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
+ }
+}
+
+function emitReadable_(stream) {
+ debug('emit readable');
+ stream.emit('readable');
+ flow(stream);
+}
+
+// at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ processNextTick(maybeReadMore_, stream, state);
+ }
+}
+
+function maybeReadMore_(stream, state) {
+ var len = state.length;
+ while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
+ debug('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length)
+ // didn't get any data, stop spinning.
+ break;else len = state.length;
+ }
+ state.readingMore = false;
+}
+
+// abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+Readable.prototype._read = function (n) {
+ this.emit('error', new Error('not implemented'));
+};
+
+Readable.prototype.pipe = function (dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
+
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+ state.pipesCount += 1;
+ debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
+
+ var endFn = doEnd ? onend : cleanup;
+ if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
+
+ dest.on('unpipe', onunpipe);
+ function onunpipe(readable) {
+ debug('onunpipe');
+ if (readable === src) {
+ cleanup();
+ }
+ }
+
+ function onend() {
+ debug('onend');
+ dest.end();
+ }
+
+ // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
+
+ var cleanedUp = false;
+ function cleanup() {
+ debug('cleanup');
+ // cleanup event handlers once the pipe is broken
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', cleanup);
+ src.removeListener('data', ondata);
+
+ cleanedUp = true;
+
+ // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+ if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
+ }
+
+ // If the user pushes more data while we're writing to dest then we'll end up
+ // in ondata again. However, we only want to increase awaitDrain once because
+ // dest will only emit one 'drain' event for the multiple writes.
+ // => Introduce a guard on increasing awaitDrain.
+ var increasedAwaitDrain = false;
+ src.on('data', ondata);
+ function ondata(chunk) {
+ debug('ondata');
+ increasedAwaitDrain = false;
+ var ret = dest.write(chunk);
+ if (false === ret && !increasedAwaitDrain) {
+ // If the user unpiped during `dest.write()`, it is possible
+ // to get stuck in a permanently paused state if that write
+ // also returned false.
+ // => Check whether `dest` is still a piping destination.
+ if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
+ debug('false write response, pause', src._readableState.awaitDrain);
+ src._readableState.awaitDrain++;
+ increasedAwaitDrain = true;
+ }
+ src.pause();
+ }
+ }
+
+ // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+ function onerror(er) {
+ debug('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
+ }
+
+ // Make sure our error handler is attached before userland ones.
+ prependListener(dest, 'error', onerror);
+
+ // Both close and finish should trigger unpipe, but only once.
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+ dest.once('close', onclose);
+ function onfinish() {
+ debug('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
+ }
+ dest.once('finish', onfinish);
+
+ function unpipe() {
+ debug('unpipe');
+ src.unpipe(dest);
+ }
+
+ // tell the dest that it's being piped to
+ dest.emit('pipe', src);
+
+ // start the flow if it hasn't been started already.
+ if (!state.flowing) {
+ debug('pipe resume');
+ src.resume();
+ }
+
+ return dest;
+};
+
+function pipeOnDrain(src) {
+ return function () {
+ var state = src._readableState;
+ debug('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain) state.awaitDrain--;
+ if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
+ state.flowing = true;
+ flow(src);
+ }
+ };
+}
+
+Readable.prototype.unpipe = function (dest) {
+ var state = this._readableState;
+
+ // if we're not piping anywhere, then do nothing.
+ if (state.pipesCount === 0) return this;
+
+ // just one destination. most common case.
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes) return this;
+
+ if (!dest) dest = state.pipes;
+
+ // got a match.
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest) dest.emit('unpipe', this);
+ return this;
+ }
+
+ // slow case. multiple pipe destinations.
+
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+
+ for (var _i = 0; _i < len; _i++) {
+ dests[_i].emit('unpipe', this);
+ }return this;
+ }
+
+ // try to find the right one.
+ var i = indexOf(state.pipes, dest);
+ if (i === -1) return this;
+
+ state.pipes.splice(i, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1) state.pipes = state.pipes[0];
+
+ dest.emit('unpipe', this);
+
+ return this;
+};
+
+// set up data events if they are asked for
+// Ensure readable listeners eventually get something
+Readable.prototype.on = function (ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
+
+ if (ev === 'data') {
+ // Start flowing on next tick if stream isn't explicitly paused
+ if (this._readableState.flowing !== false) this.resume();
+ } else if (ev === 'readable') {
+ var state = this._readableState;
+ if (!state.endEmitted && !state.readableListening) {
+ state.readableListening = state.needReadable = true;
+ state.emittedReadable = false;
+ if (!state.reading) {
+ processNextTick(nReadingNextTick, this);
+ } else if (state.length) {
+ emitReadable(this, state);
+ }
+ }
+ }
+
+ return res;
+};
+Readable.prototype.addListener = Readable.prototype.on;
+
+function nReadingNextTick(self) {
+ debug('readable nexttick read 0');
+ self.read(0);
+}
+
+// pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+Readable.prototype.resume = function () {
+ var state = this._readableState;
+ if (!state.flowing) {
+ debug('resume');
+ state.flowing = true;
+ resume(this, state);
+ }
+ return this;
+};
+
+function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ processNextTick(resume_, stream, state);
+ }
+}
+
+function resume_(stream, state) {
+ if (!state.reading) {
+ debug('resume read 0');
+ stream.read(0);
+ }
+
+ state.resumeScheduled = false;
+ state.awaitDrain = 0;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading) stream.read(0);
+}
+
+Readable.prototype.pause = function () {
+ debug('call pause flowing=%j', this._readableState.flowing);
+ if (false !== this._readableState.flowing) {
+ debug('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+ return this;
+};
+
+function flow(stream) {
+ var state = stream._readableState;
+ debug('flow', state.flowing);
+ while (state.flowing && stream.read() !== null) {}
+}
+
+// wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+Readable.prototype.wrap = function (stream) {
+ var state = this._readableState;
+ var paused = false;
+
+ var self = this;
+ stream.on('end', function () {
+ debug('wrapped end');
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) self.push(chunk);
+ }
+
+ self.push(null);
+ });
+
+ stream.on('data', function (chunk) {
+ debug('wrapped data');
+ if (state.decoder) chunk = state.decoder.write(chunk);
+
+ // don't skip over falsy values in objectMode
+ if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
+
+ var ret = self.push(chunk);
+ if (!ret) {
+ paused = true;
+ stream.pause();
+ }
+ });
+
+ // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+ for (var i in stream) {
+ if (this[i] === undefined && typeof stream[i] === 'function') {
+ this[i] = function (method) {
+ return function () {
+ return stream[method].apply(stream, arguments);
+ };
+ }(i);
+ }
+ }
+
+ // proxy certain important events.
+ var events = ['error', 'close', 'destroy', 'pause', 'resume'];
+ forEach(events, function (ev) {
+ stream.on(ev, self.emit.bind(self, ev));
+ });
+
+ // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+ self._read = function (n) {
+ debug('wrapped _read', n);
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
+
+ return self;
+};
+
+// exposed for testing purposes only.
+Readable._fromList = fromList;
+
+// Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function fromList(n, state) {
+ // nothing buffered
+ if (state.length === 0) return null;
+
+ var ret;
+ if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
+ // read it all, truncate the list
+ if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
+ state.buffer.clear();
+ } else {
+ // read part of list
+ ret = fromListPartial(n, state.buffer, state.decoder);
+ }
+
+ return ret;
+}
+
+// Extracts only enough buffered data to satisfy the amount requested.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function fromListPartial(n, list, hasStrings) {
+ var ret;
+ if (n < list.head.data.length) {
+ // slice is the same for buffers and strings
+ ret = list.head.data.slice(0, n);
+ list.head.data = list.head.data.slice(n);
+ } else if (n === list.head.data.length) {
+ // first chunk is a perfect match
+ ret = list.shift();
+ } else {
+ // result spans more than one buffer
+ ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
+ }
+ return ret;
+}
+
+// Copies a specified amount of characters from the list of buffered data
+// chunks.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function copyFromBufferString(n, list) {
+ var p = list.head;
+ var c = 1;
+ var ret = p.data;
+ n -= ret.length;
+ while (p = p.next) {
+ var str = p.data;
+ var nb = n > str.length ? str.length : n;
+ if (nb === str.length) ret += str;else ret += str.slice(0, n);
+ n -= nb;
+ if (n === 0) {
+ if (nb === str.length) {
+ ++c;
+ if (p.next) list.head = p.next;else list.head = list.tail = null;
+ } else {
+ list.head = p;
+ p.data = str.slice(nb);
+ }
+ break;
+ }
+ ++c;
+ }
+ list.length -= c;
+ return ret;
+}
+
+// Copies a specified amount of bytes from the list of buffered data chunks.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+function copyFromBuffer(n, list) {
+ var ret = bufferShim.allocUnsafe(n);
+ var p = list.head;
+ var c = 1;
+ p.data.copy(ret);
+ n -= p.data.length;
+ while (p = p.next) {
+ var buf = p.data;
+ var nb = n > buf.length ? buf.length : n;
+ buf.copy(ret, ret.length - n, 0, nb);
+ n -= nb;
+ if (n === 0) {
+ if (nb === buf.length) {
+ ++c;
+ if (p.next) list.head = p.next;else list.head = list.tail = null;
+ } else {
+ list.head = p;
+ p.data = buf.slice(nb);
+ }
+ break;
+ }
+ ++c;
+ }
+ list.length -= c;
+ return ret;
+}
+
+function endReadable(stream) {
+ var state = stream._readableState;
+
+ // If we get here before consuming all the bytes, then that is a
+ // bug in node. Should never happen.
+ if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
+
+ if (!state.endEmitted) {
+ state.ended = true;
+ processNextTick(endReadableNT, state, stream);
+ }
+}
+
+function endReadableNT(state, stream) {
+ // Check that we didn't get one last unshift.
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+ }
+}
+
+function forEach(xs, f) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ f(xs[i], i);
+ }
+}
+
+function indexOf(xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
+ }
+ return -1;
+}
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js
new file mode 100644
index 0000000..dbc996e
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js
@@ -0,0 +1,180 @@
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
+
+'use strict';
+
+module.exports = Transform;
+
+var Duplex = require('./_stream_duplex');
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+util.inherits(Transform, Duplex);
+
+function TransformState(stream) {
+ this.afterTransform = function (er, data) {
+ return afterTransform(stream, er, data);
+ };
+
+ this.needTransform = false;
+ this.transforming = false;
+ this.writecb = null;
+ this.writechunk = null;
+ this.writeencoding = null;
+}
+
+function afterTransform(stream, er, data) {
+ var ts = stream._transformState;
+ ts.transforming = false;
+
+ var cb = ts.writecb;
+
+ if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
+
+ ts.writechunk = null;
+ ts.writecb = null;
+
+ if (data !== null && data !== undefined) stream.push(data);
+
+ cb(er);
+
+ var rs = stream._readableState;
+ rs.reading = false;
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ stream._read(rs.highWaterMark);
+ }
+}
+
+function Transform(options) {
+ if (!(this instanceof Transform)) return new Transform(options);
+
+ Duplex.call(this, options);
+
+ this._transformState = new TransformState(this);
+
+ // when the writable side finishes, then flush out anything remaining.
+ var stream = this;
+
+ // start out asking for a readable event once data is transformed.
+ this._readableState.needReadable = true;
+
+ // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+ this._readableState.sync = false;
+
+ if (options) {
+ if (typeof options.transform === 'function') this._transform = options.transform;
+
+ if (typeof options.flush === 'function') this._flush = options.flush;
+ }
+
+ this.once('prefinish', function () {
+ if (typeof this._flush === 'function') this._flush(function (er) {
+ done(stream, er);
+ });else done(stream);
+ });
+}
+
+Transform.prototype.push = function (chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+};
+
+// This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
+//
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
+//
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+Transform.prototype._transform = function (chunk, encoding, cb) {
+ throw new Error('Not implemented');
+};
+
+Transform.prototype._write = function (chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
+ }
+};
+
+// Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+Transform.prototype._read = function (n) {
+ var ts = this._transformState;
+
+ if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
+ ts.transforming = true;
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
+ }
+};
+
+function done(stream, er) {
+ if (er) return stream.emit('error', er);
+
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+ var ws = stream._writableState;
+ var ts = stream._transformState;
+
+ if (ws.length) throw new Error('Calling transform done when ws.length != 0');
+
+ if (ts.transforming) throw new Error('Calling transform done when still transforming');
+
+ return stream.push(null);
+}
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js
new file mode 100644
index 0000000..ed5efcb
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js
@@ -0,0 +1,526 @@
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, encoding, cb), and it'll handle all
+// the drain event emission and buffering.
+
+'use strict';
+
+module.exports = Writable;
+
+/**/
+var processNextTick = require('process-nextick-args');
+/**/
+
+/**/
+var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
+/**/
+
+Writable.WritableState = WritableState;
+
+/**/
+var util = require('core-util-is');
+util.inherits = require('inherits');
+/**/
+
+/**/
+var internalUtil = {
+ deprecate: require('util-deprecate')
+};
+/**/
+
+/**/
+var Stream;
+(function () {
+ try {
+ Stream = require('st' + 'ream');
+ } catch (_) {} finally {
+ if (!Stream) Stream = require('events').EventEmitter;
+ }
+})();
+/**/
+
+var Buffer = require('buffer').Buffer;
+/**/
+var bufferShim = require('buffer-shims');
+/**/
+
+util.inherits(Writable, Stream);
+
+function nop() {}
+
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
+}
+
+var Duplex;
+function WritableState(options, stream) {
+ Duplex = Duplex || require('./_stream_duplex');
+
+ options = options || {};
+
+ // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+ this.objectMode = !!options.objectMode;
+
+ if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
+
+ // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+ var hwm = options.highWaterMark;
+ var defaultHwm = this.objectMode ? 16 : 16 * 1024;
+ this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
+
+ // cast to ints.
+ this.highWaterMark = ~ ~this.highWaterMark;
+
+ this.needDrain = false;
+ // at the start of calling end()
+ this.ending = false;
+ // when end() has been called, and returned
+ this.ended = false;
+ // when 'finish' is emitted
+ this.finished = false;
+
+ // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode;
+
+ // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+ this.defaultEncoding = options.defaultEncoding || 'utf8';
+
+ // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+ this.length = 0;
+
+ // a flag to see when we're in the middle of a write.
+ this.writing = false;
+
+ // when true all writes will be buffered until .uncork() call
+ this.corked = 0;
+
+ // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+ this.sync = true;
+
+ // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+ this.bufferProcessing = false;
+
+ // the callback that's passed to _write(chunk,cb)
+ this.onwrite = function (er) {
+ onwrite(stream, er);
+ };
+
+ // the callback that the user supplies to write(chunk,encoding,cb)
+ this.writecb = null;
+
+ // the amount that is being written when _write is called.
+ this.writelen = 0;
+
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null;
+
+ // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+ this.pendingcb = 0;
+
+ // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+ this.prefinished = false;
+
+ // True if the error was already emitted and should not be thrown again
+ this.errorEmitted = false;
+
+ // count buffered requests
+ this.bufferedRequestCount = 0;
+
+ // allocate the first CorkedRequest, there is always
+ // one allocated and free to use, and we maintain at most two
+ this.corkedRequestsFree = new CorkedRequest(this);
+}
+
+WritableState.prototype.getBuffer = function writableStateGetBuffer() {
+ var current = this.bufferedRequest;
+ var out = [];
+ while (current) {
+ out.push(current);
+ current = current.next;
+ }
+ return out;
+};
+
+(function () {
+ try {
+ Object.defineProperty(WritableState.prototype, 'buffer', {
+ get: internalUtil.deprecate(function () {
+ return this.getBuffer();
+ }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
+ });
+ } catch (_) {}
+})();
+
+var Duplex;
+function Writable(options) {
+ Duplex = Duplex || require('./_stream_duplex');
+
+ // Writable ctor is applied to Duplexes, though they're not
+ // instanceof Writable, they're instanceof Readable.
+ if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
+
+ this._writableState = new WritableState(options, this);
+
+ // legacy.
+ this.writable = true;
+
+ if (options) {
+ if (typeof options.write === 'function') this._write = options.write;
+
+ if (typeof options.writev === 'function') this._writev = options.writev;
+ }
+
+ Stream.call(this);
+}
+
+// Otherwise people can pipe Writable streams, which is just wrong.
+Writable.prototype.pipe = function () {
+ this.emit('error', new Error('Cannot pipe, not readable'));
+};
+
+function writeAfterEnd(stream, cb) {
+ var er = new Error('write after end');
+ // TODO: defer error events consistently everywhere, not just the cb
+ stream.emit('error', er);
+ processNextTick(cb, er);
+}
+
+// If we get something that is not a buffer, string, null, or undefined,
+// and we're not in objectMode, then that's an error.
+// Otherwise stream chunks are all considered to be of length=1, and the
+// watermarks determine how many objects to keep in the buffer, rather than
+// how many bytes or characters.
+function validChunk(stream, state, chunk, cb) {
+ var valid = true;
+ var er = false;
+ // Always throw error if a null is written
+ // if we are not in object mode then throw
+ // if it is not a buffer, string, or undefined.
+ if (chunk === null) {
+ er = new TypeError('May not write null values to stream');
+ } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
+ er = new TypeError('Invalid non-string/buffer chunk');
+ }
+ if (er) {
+ stream.emit('error', er);
+ processNextTick(cb, er);
+ valid = false;
+ }
+ return valid;
+}
+
+Writable.prototype.write = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
+
+ if (typeof cb !== 'function') cb = nop;
+
+ if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, chunk, encoding, cb);
+ }
+
+ return ret;
+};
+
+Writable.prototype.cork = function () {
+ var state = this._writableState;
+
+ state.corked++;
+};
+
+Writable.prototype.uncork = function () {
+ var state = this._writableState;
+
+ if (state.corked) {
+ state.corked--;
+
+ if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
+ }
+};
+
+Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
+ // node::ParseEncoding() requires lower case.
+ if (typeof encoding === 'string') encoding = encoding.toLowerCase();
+ if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
+ this._writableState.defaultEncoding = encoding;
+ return this;
+};
+
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
+ chunk = bufferShim.from(chunk, encoding);
+ }
+ return chunk;
+}
+
+// if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+function writeOrBuffer(stream, state, chunk, encoding, cb) {
+ chunk = decodeChunk(state, chunk, encoding);
+
+ if (Buffer.isBuffer(chunk)) encoding = 'buffer';
+ var len = state.objectMode ? 1 : chunk.length;
+
+ state.length += len;
+
+ var ret = state.length < state.highWaterMark;
+ // we must ensure that previous needDrain will not be reset to false.
+ if (!ret) state.needDrain = true;
+
+ if (state.writing || state.corked) {
+ var last = state.lastBufferedRequest;
+ state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
+ if (last) {
+ last.next = state.lastBufferedRequest;
+ } else {
+ state.bufferedRequest = state.lastBufferedRequest;
+ }
+ state.bufferedRequestCount += 1;
+ } else {
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ }
+
+ return ret;
+}
+
+function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
+ state.sync = false;
+}
+
+function onwriteError(stream, state, sync, er, cb) {
+ --state.pendingcb;
+ if (sync) processNextTick(cb, er);else cb(er);
+
+ stream._writableState.errorEmitted = true;
+ stream.emit('error', er);
+}
+
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
+
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
+
+ onwriteStateUpdate(state);
+
+ if (er) onwriteError(stream, state, sync, er, cb);else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(state);
+
+ if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
+ clearBuffer(stream, state);
+ }
+
+ if (sync) {
+ /**/
+ asyncWrite(afterWrite, stream, state, finished, cb);
+ /**/
+ } else {
+ afterWrite(stream, state, finished, cb);
+ }
+ }
+}
+
+function afterWrite(stream, state, finished, cb) {
+ if (!finished) onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
+}
+
+// Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
+ }
+}
+
+// if there's something in the buffer waiting, then process it
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
+ var entry = state.bufferedRequest;
+
+ if (stream._writev && entry && entry.next) {
+ // Fast case, write everything using _writev()
+ var l = state.bufferedRequestCount;
+ var buffer = new Array(l);
+ var holder = state.corkedRequestsFree;
+ holder.entry = entry;
+
+ var count = 0;
+ while (entry) {
+ buffer[count] = entry;
+ entry = entry.next;
+ count += 1;
+ }
+
+ doWrite(stream, state, true, state.length, buffer, '', holder.finish);
+
+ // doWrite is almost always async, defer these to save a bit of time
+ // as the hot path ends with doWrite
+ state.pendingcb++;
+ state.lastBufferedRequest = null;
+ if (holder.next) {
+ state.corkedRequestsFree = holder.next;
+ holder.next = null;
+ } else {
+ state.corkedRequestsFree = new CorkedRequest(state);
+ }
+ } else {
+ // Slow case, write chunks one-by-one
+ while (entry) {
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
+
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ entry = entry.next;
+ // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+ if (state.writing) {
+ break;
+ }
+ }
+
+ if (entry === null) state.lastBufferedRequest = null;
+ }
+
+ state.bufferedRequestCount = 0;
+ state.bufferedRequest = entry;
+ state.bufferProcessing = false;
+}
+
+Writable.prototype._write = function (chunk, encoding, cb) {
+ cb(new Error('not implemented'));
+};
+
+Writable.prototype._writev = null;
+
+Writable.prototype.end = function (chunk, encoding, cb) {
+ var state = this._writableState;
+
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
+
+ // .end() fully uncorks
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
+ }
+
+ // ignore unnecessary end() calls.
+ if (!state.ending && !state.finished) endWritable(this, state, cb);
+};
+
+function needFinish(state) {
+ return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
+}
+
+function prefinish(stream, state) {
+ if (!state.prefinished) {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+}
+
+function finishMaybe(stream, state) {
+ var need = needFinish(state);
+ if (need) {
+ if (state.pendingcb === 0) {
+ prefinish(stream, state);
+ state.finished = true;
+ stream.emit('finish');
+ } else {
+ prefinish(stream, state);
+ }
+ }
+ return need;
+}
+
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+ if (cb) {
+ if (state.finished) processNextTick(cb);else stream.once('finish', cb);
+ }
+ state.ended = true;
+ stream.writable = false;
+}
+
+// It seems a linked list but it is not
+// there will be only 2 of these for each stream
+function CorkedRequest(state) {
+ var _this = this;
+
+ this.next = null;
+ this.entry = null;
+
+ this.finish = function (err) {
+ var entry = _this.entry;
+ _this.entry = null;
+ while (entry) {
+ var cb = entry.callback;
+ state.pendingcb--;
+ cb(err);
+ entry = entry.next;
+ }
+ if (state.corkedRequestsFree) {
+ state.corkedRequestsFree.next = _this;
+ } else {
+ state.corkedRequestsFree = _this;
+ }
+ };
+}
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/BufferList.js b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/BufferList.js
new file mode 100644
index 0000000..e4bfcf0
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/BufferList.js
@@ -0,0 +1,64 @@
+'use strict';
+
+var Buffer = require('buffer').Buffer;
+/**/
+var bufferShim = require('buffer-shims');
+/**/
+
+module.exports = BufferList;
+
+function BufferList() {
+ this.head = null;
+ this.tail = null;
+ this.length = 0;
+}
+
+BufferList.prototype.push = function (v) {
+ var entry = { data: v, next: null };
+ if (this.length > 0) this.tail.next = entry;else this.head = entry;
+ this.tail = entry;
+ ++this.length;
+};
+
+BufferList.prototype.unshift = function (v) {
+ var entry = { data: v, next: this.head };
+ if (this.length === 0) this.tail = entry;
+ this.head = entry;
+ ++this.length;
+};
+
+BufferList.prototype.shift = function () {
+ if (this.length === 0) return;
+ var ret = this.head.data;
+ if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
+ --this.length;
+ return ret;
+};
+
+BufferList.prototype.clear = function () {
+ this.head = this.tail = null;
+ this.length = 0;
+};
+
+BufferList.prototype.join = function (s) {
+ if (this.length === 0) return '';
+ var p = this.head;
+ var ret = '' + p.data;
+ while (p = p.next) {
+ ret += s + p.data;
+ }return ret;
+};
+
+BufferList.prototype.concat = function (n) {
+ if (this.length === 0) return bufferShim.alloc(0);
+ if (this.length === 1) return this.head.data;
+ var ret = bufferShim.allocUnsafe(n >>> 0);
+ var p = this.head;
+ var i = 0;
+ while (p) {
+ p.data.copy(ret, i);
+ i += p.data.length;
+ p = p.next;
+ }
+ return ret;
+};
\ No newline at end of file
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/package.json b/node_modules/are-we-there-yet/node_modules/readable-stream/package.json
new file mode 100644
index 0000000..4293090
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "readable-stream",
+ "version": "2.1.5",
+ "description": "Streams3, a user-land copy of the stream library from Node.js",
+ "main": "readable.js",
+ "dependencies": {
+ "buffer-shims": "^1.0.0",
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.1",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~1.0.6",
+ "string_decoder": "~0.10.x",
+ "util-deprecate": "~1.0.1"
+ },
+ "devDependencies": {
+ "assert": "~1.4.0",
+ "babel-polyfill": "^6.9.1",
+ "nyc": "^6.4.0",
+ "tap": "~0.7.1",
+ "tape": "~4.5.1",
+ "zuul": "~3.10.0"
+ },
+ "scripts": {
+ "test": "tap test/parallel/*.js test/ours/*.js",
+ "browser": "npm run write-zuul && zuul --browser-retries 2 -- test/browser.js",
+ "write-zuul": "printf \"ui: tape\nbrowsers:\n - name: $BROWSER_NAME\n version: $BROWSER_VERSION\n\">.zuul.yml",
+ "local": "zuul --local 3000 --no-coverage -- test/browser.js",
+ "cover": "nyc npm test",
+ "report": "nyc report --reporter=lcov"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/nodejs/readable-stream"
+ },
+ "keywords": [
+ "readable",
+ "stream",
+ "pipe"
+ ],
+ "browser": {
+ "util": false
+ },
+ "nyc": {
+ "include": [
+ "lib/**.js"
+ ]
+ },
+ "license": "MIT"
+}
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js b/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js
new file mode 100644
index 0000000..27e8d8a
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/passthrough.js
@@ -0,0 +1 @@
+module.exports = require("./lib/_stream_passthrough.js")
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js b/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js
new file mode 100644
index 0000000..be2688a
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/readable.js
@@ -0,0 +1,16 @@
+var Stream = (function (){
+ try {
+ return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
+ } catch(_){}
+}());
+exports = module.exports = require('./lib/_stream_readable.js');
+exports.Stream = Stream || exports;
+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' && Stream) {
+ module.exports = Stream;
+}
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js b/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js
new file mode 100644
index 0000000..5d482f0
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/transform.js
@@ -0,0 +1 @@
+module.exports = require("./lib/_stream_transform.js")
diff --git a/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js b/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js
new file mode 100644
index 0000000..e1e9efd
--- /dev/null
+++ b/node_modules/are-we-there-yet/node_modules/readable-stream/writable.js
@@ -0,0 +1 @@
+module.exports = require("./lib/_stream_writable.js")
diff --git a/node_modules/are-we-there-yet/package.json b/node_modules/are-we-there-yet/package.json
new file mode 100644
index 0000000..3b77c6b
--- /dev/null
+++ b/node_modules/are-we-there-yet/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "are-we-there-yet",
+ "version": "1.1.2",
+ "description": "Keep track of the overall completion of many dispirate processes",
+ "main": "index.js",
+ "scripts": {
+ "test": "standard && tap test/*.js"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/iarna/are-we-there-yet.git"
+ },
+ "author": "Rebecca Turner (http://re-becca.org)",
+ "license": "ISC",
+ "bugs": {
+ "url": "https://github.com/iarna/are-we-there-yet/issues"
+ },
+ "homepage": "https://github.com/iarna/are-we-there-yet",
+ "devDependencies": {
+ "standard": "^6.0.8",
+ "tap": "^5.7.0"
+ },
+ "dependencies": {
+ "delegates": "^1.0.0",
+ "readable-stream": "^2.0.0 || ^1.1.13"
+ }
+}
diff --git a/node_modules/are-we-there-yet/test/lib/test-event.js b/node_modules/are-we-there-yet/test/lib/test-event.js
new file mode 100644
index 0000000..2aa7c05
--- /dev/null
+++ b/node_modules/are-we-there-yet/test/lib/test-event.js
@@ -0,0 +1,29 @@
+'use strict'
+var util = require('util')
+
+module.exports = function (obj, event, next) {
+ var timeout = setTimeout(gotTimeout, 10)
+ obj.once(event, gotResult)
+
+ function gotTimeout () {
+ obj.removeListener(event, gotResult)
+ next(new Error('Timeout listening for ' + event))
+ }
+ var result = []
+ function gotResult () {
+ result = Array.prototype.slice.call(arguments)
+ clearTimeout(timeout)
+ timeout = setTimeout(gotNoMoreResults, 10)
+ obj.once(event, gotTooManyResults)
+ }
+ function gotNoMoreResults () {
+ obj.removeListener(event, gotTooManyResults)
+ var args = [null].concat(result)
+ next.apply(null, args)
+ }
+ function gotTooManyResults () {
+ var secondResult = Array.prototype.slice.call(arguments)
+ clearTimeout(timeout)
+ next(new Error('Got too many results, first ' + util.inspect(result) + ' and then ' + util.inspect(secondResult)))
+ }
+}
diff --git a/node_modules/are-we-there-yet/test/tracker.js b/node_modules/are-we-there-yet/test/tracker.js
new file mode 100644
index 0000000..374c773
--- /dev/null
+++ b/node_modules/are-we-there-yet/test/tracker.js
@@ -0,0 +1,57 @@
+'use strict'
+var test = require('tap').test
+var Tracker = require('../index.js').Tracker
+
+var testEvent = require('./lib/test-event.js')
+
+var name = 'test'
+
+test('initialization', function (t) {
+ var simple = new Tracker(name)
+
+ t.is(simple.completed(), 0, 'Nothing todo is 0 completion')
+ t.done()
+})
+
+var track
+var todo = 100
+test('completion', function (t) {
+ track = new Tracker(name, todo)
+ t.is(track.completed(), 0, 'Nothing done is 0 completion')
+
+ testEvent(track, 'change', afterCompleteWork)
+
+ track.completeWork(todo)
+ t.is(track.completed(), 1, 'completeWork: 100% completed')
+
+ function afterCompleteWork (er, onChangeName) {
+ t.is(er, null, 'completeWork: on change event fired')
+ t.is(onChangeName, name, 'completeWork: on change emits the correct name')
+ t.done()
+ }
+})
+
+test('add more work', function (t) {
+ testEvent(track, 'change', afterAddWork)
+ track.addWork(todo)
+ t.is(track.completed(), 0.5, 'addWork: 50% completed')
+ function afterAddWork (er, onChangeName) {
+ t.is(er, null, 'addWork: on change event fired')
+ t.is(onChangeName, name, 'addWork: on change emits the correct name')
+ t.done()
+ }
+})
+
+test('complete more work', function (t) {
+ track.completeWork(200)
+ t.is(track.completed(), 1, 'completeWork: Over completion is still only 100% complete')
+ t.done()
+})
+
+test('finish is always 100%', function (t) {
+ var finishtest = new Tracker(name, todo)
+ finishtest.completeWork(50)
+ finishtest.finish()
+ t.is(finishtest.completed(), 1, 'finish: Explicitly finishing moves to 100%')
+ t.done()
+})
diff --git a/node_modules/are-we-there-yet/test/trackergroup.js b/node_modules/are-we-there-yet/test/trackergroup.js
new file mode 100644
index 0000000..799a767
--- /dev/null
+++ b/node_modules/are-we-there-yet/test/trackergroup.js
@@ -0,0 +1,96 @@
+'use strict'
+var test = require('tap').test
+var TrackerGroup = require('../index.js').TrackerGroup
+var testEvent = require('./lib/test-event.js')
+
+test('TrackerGroup', function (t) {
+ var name = 'test'
+
+ var track = new TrackerGroup(name)
+ t.is(track.completed(), 0, 'Nothing todo is 0 completion')
+ testEvent(track, 'change', afterFinishEmpty)
+ track.finish()
+ var a, b
+ function afterFinishEmpty (er, onChangeName, completion) {
+ t.is(er, null, 'finishEmpty: on change event fired')
+ t.is(onChangeName, name, 'finishEmpty: on change emits the correct name')
+ t.is(completion, 1, 'finishEmpty: passed through completion was correct')
+ t.is(track.completed(), 1, 'finishEmpty: Finishing an empty group actually finishes it')
+
+ track = new TrackerGroup(name)
+ a = track.newItem('a', 10, 1)
+ b = track.newItem('b', 10, 1)
+ t.is(track.completed(), 0, 'Initially empty')
+ testEvent(track, 'change', afterCompleteWork)
+ a.completeWork(5)
+ }
+ function afterCompleteWork (er, onChangeName, completion) {
+ t.is(er, null, 'on change event fired')
+ t.is(onChangeName, 'a', 'on change emits the correct name')
+ t.is(completion, 0.25, 'Complete half of one is a quarter overall')
+ t.is(track.completed(), 0.25, 'Complete half of one is a quarter overall')
+ testEvent(track, 'change', afterFinishAll)
+ track.finish()
+ }
+ function afterFinishAll (er, onChangeName, completion) {
+ t.is(er, null, 'finishAll: on change event fired')
+ t.is(onChangeName, name, 'finishAll: on change emits the correct name')
+ t.is(completion, 1, 'Finishing everything ')
+ t.is(track.completed(), 1, 'Finishing everything ')
+
+ track = new TrackerGroup(name)
+ a = track.newItem('a', 10, 2)
+ b = track.newItem('b', 10, 1)
+ t.is(track.completed(), 0, 'weighted: Initially empty')
+ testEvent(track, 'change', afterWeightedCompleteWork)
+ a.completeWork(5)
+ }
+ function afterWeightedCompleteWork (er, onChangeName, completion) {
+ t.is(er, null, 'weighted: on change event fired')
+ t.is(onChangeName, 'a', 'weighted: on change emits the correct name')
+ t.is(Math.floor(completion * 100), 33, 'weighted: Complete half of double weighted')
+ t.is(Math.floor(track.completed() * 100), 33, 'weighted: Complete half of double weighted')
+ testEvent(track, 'change', afterWeightedFinishAll)
+ track.finish()
+ }
+ function afterWeightedFinishAll (er, onChangeName, completion) {
+ t.is(er, null, 'weightedFinishAll: on change event fired')
+ t.is(onChangeName, name, 'weightedFinishAll: on change emits the correct name')
+ t.is(completion, 1, 'weightedFinishaAll: Finishing everything ')
+ t.is(track.completed(), 1, 'weightedFinishaAll: Finishing everything ')
+
+ track = new TrackerGroup(name)
+ a = track.newGroup('a', 10)
+ b = track.newGroup('b', 10)
+ var a1 = a.newItem('a.1', 10)
+ a1.completeWork(5)
+ t.is(track.completed(), 0.25, 'nested: Initially quarter done')
+ testEvent(track, 'change', afterNestedComplete)
+ b.finish()
+ }
+ function afterNestedComplete (er, onChangeName, completion) {
+ t.is(er, null, 'nestedComplete: on change event fired')
+ t.is(onChangeName, 'b', 'nestedComplete: on change emits the correct name')
+ t.is(completion, 0.75, 'nestedComplete: Finishing everything ')
+ t.is(track.completed(), 0.75, 'nestedComplete: Finishing everything ')
+ t.end()
+ }
+})
+
+test('cycles', function (t) {
+ var track = new TrackerGroup('top')
+ testCycle(track, track)
+ var layer1 = track.newGroup('layer1')
+ testCycle(layer1, track)
+ t.end()
+
+ function testCycle (addTo, toAdd) {
+ try {
+ addTo.addUnit(toAdd)
+ t.fail(toAdd.name)
+ } catch (ex) {
+ console.log(ex)
+ t.pass(toAdd.name)
+ }
+ }
+})
diff --git a/node_modules/are-we-there-yet/test/trackerstream.js b/node_modules/are-we-there-yet/test/trackerstream.js
new file mode 100644
index 0000000..65f04b0
--- /dev/null
+++ b/node_modules/are-we-there-yet/test/trackerstream.js
@@ -0,0 +1,51 @@
+'use strict'
+var test = require('tap').test
+var util = require('util')
+var stream = require('readable-stream')
+var TrackerStream = require('../index.js').TrackerStream
+var testEvent = require('./lib/test-event.js')
+
+var Sink = function () {
+ stream.Writable.apply(this, arguments)
+}
+util.inherits(Sink, stream.Writable)
+Sink.prototype._write = function (data, encoding, cb) {
+ cb()
+}
+
+test('TrackerStream', function (t) {
+ t.plan(9)
+
+ var name = 'test'
+ var track = new TrackerStream(name)
+
+ t.is(track.completed(), 0, 'Nothing todo is 0 completion')
+
+ var todo = 10
+ track = new TrackerStream(name, todo)
+ t.is(track.completed(), 0, 'Nothing done is 0 completion')
+
+ track.pipe(new Sink())
+
+ testEvent(track, 'change', afterCompleteWork)
+ track.write('0123456789')
+ function afterCompleteWork (er, onChangeName) {
+ t.is(er, null, 'write: on change event fired')
+ t.is(onChangeName, name, 'write: on change emits the correct name')
+ t.is(track.completed(), 1, 'write: 100% completed')
+
+ testEvent(track, 'change', afterAddWork)
+ track.addWork(10)
+ }
+ function afterAddWork (er, onChangeName) {
+ t.is(er, null, 'addWork: on change event fired')
+ t.is(track.completed(), 0.5, 'addWork: 50% completed')
+
+ testEvent(track, 'change', afterAllWork)
+ track.write('ABCDEFGHIJKLMNOPQRST')
+ }
+ function afterAllWork (er) {
+ t.is(er, null, 'allWork: on change event fired')
+ t.is(track.completed(), 1, 'allWork: 100% completed')
+ }
+})
diff --git a/node_modules/are-we-there-yet/tracker-base.js b/node_modules/are-we-there-yet/tracker-base.js
new file mode 100644
index 0000000..6f43687
--- /dev/null
+++ b/node_modules/are-we-there-yet/tracker-base.js
@@ -0,0 +1,11 @@
+'use strict'
+var EventEmitter = require('events').EventEmitter
+var util = require('util')
+
+var trackerId = 0
+var TrackerBase = module.exports = function (name) {
+ EventEmitter.call(this)
+ this.id = ++trackerId
+ this.name = name
+}
+util.inherits(TrackerBase, EventEmitter)
diff --git a/node_modules/are-we-there-yet/tracker-group.js b/node_modules/are-we-there-yet/tracker-group.js
new file mode 100644
index 0000000..9759e12
--- /dev/null
+++ b/node_modules/are-we-there-yet/tracker-group.js
@@ -0,0 +1,107 @@
+'use strict'
+var util = require('util')
+var TrackerBase = require('./tracker-base.js')
+var Tracker = require('./tracker.js')
+var TrackerStream = require('./tracker-stream.js')
+
+var TrackerGroup = module.exports = function (name) {
+ TrackerBase.call(this, name)
+ this.parentGroup = null
+ this.trackers = []
+ this.completion = {}
+ this.weight = {}
+ this.totalWeight = 0
+ this.finished = false
+ this.bubbleChange = bubbleChange(this)
+}
+util.inherits(TrackerGroup, TrackerBase)
+
+function bubbleChange (trackerGroup) {
+ return function (name, completed, tracker) {
+ trackerGroup.completion[tracker.id] = completed
+ if (trackerGroup.finished) return
+ trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup)
+ }
+}
+
+TrackerGroup.prototype.nameInTree = function () {
+ var names = []
+ var from = this
+ while (from) {
+ names.unshift(from.name)
+ from = from.parentGroup
+ }
+ return names.join('/')
+}
+
+TrackerGroup.prototype.addUnit = function (unit, weight) {
+ if (unit.addUnit) {
+ var toTest = this
+ while (toTest) {
+ if (unit === toTest) {
+ throw new Error(
+ 'Attempted to add tracker group ' +
+ unit.name + ' to tree that already includes it ' +
+ this.nameInTree(this))
+ }
+ toTest = toTest.parentGroup
+ }
+ unit.parentGroup = this
+ }
+ this.weight[unit.id] = weight || 1
+ this.totalWeight += this.weight[unit.id]
+ this.trackers.push(unit)
+ this.completion[unit.id] = unit.completed()
+ unit.on('change', this.bubbleChange)
+ if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit)
+ return unit
+}
+
+TrackerGroup.prototype.completed = function () {
+ if (this.trackers.length === 0) return 0
+ var valPerWeight = 1 / this.totalWeight
+ var completed = 0
+ for (var ii = 0; ii < this.trackers.length; ii++) {
+ var trackerId = this.trackers[ii].id
+ completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId]
+ }
+ return completed
+}
+
+TrackerGroup.prototype.newGroup = function (name, weight) {
+ return this.addUnit(new TrackerGroup(name), weight)
+}
+
+TrackerGroup.prototype.newItem = function (name, todo, weight) {
+ return this.addUnit(new Tracker(name, todo), weight)
+}
+
+TrackerGroup.prototype.newStream = function (name, todo, weight) {
+ return this.addUnit(new TrackerStream(name, todo), weight)
+}
+
+TrackerGroup.prototype.finish = function () {
+ this.finished = true
+ if (!this.trackers.length) this.addUnit(new Tracker(), 1, true)
+ for (var ii = 0; ii < this.trackers.length; ii++) {
+ var tracker = this.trackers[ii]
+ tracker.finish()
+ tracker.removeListener('change', this.bubbleChange)
+ }
+ this.emit('change', this.name, 1, this)
+}
+
+var buffer = ' '
+TrackerGroup.prototype.debug = function (depth) {
+ depth = depth || 0
+ var indent = depth ? buffer.substr(0, depth) : ''
+ var output = indent + (this.name || 'top') + ': ' + this.completed() + '\n'
+ this.trackers.forEach(function (tracker) {
+ if (tracker instanceof TrackerGroup) {
+ output += tracker.debug(depth + 1)
+ } else {
+ output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\n'
+ }
+ })
+ return output
+}
diff --git a/node_modules/are-we-there-yet/tracker-stream.js b/node_modules/are-we-there-yet/tracker-stream.js
new file mode 100644
index 0000000..fb9598e
--- /dev/null
+++ b/node_modules/are-we-there-yet/tracker-stream.js
@@ -0,0 +1,35 @@
+'use strict'
+var util = require('util')
+var stream = require('readable-stream')
+var delegate = require('delegates')
+var Tracker = require('./tracker.js')
+
+var TrackerStream = module.exports = function (name, size, options) {
+ stream.Transform.call(this, options)
+ this.tracker = new Tracker(name, size)
+ this.name = name
+ this.id = this.tracker.id
+ this.tracker.on('change', delegateChange(this))
+}
+util.inherits(TrackerStream, stream.Transform)
+
+function delegateChange (trackerStream) {
+ return function (name, completion, tracker) {
+ trackerStream.emit('change', name, completion, trackerStream)
+ }
+}
+
+TrackerStream.prototype._transform = function (data, encoding, cb) {
+ this.tracker.completeWork(data.length ? data.length : 1)
+ this.push(data)
+ cb()
+}
+
+TrackerStream.prototype._flush = function (cb) {
+ this.tracker.finish()
+ cb()
+}
+
+delegate(TrackerStream.prototype, 'tracker')
+ .method('completed')
+ .method('addWork')
diff --git a/node_modules/are-we-there-yet/tracker.js b/node_modules/are-we-there-yet/tracker.js
new file mode 100644
index 0000000..68c2339
--- /dev/null
+++ b/node_modules/are-we-there-yet/tracker.js
@@ -0,0 +1,30 @@
+'use strict'
+var util = require('util')
+var TrackerBase = require('./tracker-base.js')
+
+var Tracker = module.exports = function (name, todo) {
+ TrackerBase.call(this, name)
+ this.workDone = 0
+ this.workTodo = todo || 0
+}
+util.inherits(Tracker, TrackerBase)
+
+Tracker.prototype.completed = function () {
+ return this.workTodo === 0 ? 0 : this.workDone / this.workTodo
+}
+
+Tracker.prototype.addWork = function (work) {
+ this.workTodo += work
+ this.emit('change', this.name, this.completed(), this)
+}
+
+Tracker.prototype.completeWork = function (work) {
+ this.workDone += work
+ if (this.workDone > this.workTodo) this.workDone = this.workTodo
+ this.emit('change', this.name, this.completed(), this)
+}
+
+Tracker.prototype.finish = function () {
+ this.workTodo = this.workDone = 1
+ this.emit('change', this.name, 1, this)
+}
diff --git a/node_modules/arr-diff/LICENSE b/node_modules/arr-diff/LICENSE
new file mode 100755
index 0000000..fa30c4c
--- /dev/null
+++ b/node_modules/arr-diff/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2015, Jon Schlinkert.
+
+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/arr-diff/README.md b/node_modules/arr-diff/README.md
new file mode 100644
index 0000000..7705c6c
--- /dev/null
+++ b/node_modules/arr-diff/README.md
@@ -0,0 +1,74 @@
+# arr-diff [![NPM version](https://img.shields.io/npm/v/arr-diff.svg)](https://www.npmjs.com/package/arr-diff) [![Build Status](https://img.shields.io/travis/jonschlinkert/base.svg)](https://travis-ci.org/jonschlinkert/base)
+
+> Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.
+
+## Install
+
+Install with [npm](https://www.npmjs.com/)
+
+```sh
+$ npm i arr-diff --save
+```
+Install with [bower](http://bower.io/)
+
+```sh
+$ bower install arr-diff --save
+```
+
+## API
+
+### [diff](index.js#L33)
+
+Return the difference between the first array and additional arrays.
+
+**Params**
+
+* `a` **{Array}**
+* `b` **{Array}**
+* `returns` **{Array}**
+
+**Example**
+
+```js
+var diff = require('arr-diff');
+
+var a = ['a', 'b', 'c', 'd'];
+var b = ['b', 'c'];
+
+console.log(diff(a, b))
+//=> ['a', 'd']
+```
+
+## Related projects
+
+* [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten)
+* [array-filter](https://www.npmjs.com/package/array-filter): Array#filter for older browsers. | [homepage](https://github.com/juliangruber/array-filter)
+* [array-intersection](https://www.npmjs.com/package/array-intersection): Return an array with the unique values present in _all_ given arrays using strict equality… [more](https://www.npmjs.com/package/array-intersection) | [homepage](https://github.com/jonschlinkert/array-intersection)
+
+## Running tests
+
+Install dev dependencies:
+
+```sh
+$ npm i -d && npm test
+```
+
+## Contributing
+
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/arr-diff/issues/new).
+
+## Author
+
+**Jon Schlinkert**
+
++ [github/jonschlinkert](https://github.com/jonschlinkert)
++ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+
+Copyright © 2015 [Jon Schlinkert](https://github.com/jonschlinkert)
+Released under the MIT license.
+
+***
+
+_This file was generated by [verb](https://github.com/verbose/verb) on Sat Dec 05 2015 23:24:53 GMT-0500 (EST)._
diff --git a/node_modules/arr-diff/index.js b/node_modules/arr-diff/index.js
new file mode 100644
index 0000000..bc7200d
--- /dev/null
+++ b/node_modules/arr-diff/index.js
@@ -0,0 +1,58 @@
+/*!
+ * arr-diff
+ *
+ * Copyright (c) 2014 Jon Schlinkert, contributors.
+ * Licensed under the MIT License
+ */
+
+'use strict';
+
+var flatten = require('arr-flatten');
+var slice = [].slice;
+
+/**
+ * Return the difference between the first array and
+ * additional arrays.
+ *
+ * ```js
+ * var diff = require('{%= name %}');
+ *
+ * var a = ['a', 'b', 'c', 'd'];
+ * var b = ['b', 'c'];
+ *
+ * console.log(diff(a, b))
+ * //=> ['a', 'd']
+ * ```
+ *
+ * @param {Array} `a`
+ * @param {Array} `b`
+ * @return {Array}
+ * @api public
+ */
+
+function diff(arr, arrays) {
+ var argsLen = arguments.length;
+ var len = arr.length, i = -1;
+ var res = [], arrays;
+
+ if (argsLen === 1) {
+ return arr;
+ }
+
+ if (argsLen > 2) {
+ arrays = flatten(slice.call(arguments, 1));
+ }
+
+ while (++i < len) {
+ if (!~arrays.indexOf(arr[i])) {
+ res.push(arr[i]);
+ }
+ }
+ return res;
+}
+
+/**
+ * Expose `diff`
+ */
+
+module.exports = diff;
diff --git a/node_modules/arr-diff/package.json b/node_modules/arr-diff/package.json
new file mode 100644
index 0000000..d40c210
--- /dev/null
+++ b/node_modules/arr-diff/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "arr-diff",
+ "description": "Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.",
+ "version": "2.0.0",
+ "homepage": "https://github.com/jonschlinkert/arr-diff",
+ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
+ "repository": "jonschlinkert/arr-diff",
+ "bugs": {
+ "url": "https://github.com/jonschlinkert/arr-diff/issues"
+ },
+ "license": "MIT",
+ "files": [
+ "index.js"
+ ],
+ "main": "index.js",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "mocha"
+ },
+ "dependencies": {
+ "arr-flatten": "^1.0.1"
+ },
+ "devDependencies": {
+ "array-differ": "^1.0.0",
+ "array-slice": "^0.2.3",
+ "benchmarked": "^0.1.4",
+ "chalk": "^1.1.1",
+ "mocha": "*",
+ "should": "*"
+ },
+ "keywords": [
+ "arr",
+ "array",
+ "diff",
+ "differ",
+ "difference"
+ ],
+ "verb": {
+ "related": {
+ "list": [
+ "arr-flatten",
+ "array-filter",
+ "array-intersection"
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/node_modules/arr-flatten/LICENSE b/node_modules/arr-flatten/LICENSE
new file mode 100755
index 0000000..fa30c4c
--- /dev/null
+++ b/node_modules/arr-flatten/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2015, Jon Schlinkert.
+
+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/arr-flatten/README.md b/node_modules/arr-flatten/README.md
new file mode 100755
index 0000000..bd696e6
--- /dev/null
+++ b/node_modules/arr-flatten/README.md
@@ -0,0 +1,73 @@
+# arr-flatten [![NPM version](https://badge.fury.io/js/arr-flatten.svg)](http://badge.fury.io/js/arr-flatten) [![Build Status](https://travis-ci.org/jonschlinkert/arr-flatten.svg)](https://travis-ci.org/jonschlinkert/arr-flatten)
+
+> Recursively flatten an array or arrays. This is the fastest implementation of array flatten.
+
+Why another flatten utility? I wanted the fastest implementation I could find, with implementation choices that should work for 95% of use cases, but no cruft to cover the other 5%.
+
+## Run benchmarks
+
+```bash
+npm run benchmarks
+```
+
+Benchmark results comparing this library to [array-flatten]:
+
+```bash
+#1: large.js
+ arr-flatten.js x 487,030 ops/sec ±0.67% (92 runs sampled)
+ array-flatten.js x 347,020 ops/sec ±0.57% (98 runs sampled)
+
+#2: medium.js
+ arr-flatten.js x 1,914,516 ops/sec ±0.76% (94 runs sampled)
+ array-flatten.js x 1,391,661 ops/sec ±0.63% (96 runs sampled)
+
+#3: small.js
+ arr-flatten.js x 5,158,980 ops/sec ±0.85% (94 runs sampled)
+ array-flatten.js x 3,683,173 ops/sec ±0.79% (97 runs sampled)
+```
+
+## Run tests
+
+Install dev dependencies:
+
+```bash
+npm i -d && npm test
+```
+
+## Install with [npm](npmjs.org)
+
+```bash
+npm i arr-flatten --save
+```
+### Install with [bower](https://github.com/bower/bower)
+
+```bash
+bower install arr-flatten --save
+```
+
+
+## Usage
+
+```js
+var flatten = require('arr-flatten');
+
+flatten(['a', ['b', ['c']], 'd', ['e']]);
+//=> ['a', 'b', 'c', 'd', 'e']
+```
+
+## Author
+
+**Jon Schlinkert**
+
++ [github/jonschlinkert](https://github.com/jonschlinkert)
++ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+Copyright (c) 2014-2015 Jon Schlinkert
+Released under the MIT license
+
+***
+
+_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on March 11, 2015._
+
+[array-flatten]: https://github.com/blakeembrey/array-flatten
\ No newline at end of file
diff --git a/node_modules/arr-flatten/index.js b/node_modules/arr-flatten/index.js
new file mode 100755
index 0000000..f74e48c
--- /dev/null
+++ b/node_modules/arr-flatten/index.js
@@ -0,0 +1,27 @@
+/*!
+ * arr-flatten
+ *
+ * Copyright (c) 2014-2015, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+
+'use strict';
+
+module.exports = function flatten(arr) {
+ return flat(arr, []);
+};
+
+function flat(arr, res) {
+ var len = arr.length;
+ var i = -1;
+
+ while (len--) {
+ var cur = arr[++i];
+ if (Array.isArray(cur)) {
+ flat(cur, res);
+ } else {
+ res.push(cur);
+ }
+ }
+ return res;
+}
\ No newline at end of file
diff --git a/node_modules/arr-flatten/package.json b/node_modules/arr-flatten/package.json
new file mode 100755
index 0000000..8d0322d
--- /dev/null
+++ b/node_modules/arr-flatten/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "arr-flatten",
+ "description": "Recursively flatten an array or arrays. This is the fastest implementation of array flatten.",
+ "version": "1.0.1",
+ "homepage": "https://github.com/jonschlinkert/arr-flatten",
+ "author": {
+ "name": "Jon Schlinkert",
+ "url": "https://github.com/jonschlinkert"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jonschlinkert/arr-flatten.git"
+ },
+ "bugs": {
+ "url": "https://github.com/jonschlinkert/arr-flatten/issues"
+ },
+ "license": {
+ "type": "MIT",
+ "url": "https://github.com/jonschlinkert/arr-flatten/blob/master/LICENSE"
+ },
+ "files": [
+ "index.js"
+ ],
+ "main": "index.js",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "mocha",
+ "benchmarks": "node benchmark"
+ },
+ "devDependencies": {
+ "array-flatten": "^1.0.2",
+ "array-slice": "^0.2.2",
+ "benchmarked": "^0.1.3",
+ "chalk": "^0.5.1",
+ "glob": "^4.3.5",
+ "kind-of": "^1.0.0"
+ },
+ "keywords": [
+ "arr",
+ "array",
+ "elements",
+ "flat",
+ "flatten",
+ "nested",
+ "recurse",
+ "recursive",
+ "recursively"
+ ]
+}
diff --git a/node_modules/array-flatten/LICENSE b/node_modules/array-flatten/LICENSE
new file mode 100644
index 0000000..983fbe8
--- /dev/null
+++ b/node_modules/array-flatten/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/array-flatten/README.md b/node_modules/array-flatten/README.md
new file mode 100644
index 0000000..91fa5b6
--- /dev/null
+++ b/node_modules/array-flatten/README.md
@@ -0,0 +1,43 @@
+# Array Flatten
+
+[![NPM version][npm-image]][npm-url]
+[![NPM downloads][downloads-image]][downloads-url]
+[![Build status][travis-image]][travis-url]
+[![Test coverage][coveralls-image]][coveralls-url]
+
+> Flatten an array of nested arrays into a single flat array. Accepts an optional depth.
+
+## Installation
+
+```
+npm install array-flatten --save
+```
+
+## Usage
+
+```javascript
+var flatten = require('array-flatten')
+
+flatten([1, [2, [3, [4, [5], 6], 7], 8], 9])
+//=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2)
+//=> [1, 2, 3, [4, [5], 6], 7, 8, 9]
+
+(function () {
+ flatten(arguments) //=> [1, 2, 3]
+})(1, [2, 3])
+```
+
+## License
+
+MIT
+
+[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat
+[npm-url]: https://npmjs.org/package/array-flatten
+[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat
+[downloads-url]: https://npmjs.org/package/array-flatten
+[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat
+[travis-url]: https://travis-ci.org/blakeembrey/array-flatten
+[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat
+[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master
diff --git a/node_modules/array-flatten/array-flatten.js b/node_modules/array-flatten/array-flatten.js
new file mode 100644
index 0000000..089117b
--- /dev/null
+++ b/node_modules/array-flatten/array-flatten.js
@@ -0,0 +1,64 @@
+'use strict'
+
+/**
+ * Expose `arrayFlatten`.
+ */
+module.exports = arrayFlatten
+
+/**
+ * Recursive flatten function with depth.
+ *
+ * @param {Array} array
+ * @param {Array} result
+ * @param {Number} depth
+ * @return {Array}
+ */
+function flattenWithDepth (array, result, depth) {
+ for (var i = 0; i < array.length; i++) {
+ var value = array[i]
+
+ if (depth > 0 && Array.isArray(value)) {
+ flattenWithDepth(value, result, depth - 1)
+ } else {
+ result.push(value)
+ }
+ }
+
+ return result
+}
+
+/**
+ * Recursive flatten function. Omitting depth is slightly faster.
+ *
+ * @param {Array} array
+ * @param {Array} result
+ * @return {Array}
+ */
+function flattenForever (array, result) {
+ for (var i = 0; i < array.length; i++) {
+ var value = array[i]
+
+ if (Array.isArray(value)) {
+ flattenForever(value, result)
+ } else {
+ result.push(value)
+ }
+ }
+
+ return result
+}
+
+/**
+ * Flatten an array, with the ability to define a depth.
+ *
+ * @param {Array} array
+ * @param {Number} depth
+ * @return {Array}
+ */
+function arrayFlatten (array, depth) {
+ if (depth == null) {
+ return flattenForever(array, [])
+ }
+
+ return flattenWithDepth(array, [], depth)
+}
diff --git a/node_modules/array-flatten/package.json b/node_modules/array-flatten/package.json
new file mode 100644
index 0000000..1a24e2a
--- /dev/null
+++ b/node_modules/array-flatten/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "array-flatten",
+ "version": "1.1.1",
+ "description": "Flatten an array of nested arrays into a single flat array",
+ "main": "array-flatten.js",
+ "files": [
+ "array-flatten.js",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "istanbul cover _mocha -- -R spec"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/blakeembrey/array-flatten.git"
+ },
+ "keywords": [
+ "array",
+ "flatten",
+ "arguments",
+ "depth"
+ ],
+ "author": {
+ "name": "Blake Embrey",
+ "email": "hello@blakeembrey.com",
+ "url": "http://blakeembrey.me"
+ },
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/blakeembrey/array-flatten/issues"
+ },
+ "homepage": "https://github.com/blakeembrey/array-flatten",
+ "devDependencies": {
+ "istanbul": "^0.3.13",
+ "mocha": "^2.2.4",
+ "pre-commit": "^1.0.7",
+ "standard": "^3.7.3"
+ }
+}
diff --git a/node_modules/array-unique/LICENSE b/node_modules/array-unique/LICENSE
new file mode 100755
index 0000000..fa30c4c
--- /dev/null
+++ b/node_modules/array-unique/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2015, Jon Schlinkert.
+
+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/array-unique/README.md b/node_modules/array-unique/README.md
new file mode 100755
index 0000000..2e28774
--- /dev/null
+++ b/node_modules/array-unique/README.md
@@ -0,0 +1,51 @@
+# array-unique [![NPM version](https://badge.fury.io/js/array-unique.svg)](http://badge.fury.io/js/array-unique) [![Build Status](https://travis-ci.org/jonschlinkert/array-unique.svg)](https://travis-ci.org/jonschlinkert/array-unique)
+
+> Return an array free of duplicate values. Fastest ES5 implementation.
+
+## Install with [npm](npmjs.org)
+
+```bash
+npm i array-unique --save
+```
+
+## Usage
+
+```js
+var unique = require('array-unique');
+
+unique(['a', 'b', 'c', 'c']);
+//=> ['a', 'b', 'c']
+```
+
+## Related
+* [arr-diff](https://github.com/jonschlinkert/arr-diff): Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.
+* [arr-union](https://github.com/jonschlinkert/arr-union): Returns an array of unique values using strict equality for comparisons.
+* [arr-flatten](https://github.com/jonschlinkert/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten.
+* [arr-reduce](https://github.com/jonschlinkert/arr-reduce): Fast array reduce that also loops over sparse elements.
+* [arr-map](https://github.com/jonschlinkert/arr-map): Faster, node.js focused alternative to JavaScript's native array map.
+* [arr-pluck](https://github.com/jonschlinkert/arr-pluck): Retrieves the value of a specified property from all elements in the collection.
+
+## Run tests
+Install dev dependencies.
+
+```bash
+npm i -d && npm test
+```
+
+## Contributing
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/array-unique/issues)
+
+## Author
+
+**Jon Schlinkert**
+
++ [github/jonschlinkert](https://github.com/jonschlinkert)
++ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+Copyright (c) 2015 Jon Schlinkert
+Released under the MIT license
+
+***
+
+_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on March 24, 2015._
\ No newline at end of file
diff --git a/node_modules/array-unique/index.js b/node_modules/array-unique/index.js
new file mode 100755
index 0000000..7fa75af
--- /dev/null
+++ b/node_modules/array-unique/index.js
@@ -0,0 +1,28 @@
+/*!
+ * array-unique
+ *
+ * Copyright (c) 2014-2015, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+
+'use strict';
+
+module.exports = function unique(arr) {
+ if (!Array.isArray(arr)) {
+ throw new TypeError('array-unique expects an array.');
+ }
+
+ var len = arr.length;
+ var i = -1;
+
+ while (i++ < len) {
+ var j = i + 1;
+
+ for (; j < arr.length; ++j) {
+ if (arr[i] === arr[j]) {
+ arr.splice(j--, 1);
+ }
+ }
+ }
+ return arr;
+};
diff --git a/node_modules/array-unique/package.json b/node_modules/array-unique/package.json
new file mode 100755
index 0000000..a493f69
--- /dev/null
+++ b/node_modules/array-unique/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "array-unique",
+ "description": "Return an array free of duplicate values. Fastest ES5 implementation.",
+ "version": "0.2.1",
+ "homepage": "https://github.com/jonschlinkert/array-unique",
+ "author": {
+ "name": "Jon Schlinkert",
+ "url": "https://github.com/jonschlinkert"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/jonschlinkert/array-unique.git"
+ },
+ "bugs": {
+ "url": "https://github.com/jonschlinkert/array-unique/issues"
+ },
+ "license": {
+ "type": "MIT",
+ "url": "https://github.com/jonschlinkert/array-unique/blob/master/LICENSE"
+ },
+ "files": [
+ "index.js"
+ ],
+ "main": "index.js",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "mocha"
+ },
+ "devDependencies": {
+ "array-uniq": "^1.0.2",
+ "benchmarked": "^0.1.3",
+ "mocha": "*",
+ "should": "*"
+ }
+}
diff --git a/node_modules/arrify/index.js b/node_modules/arrify/index.js
new file mode 100644
index 0000000..2a2fdee
--- /dev/null
+++ b/node_modules/arrify/index.js
@@ -0,0 +1,8 @@
+'use strict';
+module.exports = function (val) {
+ if (val === null || val === undefined) {
+ return [];
+ }
+
+ return Array.isArray(val) ? val : [val];
+};
diff --git a/node_modules/arrify/license b/node_modules/arrify/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/arrify/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus (sindresorhus.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/arrify/package.json b/node_modules/arrify/package.json
new file mode 100644
index 0000000..1e63e59
--- /dev/null
+++ b/node_modules/arrify/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "arrify",
+ "version": "1.0.1",
+ "description": "Convert a value to an array",
+ "license": "MIT",
+ "repository": "sindresorhus/arrify",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "xo && ava"
+ },
+ "files": [
+ "index.js"
+ ],
+ "keywords": [
+ "array",
+ "arr",
+ "arrify",
+ "arrayify",
+ "convert",
+ "value"
+ ],
+ "devDependencies": {
+ "ava": "*",
+ "xo": "*"
+ }
+}
diff --git a/node_modules/arrify/readme.md b/node_modules/arrify/readme.md
new file mode 100644
index 0000000..183d075
--- /dev/null
+++ b/node_modules/arrify/readme.md
@@ -0,0 +1,36 @@
+# arrify [![Build Status](https://travis-ci.org/sindresorhus/arrify.svg?branch=master)](https://travis-ci.org/sindresorhus/arrify)
+
+> Convert a value to an array
+
+
+## Install
+
+```
+$ npm install --save arrify
+```
+
+
+## Usage
+
+```js
+const arrify = require('arrify');
+
+arrify('unicorn');
+//=> ['unicorn']
+
+arrify(['unicorn']);
+//=> ['unicorn']
+
+arrify(null);
+//=> []
+
+arrify(undefined);
+//=> []
+```
+
+*Supplying `null` or `undefined` results in an empty array.*
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/node_modules/asn1/.npmignore b/node_modules/asn1/.npmignore
new file mode 100644
index 0000000..eb03e3e
--- /dev/null
+++ b/node_modules/asn1/.npmignore
@@ -0,0 +1,2 @@
+node_modules
+*.log
diff --git a/node_modules/asn1/.travis.yml b/node_modules/asn1/.travis.yml
new file mode 100644
index 0000000..09d3ef3
--- /dev/null
+++ b/node_modules/asn1/.travis.yml
@@ -0,0 +1,4 @@
+language: node_js
+node_js:
+ - 0.8
+ - 0.10
diff --git a/node_modules/asn1/LICENSE b/node_modules/asn1/LICENSE
new file mode 100644
index 0000000..9b5dcdb
--- /dev/null
+++ b/node_modules/asn1/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2011 Mark Cavage, 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/asn1/README.md b/node_modules/asn1/README.md
new file mode 100644
index 0000000..7cebf7a
--- /dev/null
+++ b/node_modules/asn1/README.md
@@ -0,0 +1,50 @@
+node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS.
+Currently BER encoding is supported; at some point I'll likely have to do DER.
+
+## Usage
+
+Mostly, if you're *actually* needing to read and write ASN.1, you probably don't
+need this readme to explain what and why. If you have no idea what ASN.1 is,
+see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
+
+The source is pretty much self-explanatory, and has read/write methods for the
+common types out there.
+
+### Decoding
+
+The following reads an ASN.1 sequence with a boolean.
+
+ var Ber = require('asn1').Ber;
+
+ var reader = new Ber.Reader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff]));
+
+ reader.readSequence();
+ console.log('Sequence len: ' + reader.length);
+ if (reader.peek() === Ber.Boolean)
+ console.log(reader.readBoolean());
+
+### Encoding
+
+The following generates the same payload as above.
+
+ var Ber = require('asn1').Ber;
+
+ var writer = new Ber.Writer();
+
+ writer.startSequence();
+ writer.writeBoolean(true);
+ writer.endSequence();
+
+ console.log(writer.buffer);
+
+## Installation
+
+ npm install asn1
+
+## License
+
+MIT.
+
+## Bugs
+
+See .
diff --git a/node_modules/asn1/lib/ber/errors.js b/node_modules/asn1/lib/ber/errors.js
new file mode 100644
index 0000000..ff21d4f
--- /dev/null
+++ b/node_modules/asn1/lib/ber/errors.js
@@ -0,0 +1,13 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+
+module.exports = {
+
+ newInvalidAsn1Error: function(msg) {
+ var e = new Error();
+ e.name = 'InvalidAsn1Error';
+ e.message = msg || '';
+ return e;
+ }
+
+};
diff --git a/node_modules/asn1/lib/ber/index.js b/node_modules/asn1/lib/ber/index.js
new file mode 100644
index 0000000..4fb90ae
--- /dev/null
+++ b/node_modules/asn1/lib/ber/index.js
@@ -0,0 +1,27 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+var errors = require('./errors');
+var types = require('./types');
+
+var Reader = require('./reader');
+var Writer = require('./writer');
+
+
+///--- Exports
+
+module.exports = {
+
+ Reader: Reader,
+
+ Writer: Writer
+
+};
+
+for (var t in types) {
+ if (types.hasOwnProperty(t))
+ module.exports[t] = types[t];
+}
+for (var e in errors) {
+ if (errors.hasOwnProperty(e))
+ module.exports[e] = errors[e];
+}
diff --git a/node_modules/asn1/lib/ber/reader.js b/node_modules/asn1/lib/ber/reader.js
new file mode 100644
index 0000000..0a00e98
--- /dev/null
+++ b/node_modules/asn1/lib/ber/reader.js
@@ -0,0 +1,261 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+var assert = require('assert');
+
+var ASN1 = require('./types');
+var errors = require('./errors');
+
+
+///--- Globals
+
+var newInvalidAsn1Error = errors.newInvalidAsn1Error;
+
+
+
+///--- API
+
+function Reader(data) {
+ if (!data || !Buffer.isBuffer(data))
+ throw new TypeError('data must be a node Buffer');
+
+ this._buf = data;
+ this._size = data.length;
+
+ // These hold the "current" state
+ this._len = 0;
+ this._offset = 0;
+}
+
+Object.defineProperty(Reader.prototype, 'length', {
+ enumerable: true,
+ get: function () { return (this._len); }
+});
+
+Object.defineProperty(Reader.prototype, 'offset', {
+ enumerable: true,
+ get: function () { return (this._offset); }
+});
+
+Object.defineProperty(Reader.prototype, 'remain', {
+ get: function () { return (this._size - this._offset); }
+});
+
+Object.defineProperty(Reader.prototype, 'buffer', {
+ get: function () { return (this._buf.slice(this._offset)); }
+});
+
+
+/**
+ * Reads a single byte and advances offset; you can pass in `true` to make this
+ * a "peek" operation (i.e., get the byte, but don't advance the offset).
+ *
+ * @param {Boolean} peek true means don't move offset.
+ * @return {Number} the next byte, null if not enough data.
+ */
+Reader.prototype.readByte = function(peek) {
+ if (this._size - this._offset < 1)
+ return null;
+
+ var b = this._buf[this._offset] & 0xff;
+
+ if (!peek)
+ this._offset += 1;
+
+ return b;
+};
+
+
+Reader.prototype.peek = function() {
+ return this.readByte(true);
+};
+
+
+/**
+ * Reads a (potentially) variable length off the BER buffer. This call is
+ * not really meant to be called directly, as callers have to manipulate
+ * the internal buffer afterwards.
+ *
+ * As a result of this call, you can call `Reader.length`, until the
+ * next thing called that does a readLength.
+ *
+ * @return {Number} the amount of offset to advance the buffer.
+ * @throws {InvalidAsn1Error} on bad ASN.1
+ */
+Reader.prototype.readLength = function(offset) {
+ if (offset === undefined)
+ offset = this._offset;
+
+ if (offset >= this._size)
+ return null;
+
+ var lenB = this._buf[offset++] & 0xff;
+ if (lenB === null)
+ return null;
+
+ if ((lenB & 0x80) == 0x80) {
+ lenB &= 0x7f;
+
+ if (lenB == 0)
+ throw newInvalidAsn1Error('Indefinite length not supported');
+
+ if (lenB > 4)
+ throw newInvalidAsn1Error('encoding too long');
+
+ if (this._size - offset < lenB)
+ return null;
+
+ this._len = 0;
+ for (var i = 0; i < lenB; i++)
+ this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
+
+ } else {
+ // Wasn't a variable length
+ this._len = lenB;
+ }
+
+ return offset;
+};
+
+
+/**
+ * Parses the next sequence in this BER buffer.
+ *
+ * To get the length of the sequence, call `Reader.length`.
+ *
+ * @return {Number} the sequence's tag.
+ */
+Reader.prototype.readSequence = function(tag) {
+ var seq = this.peek();
+ if (seq === null)
+ return null;
+ if (tag !== undefined && tag !== seq)
+ throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
+ ': got 0x' + seq.toString(16));
+
+ var o = this.readLength(this._offset + 1); // stored in `length`
+ if (o === null)
+ return null;
+
+ this._offset = o;
+ return seq;
+};
+
+
+Reader.prototype.readInt = function() {
+ return this._readTag(ASN1.Integer);
+};
+
+
+Reader.prototype.readBoolean = function() {
+ return (this._readTag(ASN1.Boolean) === 0 ? false : true);
+};
+
+
+Reader.prototype.readEnumeration = function() {
+ return this._readTag(ASN1.Enumeration);
+};
+
+
+Reader.prototype.readString = function(tag, retbuf) {
+ if (!tag)
+ tag = ASN1.OctetString;
+
+ var b = this.peek();
+ if (b === null)
+ return null;
+
+ if (b !== tag)
+ throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
+ ': got 0x' + b.toString(16));
+
+ var o = this.readLength(this._offset + 1); // stored in `length`
+
+ if (o === null)
+ return null;
+
+ if (this.length > this._size - o)
+ return null;
+
+ this._offset = o;
+
+ if (this.length === 0)
+ return retbuf ? new Buffer(0) : '';
+
+ var str = this._buf.slice(this._offset, this._offset + this.length);
+ this._offset += this.length;
+
+ return retbuf ? str : str.toString('utf8');
+};
+
+Reader.prototype.readOID = function(tag) {
+ if (!tag)
+ tag = ASN1.OID;
+
+ var b = this.readString(tag, true);
+ if (b === null)
+ return null;
+
+ var values = [];
+ var value = 0;
+
+ for (var i = 0; i < b.length; i++) {
+ var byte = b[i] & 0xff;
+
+ value <<= 7;
+ value += byte & 0x7f;
+ if ((byte & 0x80) == 0) {
+ values.push(value);
+ value = 0;
+ }
+ }
+
+ value = values.shift();
+ values.unshift(value % 40);
+ values.unshift((value / 40) >> 0);
+
+ return values.join('.');
+};
+
+
+Reader.prototype._readTag = function(tag) {
+ assert.ok(tag !== undefined);
+
+ var b = this.peek();
+
+ if (b === null)
+ return null;
+
+ if (b !== tag)
+ throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
+ ': got 0x' + b.toString(16));
+
+ var o = this.readLength(this._offset + 1); // stored in `length`
+ if (o === null)
+ return null;
+
+ if (this.length > 4)
+ throw newInvalidAsn1Error('Integer too long: ' + this.length);
+
+ if (this.length > this._size - o)
+ return null;
+ this._offset = o;
+
+ var fb = this._buf[this._offset];
+ var value = 0;
+
+ for (var i = 0; i < this.length; i++) {
+ value <<= 8;
+ value |= (this._buf[this._offset++] & 0xff);
+ }
+
+ if ((fb & 0x80) == 0x80 && i !== 4)
+ value -= (1 << (i * 8));
+
+ return value >> 0;
+};
+
+
+
+///--- Exported API
+
+module.exports = Reader;
diff --git a/node_modules/asn1/lib/ber/types.js b/node_modules/asn1/lib/ber/types.js
new file mode 100644
index 0000000..8aea000
--- /dev/null
+++ b/node_modules/asn1/lib/ber/types.js
@@ -0,0 +1,36 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+
+module.exports = {
+ EOC: 0,
+ Boolean: 1,
+ Integer: 2,
+ BitString: 3,
+ OctetString: 4,
+ Null: 5,
+ OID: 6,
+ ObjectDescriptor: 7,
+ External: 8,
+ Real: 9, // float
+ Enumeration: 10,
+ PDV: 11,
+ Utf8String: 12,
+ RelativeOID: 13,
+ Sequence: 16,
+ Set: 17,
+ NumericString: 18,
+ PrintableString: 19,
+ T61String: 20,
+ VideotexString: 21,
+ IA5String: 22,
+ UTCTime: 23,
+ GeneralizedTime: 24,
+ GraphicString: 25,
+ VisibleString: 26,
+ GeneralString: 28,
+ UniversalString: 29,
+ CharacterString: 30,
+ BMPString: 31,
+ Constructor: 32,
+ Context: 128
+};
diff --git a/node_modules/asn1/lib/ber/writer.js b/node_modules/asn1/lib/ber/writer.js
new file mode 100644
index 0000000..d9d99af
--- /dev/null
+++ b/node_modules/asn1/lib/ber/writer.js
@@ -0,0 +1,316 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+var assert = require('assert');
+var ASN1 = require('./types');
+var errors = require('./errors');
+
+
+///--- Globals
+
+var newInvalidAsn1Error = errors.newInvalidAsn1Error;
+
+var DEFAULT_OPTS = {
+ size: 1024,
+ growthFactor: 8
+};
+
+
+///--- Helpers
+
+function merge(from, to) {
+ assert.ok(from);
+ assert.equal(typeof(from), 'object');
+ assert.ok(to);
+ assert.equal(typeof(to), 'object');
+
+ var keys = Object.getOwnPropertyNames(from);
+ keys.forEach(function(key) {
+ if (to[key])
+ return;
+
+ var value = Object.getOwnPropertyDescriptor(from, key);
+ Object.defineProperty(to, key, value);
+ });
+
+ return to;
+}
+
+
+
+///--- API
+
+function Writer(options) {
+ options = merge(DEFAULT_OPTS, options || {});
+
+ this._buf = new Buffer(options.size || 1024);
+ this._size = this._buf.length;
+ this._offset = 0;
+ this._options = options;
+
+ // A list of offsets in the buffer where we need to insert
+ // sequence tag/len pairs.
+ this._seq = [];
+}
+
+Object.defineProperty(Writer.prototype, 'buffer', {
+ get: function () {
+ if (this._seq.length)
+ throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)');
+
+ return (this._buf.slice(0, this._offset));
+ }
+});
+
+Writer.prototype.writeByte = function(b) {
+ if (typeof(b) !== 'number')
+ throw new TypeError('argument must be a Number');
+
+ this._ensure(1);
+ this._buf[this._offset++] = b;
+};
+
+
+Writer.prototype.writeInt = function(i, tag) {
+ if (typeof(i) !== 'number')
+ throw new TypeError('argument must be a Number');
+ if (typeof(tag) !== 'number')
+ tag = ASN1.Integer;
+
+ var sz = 4;
+
+ while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
+ (sz > 1)) {
+ sz--;
+ i <<= 8;
+ }
+
+ if (sz > 4)
+ throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
+
+ this._ensure(2 + sz);
+ this._buf[this._offset++] = tag;
+ this._buf[this._offset++] = sz;
+
+ while (sz-- > 0) {
+ this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
+ i <<= 8;
+ }
+
+};
+
+
+Writer.prototype.writeNull = function() {
+ this.writeByte(ASN1.Null);
+ this.writeByte(0x00);
+};
+
+
+Writer.prototype.writeEnumeration = function(i, tag) {
+ if (typeof(i) !== 'number')
+ throw new TypeError('argument must be a Number');
+ if (typeof(tag) !== 'number')
+ tag = ASN1.Enumeration;
+
+ return this.writeInt(i, tag);
+};
+
+
+Writer.prototype.writeBoolean = function(b, tag) {
+ if (typeof(b) !== 'boolean')
+ throw new TypeError('argument must be a Boolean');
+ if (typeof(tag) !== 'number')
+ tag = ASN1.Boolean;
+
+ this._ensure(3);
+ this._buf[this._offset++] = tag;
+ this._buf[this._offset++] = 0x01;
+ this._buf[this._offset++] = b ? 0xff : 0x00;
+};
+
+
+Writer.prototype.writeString = function(s, tag) {
+ if (typeof(s) !== 'string')
+ throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
+ if (typeof(tag) !== 'number')
+ tag = ASN1.OctetString;
+
+ var len = Buffer.byteLength(s);
+ this.writeByte(tag);
+ this.writeLength(len);
+ if (len) {
+ this._ensure(len);
+ this._buf.write(s, this._offset);
+ this._offset += len;
+ }
+};
+
+
+Writer.prototype.writeBuffer = function(buf, tag) {
+ if (typeof(tag) !== 'number')
+ throw new TypeError('tag must be a number');
+ if (!Buffer.isBuffer(buf))
+ throw new TypeError('argument must be a buffer');
+
+ this.writeByte(tag);
+ this.writeLength(buf.length);
+ this._ensure(buf.length);
+ buf.copy(this._buf, this._offset, 0, buf.length);
+ this._offset += buf.length;
+};
+
+
+Writer.prototype.writeStringArray = function(strings) {
+ if ((!strings instanceof Array))
+ throw new TypeError('argument must be an Array[String]');
+
+ var self = this;
+ strings.forEach(function(s) {
+ self.writeString(s);
+ });
+};
+
+// This is really to solve DER cases, but whatever for now
+Writer.prototype.writeOID = function(s, tag) {
+ if (typeof(s) !== 'string')
+ throw new TypeError('argument must be a string');
+ if (typeof(tag) !== 'number')
+ tag = ASN1.OID;
+
+ if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
+ throw new Error('argument is not a valid OID string');
+
+ function encodeOctet(bytes, octet) {
+ if (octet < 128) {
+ bytes.push(octet);
+ } else if (octet < 16384) {
+ bytes.push((octet >>> 7) | 0x80);
+ bytes.push(octet & 0x7F);
+ } else if (octet < 2097152) {
+ bytes.push((octet >>> 14) | 0x80);
+ bytes.push(((octet >>> 7) | 0x80) & 0xFF);
+ bytes.push(octet & 0x7F);
+ } else if (octet < 268435456) {
+ bytes.push((octet >>> 21) | 0x80);
+ bytes.push(((octet >>> 14) | 0x80) & 0xFF);
+ bytes.push(((octet >>> 7) | 0x80) & 0xFF);
+ bytes.push(octet & 0x7F);
+ } else {
+ bytes.push(((octet >>> 28) | 0x80) & 0xFF);
+ bytes.push(((octet >>> 21) | 0x80) & 0xFF);
+ bytes.push(((octet >>> 14) | 0x80) & 0xFF);
+ bytes.push(((octet >>> 7) | 0x80) & 0xFF);
+ bytes.push(octet & 0x7F);
+ }
+ }
+
+ var tmp = s.split('.');
+ var bytes = [];
+ bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
+ tmp.slice(2).forEach(function(b) {
+ encodeOctet(bytes, parseInt(b, 10));
+ });
+
+ var self = this;
+ this._ensure(2 + bytes.length);
+ this.writeByte(tag);
+ this.writeLength(bytes.length);
+ bytes.forEach(function(b) {
+ self.writeByte(b);
+ });
+};
+
+
+Writer.prototype.writeLength = function(len) {
+ if (typeof(len) !== 'number')
+ throw new TypeError('argument must be a Number');
+
+ this._ensure(4);
+
+ if (len <= 0x7f) {
+ this._buf[this._offset++] = len;
+ } else if (len <= 0xff) {
+ this._buf[this._offset++] = 0x81;
+ this._buf[this._offset++] = len;
+ } else if (len <= 0xffff) {
+ this._buf[this._offset++] = 0x82;
+ this._buf[this._offset++] = len >> 8;
+ this._buf[this._offset++] = len;
+ } else if (len <= 0xffffff) {
+ this._buf[this._offset++] = 0x83;
+ this._buf[this._offset++] = len >> 16;
+ this._buf[this._offset++] = len >> 8;
+ this._buf[this._offset++] = len;
+ } else {
+ throw new InvalidAsn1ERror('Length too long (> 4 bytes)');
+ }
+};
+
+Writer.prototype.startSequence = function(tag) {
+ if (typeof(tag) !== 'number')
+ tag = ASN1.Sequence | ASN1.Constructor;
+
+ this.writeByte(tag);
+ this._seq.push(this._offset);
+ this._ensure(3);
+ this._offset += 3;
+};
+
+
+Writer.prototype.endSequence = function() {
+ var seq = this._seq.pop();
+ var start = seq + 3;
+ var len = this._offset - start;
+
+ if (len <= 0x7f) {
+ this._shift(start, len, -2);
+ this._buf[seq] = len;
+ } else if (len <= 0xff) {
+ this._shift(start, len, -1);
+ this._buf[seq] = 0x81;
+ this._buf[seq + 1] = len;
+ } else if (len <= 0xffff) {
+ this._buf[seq] = 0x82;
+ this._buf[seq + 1] = len >> 8;
+ this._buf[seq + 2] = len;
+ } else if (len <= 0xffffff) {
+ this._shift(start, len, 1);
+ this._buf[seq] = 0x83;
+ this._buf[seq + 1] = len >> 16;
+ this._buf[seq + 2] = len >> 8;
+ this._buf[seq + 3] = len;
+ } else {
+ throw new InvalidAsn1Error('Sequence too long');
+ }
+};
+
+
+Writer.prototype._shift = function(start, len, shift) {
+ assert.ok(start !== undefined);
+ assert.ok(len !== undefined);
+ assert.ok(shift);
+
+ this._buf.copy(this._buf, start + shift, start, start + len);
+ this._offset += shift;
+};
+
+Writer.prototype._ensure = function(len) {
+ assert.ok(len);
+
+ if (this._size - this._offset < len) {
+ var sz = this._size * this._options.growthFactor;
+ if (sz - this._offset < len)
+ sz += len;
+
+ var buf = new Buffer(sz);
+
+ this._buf.copy(buf, 0, 0, this._offset);
+ this._buf = buf;
+ this._size = sz;
+ }
+};
+
+
+
+///--- Exported API
+
+module.exports = Writer;
diff --git a/node_modules/asn1/lib/index.js b/node_modules/asn1/lib/index.js
new file mode 100644
index 0000000..d1766e7
--- /dev/null
+++ b/node_modules/asn1/lib/index.js
@@ -0,0 +1,20 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+// If you have no idea what ASN.1 or BER is, see this:
+// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
+
+var Ber = require('./ber/index');
+
+
+
+///--- Exported API
+
+module.exports = {
+
+ Ber: Ber,
+
+ BerReader: Ber.Reader,
+
+ BerWriter: Ber.Writer
+
+};
diff --git a/node_modules/asn1/package.json b/node_modules/asn1/package.json
new file mode 100644
index 0000000..f6dfb06
--- /dev/null
+++ b/node_modules/asn1/package.json
@@ -0,0 +1,24 @@
+{
+ "author": "Mark Cavage ",
+ "contributors": [
+ "David Gwynne ",
+ "Yunong Xiao ",
+ "Alex Wilson "
+ ],
+ "name": "asn1",
+ "description": "Contains parsers and serializers for ASN.1 (currently BER only)",
+ "version": "0.2.3",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/mcavage/node-asn1.git"
+ },
+ "main": "lib/index.js",
+ "dependencies": {},
+ "devDependencies": {
+ "tap": "0.4.8"
+ },
+ "scripts": {
+ "test": "./node_modules/.bin/tap ./tst"
+ },
+ "license": "MIT"
+}
diff --git a/node_modules/asn1/tst/ber/reader.test.js b/node_modules/asn1/tst/ber/reader.test.js
new file mode 100644
index 0000000..062fd7e
--- /dev/null
+++ b/node_modules/asn1/tst/ber/reader.test.js
@@ -0,0 +1,208 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+var test = require('tap').test;
+
+
+
+///--- Globals
+
+var BerReader;
+
+
+
+///--- Tests
+
+test('load library', function(t) {
+ BerReader = require('../../lib/index').BerReader;
+ t.ok(BerReader);
+ try {
+ new BerReader();
+ t.fail('Should have thrown');
+ } catch (e) {
+ t.ok(e instanceof TypeError, 'Should have been a type error');
+ }
+ t.end();
+});
+
+
+test('read byte', function(t) {
+ var reader = new BerReader(new Buffer([0xde]));
+ t.ok(reader);
+ t.equal(reader.readByte(), 0xde, 'wrong value');
+ t.end();
+});
+
+
+test('read 1 byte int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x01, 0x03]));
+ t.ok(reader);
+ t.equal(reader.readInt(), 0x03, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('read 2 byte int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x02, 0x7e, 0xde]));
+ t.ok(reader);
+ t.equal(reader.readInt(), 0x7ede, 'wrong value');
+ t.equal(reader.length, 0x02, 'wrong length');
+ t.end();
+});
+
+
+test('read 3 byte int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x03, 0x7e, 0xde, 0x03]));
+ t.ok(reader);
+ t.equal(reader.readInt(), 0x7ede03, 'wrong value');
+ t.equal(reader.length, 0x03, 'wrong length');
+ t.end();
+});
+
+
+test('read 4 byte int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x04, 0x7e, 0xde, 0x03, 0x01]));
+ t.ok(reader);
+ t.equal(reader.readInt(), 0x7ede0301, 'wrong value');
+ t.equal(reader.length, 0x04, 'wrong length');
+ t.end();
+});
+
+
+test('read 1 byte negative int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x01, 0xdc]));
+ t.ok(reader);
+ t.equal(reader.readInt(), -36, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('read 2 byte negative int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x02, 0xc0, 0x4e]));
+ t.ok(reader);
+ t.equal(reader.readInt(), -16306, 'wrong value');
+ t.equal(reader.length, 0x02, 'wrong length');
+ t.end();
+});
+
+
+test('read 3 byte negative int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x03, 0xff, 0x00, 0x19]));
+ t.ok(reader);
+ t.equal(reader.readInt(), -65511, 'wrong value');
+ t.equal(reader.length, 0x03, 'wrong length');
+ t.end();
+});
+
+
+test('read 4 byte negative int', function(t) {
+ var reader = new BerReader(new Buffer([0x02, 0x04, 0x91, 0x7c, 0x22, 0x1f]));
+ t.ok(reader);
+ t.equal(reader.readInt(), -1854135777, 'wrong value');
+ t.equal(reader.length, 0x04, 'wrong length');
+ t.end();
+});
+
+
+test('read boolean true', function(t) {
+ var reader = new BerReader(new Buffer([0x01, 0x01, 0xff]));
+ t.ok(reader);
+ t.equal(reader.readBoolean(), true, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('read boolean false', function(t) {
+ var reader = new BerReader(new Buffer([0x01, 0x01, 0x00]));
+ t.ok(reader);
+ t.equal(reader.readBoolean(), false, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('read enumeration', function(t) {
+ var reader = new BerReader(new Buffer([0x0a, 0x01, 0x20]));
+ t.ok(reader);
+ t.equal(reader.readEnumeration(), 0x20, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('read string', function(t) {
+ var dn = 'cn=foo,ou=unit,o=test';
+ var buf = new Buffer(dn.length + 2);
+ buf[0] = 0x04;
+ buf[1] = Buffer.byteLength(dn);
+ buf.write(dn, 2);
+ var reader = new BerReader(buf);
+ t.ok(reader);
+ t.equal(reader.readString(), dn, 'wrong value');
+ t.equal(reader.length, dn.length, 'wrong length');
+ t.end();
+});
+
+
+test('read sequence', function(t) {
+ var reader = new BerReader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff]));
+ t.ok(reader);
+ t.equal(reader.readSequence(), 0x30, 'wrong value');
+ t.equal(reader.length, 0x03, 'wrong length');
+ t.equal(reader.readBoolean(), true, 'wrong value');
+ t.equal(reader.length, 0x01, 'wrong length');
+ t.end();
+});
+
+
+test('anonymous LDAPv3 bind', function(t) {
+ var BIND = new Buffer(14);
+ BIND[0] = 0x30; // Sequence
+ BIND[1] = 12; // len
+ BIND[2] = 0x02; // ASN.1 Integer
+ BIND[3] = 1; // len
+ BIND[4] = 0x04; // msgid (make up 4)
+ BIND[5] = 0x60; // Bind Request
+ BIND[6] = 7; // len
+ BIND[7] = 0x02; // ASN.1 Integer
+ BIND[8] = 1; // len
+ BIND[9] = 0x03; // v3
+ BIND[10] = 0x04; // String (bind dn)
+ BIND[11] = 0; // len
+ BIND[12] = 0x80; // ContextSpecific (choice)
+ BIND[13] = 0; // simple bind
+
+ // Start testing ^^
+ var ber = new BerReader(BIND);
+ t.equal(ber.readSequence(), 48, 'Not an ASN.1 Sequence');
+ t.equal(ber.length, 12, 'Message length should be 12');
+ t.equal(ber.readInt(), 4, 'Message id should have been 4');
+ t.equal(ber.readSequence(), 96, 'Bind Request should have been 96');
+ t.equal(ber.length, 7, 'Bind length should have been 7');
+ t.equal(ber.readInt(), 3, 'LDAP version should have been 3');
+ t.equal(ber.readString(), '', 'Bind DN should have been empty');
+ t.equal(ber.length, 0, 'string length should have been 0');
+ t.equal(ber.readByte(), 0x80, 'Should have been ContextSpecific (choice)');
+ t.equal(ber.readByte(), 0, 'Should have been simple bind');
+ t.equal(null, ber.readByte(), 'Should be out of data');
+ t.end();
+});
+
+
+test('long string', function(t) {
+ var buf = new Buffer(256);
+ var o;
+ var s =
+ '2;649;CN=Red Hat CS 71GA Demo,O=Red Hat CS 71GA Demo,C=US;' +
+ 'CN=RHCS Agent - admin01,UID=admin01,O=redhat,C=US [1] This is ' +
+ 'Teena Vradmin\'s description.';
+ buf[0] = 0x04;
+ buf[1] = 0x81;
+ buf[2] = 0x94;
+ buf.write(s, 3);
+ var ber = new BerReader(buf.slice(0, 3 + s.length));
+ t.equal(ber.readString(), s);
+ t.end();
+});
diff --git a/node_modules/asn1/tst/ber/writer.test.js b/node_modules/asn1/tst/ber/writer.test.js
new file mode 100644
index 0000000..d87cb7b
--- /dev/null
+++ b/node_modules/asn1/tst/ber/writer.test.js
@@ -0,0 +1,370 @@
+// Copyright 2011 Mark Cavage All rights reserved.
+
+var test = require('tap').test;
+var sys = require('sys');
+
+///--- Globals
+
+var BerWriter;
+
+var BerReader;
+
+
+///--- Tests
+
+test('load library', function(t) {
+ BerWriter = require('../../lib/index').BerWriter;
+ t.ok(BerWriter);
+ t.ok(new BerWriter());
+ t.end();
+});
+
+
+test('write byte', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeByte(0xC2);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 1, 'Wrong length');
+ t.equal(ber[0], 0xC2, 'value wrong');
+
+ t.end();
+});
+
+
+test('write 1 byte int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(0x7f);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 3, 'Wrong length for an int: ' + ber.length);
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong (2) -> ' + ber[0]);
+ t.equal(ber[1], 0x01, 'length wrong(1) -> ' + ber[1]);
+ t.equal(ber[2], 0x7f, 'value wrong(3) -> ' + ber[2]);
+
+ t.end();
+});
+
+
+test('write 2 byte int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(0x7ffe);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 4, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x02, 'length wrong');
+ t.equal(ber[2], 0x7f, 'value wrong (byte 1)');
+ t.equal(ber[3], 0xfe, 'value wrong (byte 2)');
+
+ t.end();
+});
+
+
+test('write 3 byte int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(0x7ffffe);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 5, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x03, 'length wrong');
+ t.equal(ber[2], 0x7f, 'value wrong (byte 1)');
+ t.equal(ber[3], 0xff, 'value wrong (byte 2)');
+ t.equal(ber[4], 0xfe, 'value wrong (byte 3)');
+
+ t.end();
+});
+
+
+test('write 4 byte int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(0x7ffffffe);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 6, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x04, 'length wrong');
+ t.equal(ber[2], 0x7f, 'value wrong (byte 1)');
+ t.equal(ber[3], 0xff, 'value wrong (byte 2)');
+ t.equal(ber[4], 0xff, 'value wrong (byte 3)');
+ t.equal(ber[5], 0xfe, 'value wrong (byte 4)');
+
+ t.end();
+});
+
+
+test('write 1 byte negative int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(-128);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 3, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x01, 'length wrong');
+ t.equal(ber[2], 0x80, 'value wrong (byte 1)');
+
+ t.end();
+});
+
+
+test('write 2 byte negative int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(-22400);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 4, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x02, 'length wrong');
+ t.equal(ber[2], 0xa8, 'value wrong (byte 1)');
+ t.equal(ber[3], 0x80, 'value wrong (byte 2)');
+
+ t.end();
+});
+
+
+test('write 3 byte negative int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(-481653);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 5, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x03, 'length wrong');
+ t.equal(ber[2], 0xf8, 'value wrong (byte 1)');
+ t.equal(ber[3], 0xa6, 'value wrong (byte 2)');
+ t.equal(ber[4], 0x8b, 'value wrong (byte 3)');
+
+ t.end();
+});
+
+
+test('write 4 byte negative int', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeInt(-1522904131);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 6, 'Wrong length for an int');
+ t.equal(ber[0], 0x02, 'ASN.1 tag wrong');
+ t.equal(ber[1], 0x04, 'length wrong');
+ t.equal(ber[2], 0xa5, 'value wrong (byte 1)');
+ t.equal(ber[3], 0x3a, 'value wrong (byte 2)');
+ t.equal(ber[4], 0x53, 'value wrong (byte 3)');
+ t.equal(ber[5], 0xbd, 'value wrong (byte 4)');
+
+ t.end();
+});
+
+
+test('write boolean', function(t) {
+ var writer = new BerWriter();
+
+ writer.writeBoolean(true);
+ writer.writeBoolean(false);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 6, 'Wrong length');
+ t.equal(ber[0], 0x01, 'tag wrong');
+ t.equal(ber[1], 0x01, 'length wrong');
+ t.equal(ber[2], 0xff, 'value wrong');
+ t.equal(ber[3], 0x01, 'tag wrong');
+ t.equal(ber[4], 0x01, 'length wrong');
+ t.equal(ber[5], 0x00, 'value wrong');
+
+ t.end();
+});
+
+
+test('write string', function(t) {
+ var writer = new BerWriter();
+ writer.writeString('hello world');
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 13, 'wrong length');
+ t.equal(ber[0], 0x04, 'wrong tag');
+ t.equal(ber[1], 11, 'wrong length');
+ t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value');
+
+ t.end();
+});
+
+test('write buffer', function(t) {
+ var writer = new BerWriter();
+ // write some stuff to start with
+ writer.writeString('hello world');
+ var ber = writer.buffer;
+ var buf = new Buffer([0x04, 0x0b, 0x30, 0x09, 0x02, 0x01, 0x0f, 0x01, 0x01,
+ 0xff, 0x01, 0x01, 0xff]);
+ writer.writeBuffer(buf.slice(2, buf.length), 0x04);
+ ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 26, 'wrong length');
+ t.equal(ber[0], 0x04, 'wrong tag');
+ t.equal(ber[1], 11, 'wrong length');
+ t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value');
+ t.equal(ber[13], buf[0], 'wrong tag');
+ t.equal(ber[14], buf[1], 'wrong length');
+ for (var i = 13, j = 0; i < ber.length && j < buf.length; i++, j++) {
+ t.equal(ber[i], buf[j], 'buffer contents not identical');
+ }
+ t.end();
+});
+
+test('write string array', function(t) {
+ var writer = new BerWriter();
+ writer.writeStringArray(['hello world', 'fubar!']);
+ var ber = writer.buffer;
+
+ t.ok(ber);
+
+ t.equal(ber.length, 21, 'wrong length');
+ t.equal(ber[0], 0x04, 'wrong tag');
+ t.equal(ber[1], 11, 'wrong length');
+ t.equal(ber.slice(2, 13).toString('utf8'), 'hello world', 'wrong value');
+
+ t.equal(ber[13], 0x04, 'wrong tag');
+ t.equal(ber[14], 6, 'wrong length');
+ t.equal(ber.slice(15).toString('utf8'), 'fubar!', 'wrong value');
+
+ t.end();
+});
+
+
+test('resize internal buffer', function(t) {
+ var writer = new BerWriter({size: 2});
+ writer.writeString('hello world');
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 13, 'wrong length');
+ t.equal(ber[0], 0x04, 'wrong tag');
+ t.equal(ber[1], 11, 'wrong length');
+ t.equal(ber.slice(2).toString('utf8'), 'hello world', 'wrong value');
+
+ t.end();
+});
+
+
+test('sequence', function(t) {
+ var writer = new BerWriter({size: 25});
+ writer.startSequence();
+ writer.writeString('hello world');
+ writer.endSequence();
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ console.log(ber);
+ t.equal(ber.length, 15, 'wrong length');
+ t.equal(ber[0], 0x30, 'wrong tag');
+ t.equal(ber[1], 13, 'wrong length');
+ t.equal(ber[2], 0x04, 'wrong tag');
+ t.equal(ber[3], 11, 'wrong length');
+ t.equal(ber.slice(4).toString('utf8'), 'hello world', 'wrong value');
+
+ t.end();
+});
+
+
+test('nested sequence', function(t) {
+ var writer = new BerWriter({size: 25});
+ writer.startSequence();
+ writer.writeString('hello world');
+ writer.startSequence();
+ writer.writeString('hello world');
+ writer.endSequence();
+ writer.endSequence();
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 30, 'wrong length');
+ t.equal(ber[0], 0x30, 'wrong tag');
+ t.equal(ber[1], 28, 'wrong length');
+ t.equal(ber[2], 0x04, 'wrong tag');
+ t.equal(ber[3], 11, 'wrong length');
+ t.equal(ber.slice(4, 15).toString('utf8'), 'hello world', 'wrong value');
+ t.equal(ber[15], 0x30, 'wrong tag');
+ t.equal(ber[16], 13, 'wrong length');
+ t.equal(ber[17], 0x04, 'wrong tag');
+ t.equal(ber[18], 11, 'wrong length');
+ t.equal(ber.slice(19, 30).toString('utf8'), 'hello world', 'wrong value');
+
+ t.end();
+});
+
+
+test('LDAP bind message', function(t) {
+ var dn = 'cn=foo,ou=unit,o=test';
+ var writer = new BerWriter();
+ writer.startSequence();
+ writer.writeInt(3); // msgid = 3
+ writer.startSequence(0x60); // ldap bind
+ writer.writeInt(3); // ldap v3
+ writer.writeString(dn);
+ writer.writeByte(0x80);
+ writer.writeByte(0x00);
+ writer.endSequence();
+ writer.endSequence();
+ var ber = writer.buffer;
+
+ t.ok(ber);
+ t.equal(ber.length, 35, 'wrong length (buffer)');
+ t.equal(ber[0], 0x30, 'wrong tag');
+ t.equal(ber[1], 33, 'wrong length');
+ t.equal(ber[2], 0x02, 'wrong tag');
+ t.equal(ber[3], 1, 'wrong length');
+ t.equal(ber[4], 0x03, 'wrong value');
+ t.equal(ber[5], 0x60, 'wrong tag');
+ t.equal(ber[6], 28, 'wrong length');
+ t.equal(ber[7], 0x02, 'wrong tag');
+ t.equal(ber[8], 1, 'wrong length');
+ t.equal(ber[9], 0x03, 'wrong value');
+ t.equal(ber[10], 0x04, 'wrong tag');
+ t.equal(ber[11], dn.length, 'wrong length');
+ t.equal(ber.slice(12, 33).toString('utf8'), dn, 'wrong value');
+ t.equal(ber[33], 0x80, 'wrong tag');
+ t.equal(ber[34], 0x00, 'wrong len');
+
+ t.end();
+});
+
+
+test('Write OID', function(t) {
+ var oid = '1.2.840.113549.1.1.1';
+ var writer = new BerWriter();
+ writer.writeOID(oid);
+
+ var ber = writer.buffer;
+ t.ok(ber);
+ console.log(require('util').inspect(ber));
+ console.log(require('util').inspect(new Buffer([0x06, 0x09, 0x2a, 0x86,
+ 0x48, 0x86, 0xf7, 0x0d,
+ 0x01, 0x01, 0x01])));
+
+ t.end();
+});
diff --git a/node_modules/assert-plus/AUTHORS b/node_modules/assert-plus/AUTHORS
new file mode 100644
index 0000000..1923524
--- /dev/null
+++ b/node_modules/assert-plus/AUTHORS
@@ -0,0 +1,6 @@
+Dave Eddy
+Fred Kuo
+Lars-Magnus Skog
+Mark Cavage
+Patrick Mooney
+Rob Gulewich
diff --git a/node_modules/assert-plus/CHANGES.md b/node_modules/assert-plus/CHANGES.md
new file mode 100644
index 0000000..d249d9b
--- /dev/null
+++ b/node_modules/assert-plus/CHANGES.md
@@ -0,0 +1,8 @@
+# assert-plus Changelog
+
+## 0.2.0
+
+- Fix `assert.object(null)` so it throws
+- Fix optional/arrayOf exports for non-type-of asserts
+- Add optiona/arrayOf exports for Stream/Date/Regex/uuid
+- Add basic unit test coverage
diff --git a/node_modules/assert-plus/README.md b/node_modules/assert-plus/README.md
new file mode 100644
index 0000000..0b39593
--- /dev/null
+++ b/node_modules/assert-plus/README.md
@@ -0,0 +1,155 @@
+# assert-plus
+
+This library is a super small wrapper over node's assert module that has two
+things: (1) the ability to disable assertions with the environment variable
+NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like
+`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks
+like this:
+
+```javascript
+ var assert = require('assert-plus');
+
+ function fooAccount(options, callback) {
+ assert.object(options, 'options');
+ assert.number(options.id, 'options.id');
+ assert.bool(options.isManager, 'options.isManager');
+ assert.string(options.name, 'options.name');
+ assert.arrayOfString(options.email, 'options.email');
+ assert.func(callback, 'callback');
+
+ // Do stuff
+ callback(null, {});
+ }
+```
+
+# API
+
+All methods that *aren't* part of node's core assert API are simply assumed to
+take an argument, and then a string 'name' that's not a message; `AssertionError`
+will be thrown if the assertion fails with a message like:
+
+ AssertionError: foo (string) is required
+ at test (/home/mark/work/foo/foo.js:3:9)
+ at Object. (/home/mark/work/foo/foo.js:15:1)
+ at Module._compile (module.js:446:26)
+ at Object..js (module.js:464:10)
+ at Module.load (module.js:353:31)
+ at Function._load (module.js:311:12)
+ at Array.0 (module.js:484:10)
+ at EventEmitter._tickCallback (node.js:190:38)
+
+from:
+
+```javascript
+ function test(foo) {
+ assert.string(foo, 'foo');
+ }
+```
+
+There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`:
+
+```javascript
+ function test(foo) {
+ assert.arrayOfString(foo, 'foo');
+ }
+```
+
+You can assert IFF an argument is not `undefined` (i.e., an optional arg):
+
+```javascript
+ assert.optionalString(foo, 'foo');
+```
+
+Lastly, you can opt-out of assertion checking altogether by setting the
+environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have
+lots of assertions, and don't want to pay `typeof ()` taxes to v8 in
+production. Be advised: The standard functions re-exported from `assert` are
+also disabled in assert-plus if NDEBUG is specified. Using them directly from
+the `assert` module avoids this behavior.
+
+The complete list of APIs is:
+
+* assert.array
+* assert.bool
+* assert.buffer
+* assert.func
+* assert.number
+* assert.object
+* assert.string
+* assert.stream
+* assert.date
+* assert.regex
+* assert.uuid
+* assert.arrayOfArray
+* assert.arrayOfBool
+* assert.arrayOfBuffer
+* assert.arrayOfFunc
+* assert.arrayOfNumber
+* assert.arrayOfObject
+* assert.arrayOfString
+* assert.arrayOfStream
+* assert.arrayOfDate
+* assert.arrayOfUuid
+* assert.optionalArray
+* assert.optionalBool
+* assert.optionalBuffer
+* assert.optionalFunc
+* assert.optionalNumber
+* assert.optionalObject
+* assert.optionalString
+* assert.optionalStream
+* assert.optionalDate
+* assert.optionalUuid
+* assert.optionalArrayOfArray
+* assert.optionalArrayOfBool
+* assert.optionalArrayOfBuffer
+* assert.optionalArrayOfFunc
+* assert.optionalArrayOfNumber
+* assert.optionalArrayOfObject
+* assert.optionalArrayOfString
+* assert.optionalArrayOfStream
+* assert.optionalArrayOfDate
+* assert.optionalArrayOfUuid
+* assert.AssertionError
+* assert.fail
+* assert.ok
+* assert.equal
+* assert.notEqual
+* assert.deepEqual
+* assert.notDeepEqual
+* assert.strictEqual
+* assert.notStrictEqual
+* assert.throws
+* assert.doesNotThrow
+* assert.ifError
+
+# Installation
+
+ npm install assert-plus
+
+## License
+
+The MIT License (MIT)
+Copyright (c) 2012 Mark Cavage
+
+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.
+
+## Bugs
+
+See .
diff --git a/node_modules/assert-plus/assert.js b/node_modules/assert-plus/assert.js
new file mode 100644
index 0000000..6bce4d8
--- /dev/null
+++ b/node_modules/assert-plus/assert.js
@@ -0,0 +1,206 @@
+// Copyright (c) 2012, Mark Cavage. All rights reserved.
+// Copyright 2015 Joyent, Inc.
+
+var assert = require('assert');
+var Stream = require('stream').Stream;
+var util = require('util');
+
+
+///--- Globals
+
+/* JSSTYLED */
+var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
+
+
+///--- Internal
+
+function _capitalize(str) {
+ return (str.charAt(0).toUpperCase() + str.slice(1));
+}
+
+function _toss(name, expected, oper, arg, actual) {
+ throw new assert.AssertionError({
+ message: util.format('%s (%s) is required', name, expected),
+ actual: (actual === undefined) ? typeof (arg) : actual(arg),
+ expected: expected,
+ operator: oper || '===',
+ stackStartFunction: _toss.caller
+ });
+}
+
+function _getClass(arg) {
+ return (Object.prototype.toString.call(arg).slice(8, -1));
+}
+
+function noop() {
+ // Why even bother with asserts?
+}
+
+
+///--- Exports
+
+var types = {
+ bool: {
+ check: function (arg) { return typeof (arg) === 'boolean'; }
+ },
+ func: {
+ check: function (arg) { return typeof (arg) === 'function'; }
+ },
+ string: {
+ check: function (arg) { return typeof (arg) === 'string'; }
+ },
+ object: {
+ check: function (arg) {
+ return typeof (arg) === 'object' && arg !== null;
+ }
+ },
+ number: {
+ check: function (arg) {
+ return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
+ }
+ },
+ buffer: {
+ check: function (arg) { return Buffer.isBuffer(arg); },
+ operator: 'Buffer.isBuffer'
+ },
+ array: {
+ check: function (arg) { return Array.isArray(arg); },
+ operator: 'Array.isArray'
+ },
+ stream: {
+ check: function (arg) { return arg instanceof Stream; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ date: {
+ check: function (arg) { return arg instanceof Date; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ regexp: {
+ check: function (arg) { return arg instanceof RegExp; },
+ operator: 'instanceof',
+ actual: _getClass
+ },
+ uuid: {
+ check: function (arg) {
+ return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
+ },
+ operator: 'isUUID'
+ }
+};
+
+function _setExports(ndebug) {
+ var keys = Object.keys(types);
+ var out;
+
+ /* re-export standard assert */
+ if (process.env.NODE_NDEBUG) {
+ out = noop;
+ } else {
+ out = function (arg, msg) {
+ if (!arg) {
+ _toss(msg, 'true', arg);
+ }
+ };
+ }
+
+ /* standard checks */
+ keys.forEach(function (k) {
+ if (ndebug) {
+ out[k] = noop;
+ return;
+ }
+ var type = types[k];
+ out[k] = function (arg, msg) {
+ if (!type.check(arg)) {
+ _toss(msg, k, type.operator, arg, type.actual);
+ }
+ };
+ });
+
+ /* optional checks */
+ keys.forEach(function (k) {
+ var name = 'optional' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
+ }
+ var type = types[k];
+ out[name] = function (arg, msg) {
+ if (arg === undefined || arg === null) {
+ return;
+ }
+ if (!type.check(arg)) {
+ _toss(msg, k, type.operator, arg, type.actual);
+ }
+ };
+ });
+
+ /* arrayOf checks */
+ keys.forEach(function (k) {
+ var name = 'arrayOf' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
+ }
+ var type = types[k];
+ var expected = '[' + k + ']';
+ out[name] = function (arg, msg) {
+ if (!Array.isArray(arg)) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ var i;
+ for (i = 0; i < arg.length; i++) {
+ if (!type.check(arg[i])) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ }
+ };
+ });
+
+ /* optionalArrayOf checks */
+ keys.forEach(function (k) {
+ var name = 'optionalArrayOf' + _capitalize(k);
+ if (ndebug) {
+ out[name] = noop;
+ return;
+ }
+ var type = types[k];
+ var expected = '[' + k + ']';
+ out[name] = function (arg, msg) {
+ if (arg === undefined || arg === null) {
+ return;
+ }
+ if (!Array.isArray(arg)) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ var i;
+ for (i = 0; i < arg.length; i++) {
+ if (!type.check(arg[i])) {
+ _toss(msg, expected, type.operator, arg, type.actual);
+ }
+ }
+ };
+ });
+
+ /* re-export built-in assertions */
+ Object.keys(assert).forEach(function (k) {
+ if (k === 'AssertionError') {
+ out[k] = assert[k];
+ return;
+ }
+ if (ndebug) {
+ out[k] = noop;
+ return;
+ }
+ out[k] = assert[k];
+ });
+
+ /* export ourselves (for unit tests _only_) */
+ out._setExports = _setExports;
+
+ return out;
+}
+
+module.exports = _setExports(process.env.NODE_NDEBUG);
diff --git a/node_modules/assert-plus/package.json b/node_modules/assert-plus/package.json
new file mode 100644
index 0000000..7654fa9
--- /dev/null
+++ b/node_modules/assert-plus/package.json
@@ -0,0 +1,23 @@
+{
+ "author": "Mark Cavage ",
+ "name": "assert-plus",
+ "description": "Extra assertions on top of node's assert module",
+ "version": "0.2.0",
+ "license": "MIT",
+ "main": "./assert.js",
+ "devDependencies": {
+ "tape": "4.2.2",
+ "faucet": "0.0.1"
+ },
+ "optionalDependencies": {},
+ "scripts": {
+ "test": "./node_modules/.bin/tape tests/*.js | ./node_modules/.bin/faucet"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mcavage/node-assert-plus.git"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+}
diff --git a/node_modules/assert/.npmignore b/node_modules/assert/.npmignore
new file mode 100644
index 0000000..3c3629e
--- /dev/null
+++ b/node_modules/assert/.npmignore
@@ -0,0 +1 @@
+node_modules
diff --git a/node_modules/assert/.travis.yml b/node_modules/assert/.travis.yml
new file mode 100644
index 0000000..a690ffd
--- /dev/null
+++ b/node_modules/assert/.travis.yml
@@ -0,0 +1,31 @@
+language: node_js
+before_install:
+ - npm install -g npm@2
+ - npm install -g npm
+matrix:
+ include:
+ - node_js: '0.8'
+ env: TASK=test-node
+ - node_js: '0.10'
+ env: TASK=test-node
+ - node_js: '0.11'
+ env: TASK=test-node
+ - node_js: '0.12'
+ env: TASK=test-node
+ - node_js: 1
+ env: TASK=test-node
+ - node_js: 2
+ env: TASK=test-node
+ - node_js: 3
+ env: TASK=test-node
+ - node_js: 4
+ env: TASK=test-node
+ - node_js: 5
+ env: TASK=test-node
+ - node_js: '0.10'
+ env: TASK=test-browser
+script: "npm run $TASK"
+env:
+ global:
+ - secure: qThuKBZQtkooAvzaYldECGNqvKGPRTnXx62IVyhSbFlsCY1VCmjhLldhyPDiZQ3JqL1XvSkK8OMDupiHqZnNE0nGijoO4M/kaEdjBB+jpjg3f8I6te2SNU935SbkfY9KHAaFXMZwdcq7Fk932AxWEu+FMSDM+080wNKpEATXDe4=
+ - secure: O/scKjHLRcPN5ILV5qsSkksQ7qcZQdHWEUUPItmj/4+vmCc28bHpicoUxXG5A96iHvkBbdmky/nGCg464ZaNLk68m6hfEMDAR3J6mhM2Pf5C4QI/LlFlR1fob9sQ8lztwSGOItwdK8Rfrgb30RRVV71f6FxnaJ6PKMuMNT5S1AQ=
diff --git a/node_modules/assert/.zuul.yml b/node_modules/assert/.zuul.yml
new file mode 100644
index 0000000..9353eb7
--- /dev/null
+++ b/node_modules/assert/.zuul.yml
@@ -0,0 +1,13 @@
+ui: mocha-qunit
+tunnel: ngrok
+browsers:
+ - name: chrome
+ version: latest
+ - name: firefox
+ version: latest
+ - name: safari
+ version: latest
+ - name: ie
+ version: 9..latest
+ - name: microsoftedge
+ version: latest
diff --git a/node_modules/assert/LICENSE b/node_modules/assert/LICENSE
new file mode 100644
index 0000000..e3d4e69
--- /dev/null
+++ b/node_modules/assert/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/assert/README.md b/node_modules/assert/README.md
new file mode 100644
index 0000000..6d252ab
--- /dev/null
+++ b/node_modules/assert/README.md
@@ -0,0 +1,64 @@
+# assert
+
+[![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert)
+
+This module is used for writing unit tests for your applications, you can access it with require('assert').
+
+The API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html)
+
+## assert.fail(actual, expected, message, operator)
+Throws an exception that displays the values for actual and expected separated by the provided operator.
+
+## assert(value, message), assert.ok(value, [message])
+Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
+
+## assert.equal(actual, expected, [message])
+Tests shallow, coercive equality with the equal comparison operator ( == ).
+
+## assert.notEqual(actual, expected, [message])
+Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
+
+## assert.deepEqual(actual, expected, [message])
+Tests for deep equality.
+
+## assert.notDeepEqual(actual, expected, [message])
+Tests for any deep inequality.
+
+## assert.strictEqual(actual, expected, [message])
+Tests strict equality, as determined by the strict equality operator ( === )
+
+## assert.notStrictEqual(actual, expected, [message])
+Tests strict non-equality, as determined by the strict not equal operator ( !== )
+
+## assert.throws(block, [error], [message])
+Expects block to throw an error. error can be constructor, regexp or validation function.
+
+Validate instanceof using constructor:
+
+```javascript
+assert.throws(function() { throw new Error("Wrong value"); }, Error);
+```
+
+Validate error message using RegExp:
+
+```javascript
+assert.throws(function() { throw new Error("Wrong value"); }, /value/);
+```
+
+Custom error validation:
+
+```javascript
+assert.throws(function() {
+ throw new Error("Wrong value");
+}, function(err) {
+ if ( (err instanceof Error) && /value/.test(err) ) {
+ return true;
+ }
+}, "unexpected error");
+```
+
+## assert.doesNotThrow(block, [message])
+Expects block not to throw an error, see assert.throws for details.
+
+## assert.ifError(value)
+Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
diff --git a/node_modules/assert/assert.js b/node_modules/assert/assert.js
new file mode 100644
index 0000000..fa1b910
--- /dev/null
+++ b/node_modules/assert/assert.js
@@ -0,0 +1,490 @@
+'use strict';
+
+// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
+// original notice:
+
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+function compare(a, b) {
+ if (a === b) {
+ return 0;
+ }
+
+ var x = a.length;
+ var y = b.length;
+
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i];
+ y = b[i];
+ break;
+ }
+ }
+
+ if (x < y) {
+ return -1;
+ }
+ if (y < x) {
+ return 1;
+ }
+ return 0;
+}
+function isBuffer(b) {
+ if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
+ return global.Buffer.isBuffer(b);
+ }
+ return !!(b != null && b._isBuffer);
+}
+
+// based on node assert, original notice:
+
+// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
+//
+// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
+//
+// Originally from narwhal.js (http://narwhaljs.org)
+// Copyright (c) 2009 Thomas Robinson <280north.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 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 util = require('util/');
+var hasOwn = Object.prototype.hasOwnProperty;
+var pSlice = Array.prototype.slice;
+var functionsHaveNames = (function () {
+ return function foo() {}.name === 'foo';
+}());
+function pToString (obj) {
+ return Object.prototype.toString.call(obj);
+}
+function isView(arrbuf) {
+ if (isBuffer(arrbuf)) {
+ return false;
+ }
+ if (typeof global.ArrayBuffer !== 'function') {
+ return false;
+ }
+ if (typeof ArrayBuffer.isView === 'function') {
+ return ArrayBuffer.isView(arrbuf);
+ }
+ if (!arrbuf) {
+ return false;
+ }
+ if (arrbuf instanceof DataView) {
+ return true;
+ }
+ if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
+ return true;
+ }
+ return false;
+}
+// 1. The assert module provides functions that throw
+// AssertionError's when particular conditions are not met. The
+// assert module must conform to the following interface.
+
+var assert = module.exports = ok;
+
+// 2. The AssertionError is defined in assert.
+// new assert.AssertionError({ message: message,
+// actual: actual,
+// expected: expected })
+
+var regex = /\s*function\s+([^\(\s]*)\s*/;
+// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
+function getName(func) {
+ if (!util.isFunction(func)) {
+ return;
+ }
+ if (functionsHaveNames) {
+ return func.name;
+ }
+ var str = func.toString();
+ var match = str.match(regex);
+ return match && match[1];
+}
+assert.AssertionError = function AssertionError(options) {
+ this.name = 'AssertionError';
+ this.actual = options.actual;
+ this.expected = options.expected;
+ this.operator = options.operator;
+ if (options.message) {
+ this.message = options.message;
+ this.generatedMessage = false;
+ } else {
+ this.message = getMessage(this);
+ this.generatedMessage = true;
+ }
+ var stackStartFunction = options.stackStartFunction || fail;
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, stackStartFunction);
+ } else {
+ // non v8 browsers so we can have a stacktrace
+ var err = new Error();
+ if (err.stack) {
+ var out = err.stack;
+
+ // try to strip useless frames
+ var fn_name = getName(stackStartFunction);
+ var idx = out.indexOf('\n' + fn_name);
+ if (idx >= 0) {
+ // once we have located the function frame
+ // we need to strip out everything before it (and its line)
+ var next_line = out.indexOf('\n', idx + 1);
+ out = out.substring(next_line + 1);
+ }
+
+ this.stack = out;
+ }
+ }
+};
+
+// assert.AssertionError instanceof Error
+util.inherits(assert.AssertionError, Error);
+
+function truncate(s, n) {
+ if (typeof s === 'string') {
+ return s.length < n ? s : s.slice(0, n);
+ } else {
+ return s;
+ }
+}
+function inspect(something) {
+ if (functionsHaveNames || !util.isFunction(something)) {
+ return util.inspect(something);
+ }
+ var rawname = getName(something);
+ var name = rawname ? ': ' + rawname : '';
+ return '[Function' + name + ']';
+}
+function getMessage(self) {
+ return truncate(inspect(self.actual), 128) + ' ' +
+ self.operator + ' ' +
+ truncate(inspect(self.expected), 128);
+}
+
+// At present only the three keys mentioned above are used and
+// understood by the spec. Implementations or sub modules can pass
+// other keys to the AssertionError's constructor - they will be
+// ignored.
+
+// 3. All of the following functions must throw an AssertionError
+// when a corresponding condition is not met, with a message that
+// may be undefined if not provided. All assertion methods provide
+// both the actual and expected values to the assertion error for
+// display purposes.
+
+function fail(actual, expected, message, operator, stackStartFunction) {
+ throw new assert.AssertionError({
+ message: message,
+ actual: actual,
+ expected: expected,
+ operator: operator,
+ stackStartFunction: stackStartFunction
+ });
+}
+
+// EXTENSION! allows for well behaved errors defined elsewhere.
+assert.fail = fail;
+
+// 4. Pure assertion tests whether a value is truthy, as determined
+// by !!guard.
+// assert.ok(guard, message_opt);
+// This statement is equivalent to assert.equal(true, !!guard,
+// message_opt);. To test strictly for the value true, use
+// assert.strictEqual(true, guard, message_opt);.
+
+function ok(value, message) {
+ if (!value) fail(value, true, message, '==', assert.ok);
+}
+assert.ok = ok;
+
+// 5. The equality assertion tests shallow, coercive equality with
+// ==.
+// assert.equal(actual, expected, message_opt);
+
+assert.equal = function equal(actual, expected, message) {
+ if (actual != expected) fail(actual, expected, message, '==', assert.equal);
+};
+
+// 6. The non-equality assertion tests for whether two objects are not equal
+// with != assert.notEqual(actual, expected, message_opt);
+
+assert.notEqual = function notEqual(actual, expected, message) {
+ if (actual == expected) {
+ fail(actual, expected, message, '!=', assert.notEqual);
+ }
+};
+
+// 7. The equivalence assertion tests a deep equality relation.
+// assert.deepEqual(actual, expected, message_opt);
+
+assert.deepEqual = function deepEqual(actual, expected, message) {
+ if (!_deepEqual(actual, expected, false)) {
+ fail(actual, expected, message, 'deepEqual', assert.deepEqual);
+ }
+};
+
+assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
+ if (!_deepEqual(actual, expected, true)) {
+ fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
+ }
+};
+
+function _deepEqual(actual, expected, strict, memos) {
+ // 7.1. All identical values are equivalent, as determined by ===.
+ if (actual === expected) {
+ return true;
+ } else if (isBuffer(actual) && isBuffer(expected)) {
+ return compare(actual, expected) === 0;
+
+ // 7.2. If the expected value is a Date object, the actual value is
+ // equivalent if it is also a Date object that refers to the same time.
+ } else if (util.isDate(actual) && util.isDate(expected)) {
+ return actual.getTime() === expected.getTime();
+
+ // 7.3 If the expected value is a RegExp object, the actual value is
+ // equivalent if it is also a RegExp object with the same source and
+ // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
+ } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
+ return actual.source === expected.source &&
+ actual.global === expected.global &&
+ actual.multiline === expected.multiline &&
+ actual.lastIndex === expected.lastIndex &&
+ actual.ignoreCase === expected.ignoreCase;
+
+ // 7.4. Other pairs that do not both pass typeof value == 'object',
+ // equivalence is determined by ==.
+ } else if ((actual === null || typeof actual !== 'object') &&
+ (expected === null || typeof expected !== 'object')) {
+ return strict ? actual === expected : actual == expected;
+
+ // If both values are instances of typed arrays, wrap their underlying
+ // ArrayBuffers in a Buffer each to increase performance
+ // This optimization requires the arrays to have the same type as checked by
+ // Object.prototype.toString (aka pToString). Never perform binary
+ // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
+ // bit patterns are not identical.
+ } else if (isView(actual) && isView(expected) &&
+ pToString(actual) === pToString(expected) &&
+ !(actual instanceof Float32Array ||
+ actual instanceof Float64Array)) {
+ return compare(new Uint8Array(actual.buffer),
+ new Uint8Array(expected.buffer)) === 0;
+
+ // 7.5 For all other Object pairs, including Array objects, equivalence is
+ // determined by having the same number of owned properties (as verified
+ // with Object.prototype.hasOwnProperty.call), the same set of keys
+ // (although not necessarily the same order), equivalent values for every
+ // corresponding key, and an identical 'prototype' property. Note: this
+ // accounts for both named and indexed properties on Arrays.
+ } else if (isBuffer(actual) !== isBuffer(expected)) {
+ return false;
+ } else {
+ memos = memos || {actual: [], expected: []};
+
+ var actualIndex = memos.actual.indexOf(actual);
+ if (actualIndex !== -1) {
+ if (actualIndex === memos.expected.indexOf(expected)) {
+ return true;
+ }
+ }
+
+ memos.actual.push(actual);
+ memos.expected.push(expected);
+
+ return objEquiv(actual, expected, strict, memos);
+ }
+}
+
+function isArguments(object) {
+ return Object.prototype.toString.call(object) == '[object Arguments]';
+}
+
+function objEquiv(a, b, strict, actualVisitedObjects) {
+ if (a === null || a === undefined || b === null || b === undefined)
+ return false;
+ // if one is a primitive, the other must be same
+ if (util.isPrimitive(a) || util.isPrimitive(b))
+ return a === b;
+ if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
+ return false;
+ var aIsArgs = isArguments(a);
+ var bIsArgs = isArguments(b);
+ if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
+ return false;
+ if (aIsArgs) {
+ a = pSlice.call(a);
+ b = pSlice.call(b);
+ return _deepEqual(a, b, strict);
+ }
+ var ka = objectKeys(a);
+ var kb = objectKeys(b);
+ var key, i;
+ // having the same number of owned properties (keys incorporates
+ // hasOwnProperty)
+ if (ka.length !== kb.length)
+ return false;
+ //the same set of keys (although not necessarily the same order),
+ ka.sort();
+ kb.sort();
+ //~~~cheap key test
+ for (i = ka.length - 1; i >= 0; i--) {
+ if (ka[i] !== kb[i])
+ return false;
+ }
+ //equivalent values for every corresponding key, and
+ //~~~possibly expensive deep test
+ for (i = ka.length - 1; i >= 0; i--) {
+ key = ka[i];
+ if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
+ return false;
+ }
+ return true;
+}
+
+// 8. The non-equivalence assertion tests for any deep inequality.
+// assert.notDeepEqual(actual, expected, message_opt);
+
+assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
+ if (_deepEqual(actual, expected, false)) {
+ fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
+ }
+};
+
+assert.notDeepStrictEqual = notDeepStrictEqual;
+function notDeepStrictEqual(actual, expected, message) {
+ if (_deepEqual(actual, expected, true)) {
+ fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
+ }
+}
+
+
+// 9. The strict equality assertion tests strict equality, as determined by ===.
+// assert.strictEqual(actual, expected, message_opt);
+
+assert.strictEqual = function strictEqual(actual, expected, message) {
+ if (actual !== expected) {
+ fail(actual, expected, message, '===', assert.strictEqual);
+ }
+};
+
+// 10. The strict non-equality assertion tests for strict inequality, as
+// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
+
+assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
+ if (actual === expected) {
+ fail(actual, expected, message, '!==', assert.notStrictEqual);
+ }
+};
+
+function expectedException(actual, expected) {
+ if (!actual || !expected) {
+ return false;
+ }
+
+ if (Object.prototype.toString.call(expected) == '[object RegExp]') {
+ return expected.test(actual);
+ }
+
+ try {
+ if (actual instanceof expected) {
+ return true;
+ }
+ } catch (e) {
+ // Ignore. The instanceof check doesn't work for arrow functions.
+ }
+
+ if (Error.isPrototypeOf(expected)) {
+ return false;
+ }
+
+ return expected.call({}, actual) === true;
+}
+
+function _tryBlock(block) {
+ var error;
+ try {
+ block();
+ } catch (e) {
+ error = e;
+ }
+ return error;
+}
+
+function _throws(shouldThrow, block, expected, message) {
+ var actual;
+
+ if (typeof block !== 'function') {
+ throw new TypeError('"block" argument must be a function');
+ }
+
+ if (typeof expected === 'string') {
+ message = expected;
+ expected = null;
+ }
+
+ actual = _tryBlock(block);
+
+ message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
+ (message ? ' ' + message : '.');
+
+ if (shouldThrow && !actual) {
+ fail(actual, expected, 'Missing expected exception' + message);
+ }
+
+ var userProvidedMessage = typeof message === 'string';
+ var isUnwantedException = !shouldThrow && util.isError(actual);
+ var isUnexpectedException = !shouldThrow && actual && !expected;
+
+ if ((isUnwantedException &&
+ userProvidedMessage &&
+ expectedException(actual, expected)) ||
+ isUnexpectedException) {
+ fail(actual, expected, 'Got unwanted exception' + message);
+ }
+
+ if ((shouldThrow && actual && expected &&
+ !expectedException(actual, expected)) || (!shouldThrow && actual)) {
+ throw actual;
+ }
+}
+
+// 11. Expected to throw an error:
+// assert.throws(block, Error_opt, message_opt);
+
+assert.throws = function(block, /*optional*/error, /*optional*/message) {
+ _throws(true, block, error, message);
+};
+
+// EXTENSION! This is annoying to write outside this module.
+assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
+ _throws(false, block, error, message);
+};
+
+assert.ifError = function(err) { if (err) throw err; };
+
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ if (hasOwn.call(obj, key)) keys.push(key);
+ }
+ return keys;
+};
diff --git a/node_modules/assert/package.json b/node_modules/assert/package.json
new file mode 100644
index 0000000..bc6a405
--- /dev/null
+++ b/node_modules/assert/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "assert",
+ "description": "commonjs assert - node.js api compatible",
+ "keywords": [
+ "assert"
+ ],
+ "version": "1.4.1",
+ "homepage": "https://github.com/defunctzombie/commonjs-assert",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/defunctzombie/commonjs-assert.git"
+ },
+ "main": "./assert.js",
+ "dependencies": {
+ "util": "0.10.3"
+ },
+ "devDependencies": {
+ "mocha": "~1.21.4",
+ "zuul": "~3.10.0",
+ "zuul-ngrok": "^4.0.0"
+ },
+ "license": "MIT",
+ "scripts": {
+ "test-node": "mocha --ui qunit test.js",
+ "test-browser": "zuul -- test.js",
+ "test": "npm run test-node && npm run test-browser",
+ "test-native": "TEST_NATIVE=true mocha --ui qunit test.js",
+ "browser-local": "zuul --no-coverage --local 8000 -- test.js"
+ }
+}
diff --git a/node_modules/assert/test.js b/node_modules/assert/test.js
new file mode 100644
index 0000000..8c7c5a4
--- /dev/null
+++ b/node_modules/assert/test.js
@@ -0,0 +1,345 @@
+// 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 nodeAssert = require('assert');
+var ourAssert = require('./');
+var keys = Object.keys;
+if (process.env.TEST_NATIVE === true) {
+ tests(nodeAssert, 'node assert');
+} else {
+ tests(ourAssert, 'our assert');
+}
+
+function makeBlock(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function() {
+ return f.apply(this, args);
+ };
+}
+
+function tests (assert, what) {
+ test('assert.ok', function () {
+ assert.throws(makeBlock(assert, false), assert.AssertionError, 'ok(false)');
+
+ assert.doesNotThrow(makeBlock(assert, true), assert.AssertionError, 'ok(true)');
+
+ assert.doesNotThrow(makeBlock(assert, 'test', 'ok(\'test\')'));
+
+ assert.throws(makeBlock(assert.ok, false),
+ assert.AssertionError, 'ok(false)');
+
+ assert.doesNotThrow(makeBlock(assert.ok, true),
+ assert.AssertionError, 'ok(true)');
+
+ assert.doesNotThrow(makeBlock(assert.ok, 'test'), 'ok(\'test\')');
+ });
+
+ test('assert.equal', function () {
+ assert.throws(makeBlock(assert.equal, true, false), assert.AssertionError, 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.equal, null, null), 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.equal, undefined, undefined), 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.equal, null, undefined), 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.equal, true, true), 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.equal, 2, '2'), 'equal');
+
+ assert.doesNotThrow(makeBlock(assert.notEqual, true, false), 'notEqual');
+
+ assert.throws(makeBlock(assert.notEqual, true, true),
+ assert.AssertionError, 'notEqual');
+ });
+
+ test('assert.strictEqual', function () {
+ assert.throws(makeBlock(assert.strictEqual, 2, '2'),
+ assert.AssertionError, 'strictEqual');
+
+ assert.throws(makeBlock(assert.strictEqual, null, undefined),
+ assert.AssertionError, 'strictEqual');
+
+ assert.doesNotThrow(makeBlock(assert.notStrictEqual, 2, '2'), 'notStrictEqual');
+ });
+
+ test('assert.deepStrictEqual', function () {
+ assert.throws(makeBlock(assert.deepStrictEqual, [2], ['2']),
+ assert.AssertionError, 'deepStrictEqual');
+
+ assert.throws(makeBlock(assert.deepStrictEqual, [null], [undefined]),
+ assert.AssertionError, 'deepStrictEqual');
+
+ assert.doesNotThrow(makeBlock(assert.notDeepStrictEqual, [2], ['2']), 'notDeepStrictEqual');
+ });
+
+ test('assert.deepEqual - 7.2', function () {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new Date(2000, 3, 14),
+ new Date(2000, 3, 14)), 'deepEqual date');
+
+ assert.throws(makeBlock(assert.deepEqual, new Date(), new Date(2000, 3, 14)),
+ assert.AssertionError,
+ 'deepEqual date');
+ });
+
+ test('assert.deepEqual - 7.3', function () {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, /a/, /a/));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, /a/g, /a/g));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, /a/i, /a/i));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, /a/m, /a/m));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, /a/igm, /a/igm));
+ assert.throws(makeBlock(assert.deepEqual, /ab/, /a/));
+ assert.throws(makeBlock(assert.deepEqual, /a/g, /a/));
+ assert.throws(makeBlock(assert.deepEqual, /a/i, /a/));
+ assert.throws(makeBlock(assert.deepEqual, /a/m, /a/));
+ assert.throws(makeBlock(assert.deepEqual, /a/igm, /a/im));
+
+ var re1 = /a/;
+ re1.lastIndex = 3;
+ assert.throws(makeBlock(assert.deepEqual, re1, /a/));
+ });
+
+ test('assert.deepEqual - 7.4', function () {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, 4, '4'), 'deepEqual == check');
+ assert.doesNotThrow(makeBlock(assert.deepEqual, true, 1), 'deepEqual == check');
+ assert.throws(makeBlock(assert.deepEqual, 4, '5'),
+ assert.AssertionError,
+ 'deepEqual == check');
+ });
+
+ test('assert.deepEqual - 7.5', function () {
+ // having the same number of owned properties && the same set of keys
+ assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4}, {a: 4}));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'}));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, [4], ['4']));
+ assert.throws(makeBlock(assert.deepEqual, {a: 4}, {a: 4, b: true}),
+ assert.AssertionError);
+ assert.doesNotThrow(makeBlock(assert.deepEqual, ['a'], {0: 'a'}));
+ //(although not necessarily the same order),
+ assert.doesNotThrow(makeBlock(assert.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4}));
+ var a1 = [1, 2, 3];
+ var a2 = [1, 2, 3];
+ a1.a = 'test';
+ a1.b = true;
+ a2.b = true;
+ a2.a = 'test';
+ assert.throws(makeBlock(assert.deepEqual, keys(a1), keys(a2)),
+ assert.AssertionError);
+ assert.doesNotThrow(makeBlock(assert.deepEqual, a1, a2));
+ });
+
+ test('assert.deepEqual - ES6 primitives', function () {
+ assert.throws(makeBlock(assert.deepEqual, null, {}), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, undefined, {}), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, 'a', ['a']), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, 'a', {0: 'a'}), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, 1, {}), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, true, {}), assert.AssertionError);
+ if (typeof Symbol === 'symbol') {
+ assert.throws(makeBlock(assert.deepEqual, Symbol(), {}), assert.AssertionError);
+ }
+ });
+
+ test('assert.deepEqual - object wrappers', function () {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), ['a']));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new String('a'), {0: 'a'}));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new Number(1), {}));
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new Boolean(true), {}));
+ });
+
+ test('assert.deepEqual - Buffers', function () {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new Buffer([1, 2, 3]), new Buffer([1, 2, 3])));
+ if (typeof global.Uint8Array === 'function') {
+ assert.throws(makeBlock(assert.deepEqual, new Buffer([1, 2, 3]), new Uint8Array([1, 2, 3])));
+ }
+ if (typeof global.Uint16Array === 'function') {
+ assert.doesNotThrow(makeBlock(assert.deepEqual, new Uint16Array([1, 2, 3]), new Uint16Array([1, 2, 3])));
+ }
+ });
+
+ function thrower(errorConstructor) {
+ throw new errorConstructor('test');
+ }
+
+ test('assert - Testing the throwing', function () {
+ var aethrow = makeBlock(thrower, assert.AssertionError);
+ aethrow = makeBlock(thrower, assert.AssertionError);
+
+ // the basic calls work
+ assert.throws(makeBlock(thrower, assert.AssertionError),
+ assert.AssertionError, 'message');
+ assert.throws(makeBlock(thrower, assert.AssertionError), assert.AssertionError);
+ assert.throws(makeBlock(thrower, assert.AssertionError));
+
+ // if not passing an error, catch all.
+ assert.throws(makeBlock(thrower, TypeError));
+
+ // when passing a type, only catch errors of the appropriate type
+ var threw = false;
+ try {
+ assert.throws(makeBlock(thrower, TypeError), assert.AssertionError);
+ } catch (e) {
+ threw = true;
+ assert.ok(e instanceof TypeError, 'type');
+ }
+ assert.equal(true, threw,
+ 'a.throws with an explicit error is eating extra errors',
+ assert.AssertionError);
+ threw = false;
+
+ // doesNotThrow should pass through all errors
+ try {
+ assert.doesNotThrow(makeBlock(thrower, TypeError), assert.AssertionError);
+ } catch (e) {
+ threw = true;
+ assert.ok(e instanceof TypeError);
+ }
+ assert.equal(true, threw,
+ 'a.doesNotThrow with an explicit error is eating extra errors');
+
+ // key difference is that throwing our correct error makes an assertion error
+ try {
+ assert.doesNotThrow(makeBlock(thrower, TypeError), TypeError);
+ } catch (e) {
+ threw = true;
+ assert.ok(e instanceof assert.AssertionError);
+ }
+ assert.equal(true, threw,
+ 'a.doesNotThrow is not catching type matching errors');
+ });
+
+ test('assert.ifError', function () {
+ assert.throws(function() {assert.ifError(new Error('test error'))});
+ assert.doesNotThrow(function() {assert.ifError(null)});
+ assert.doesNotThrow(function() {assert.ifError()});
+ });
+
+ test('assert - make sure that validating using constructor really works', function () {
+ var threw = false;
+ try {
+ assert.throws(
+ function() {
+ throw ({});
+ },
+ Array
+ );
+ } catch (e) {
+ threw = true;
+ }
+ assert.ok(threw, 'wrong constructor validation');
+ });
+
+ test('assert - use a RegExp to validate error message', function () {
+ assert.throws(makeBlock(thrower, TypeError), /test/);
+ });
+
+ test('assert - se a fn to validate error object', function () {
+ assert.throws(makeBlock(thrower, TypeError), function(err) {
+ if ((err instanceof TypeError) && /test/.test(err)) {
+ return true;
+ }
+ });
+ });
+
+ test('assert - Make sure deepEqual doesn\'t loop forever on circular refs', function () {
+ var b = {};
+ b.b = b;
+
+ var c = {};
+ c.b = c;
+
+ var gotError = false;
+ var equal = true;
+ try {
+ equal = assert.deepEqual(b, c);
+ } catch (e) {
+ gotError = true;
+ }
+ assert.ok(gotError || !equal, gotError ? 'got error': 'are equal');
+ });
+
+ test('assert - Ensure reflexivity of deepEqual with `arguments` objects', function() {
+ var args = (function() { return arguments; })();
+ assert.throws(makeBlock(assert.deepEqual, [], args), assert.AssertionError);
+ assert.throws(makeBlock(assert.deepEqual, args, []), assert.AssertionError);
+ });
+
+ test('assert - test assertion message', function () {
+ function testAssertionMessage(actual, expected) {
+ try {
+ assert.equal(actual, '');
+ } catch (e) {
+ assert.equal(e.toString(),
+ ['AssertionError:', expected, '==', '\'\''].join(' '));
+ }
+ }
+ testAssertionMessage(undefined, 'undefined');
+ testAssertionMessage(null, 'null');
+ testAssertionMessage(true, 'true');
+ testAssertionMessage(false, 'false');
+ testAssertionMessage(0, '0');
+ testAssertionMessage(100, '100');
+ testAssertionMessage(NaN, 'NaN');
+ testAssertionMessage(Infinity, 'Infinity');
+ testAssertionMessage(-Infinity, '-Infinity');
+ testAssertionMessage('', '""');
+ testAssertionMessage('foo', '\'foo\'');
+ testAssertionMessage([], '[]');
+ testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]');
+ testAssertionMessage(new Buffer([1, 2, 3]), '');
+ if (typeof global.Uint8Array === 'function' && Object.getOwnPropertyNames( new Uint8Array([])).length === 0) {
+ // todo fix util.inspect
+ testAssertionMessage(new Uint8Array([1, 2, 3]), '{ \'0\': 1, \'1\': 2, \'2\': 3 }');
+ }
+ testAssertionMessage(/a/, '/a/');
+ testAssertionMessage(function f() {}, '[Function: f]');
+ testAssertionMessage({}, '{}');
+ testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }');
+ testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
+ '{ a: NaN, b: Infinity, c: -Infinity }');
+ });
+
+ test('assert - regressions from node.js testcase', function () {
+ var threw = false;
+
+ try {
+ assert.throws(function () {
+ assert.ifError(null);
+ });
+ } catch (e) {
+ threw = true;
+ assert.equal(e.message, 'Missing expected exception..');
+ }
+ assert.ok(threw);
+
+ try {
+ assert.equal(1, 2);
+ } catch (e) {
+ assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2');
+ }
+
+ try {
+ assert.equal(1, 2, 'oh no');
+ } catch (e) {
+ assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no');
+ }
+ });
+}
diff --git a/node_modules/async-each/.npmignore b/node_modules/async-each/.npmignore
new file mode 100644
index 0000000..3887b2b
--- /dev/null
+++ b/node_modules/async-each/.npmignore
@@ -0,0 +1,3 @@
+bower.json
+component.json
+CHANGELOG.md
diff --git a/node_modules/async-each/CHANGELOG.md b/node_modules/async-each/CHANGELOG.md
new file mode 100644
index 0000000..bee2548
--- /dev/null
+++ b/node_modules/async-each/CHANGELOG.md
@@ -0,0 +1,23 @@
+# async-each 1.0.0 (26 November 2015)
+* Bumped version to 1.0.0 (no functional changes)
+
+# async-each 0.1.6 (5 November 2014)
+* Add license to package.json
+
+# async-each 0.1.5 (22 October 2014)
+* Clean up package.json to fix npm warning about `repo`
+
+# async-each 0.1.4 (12 November 2013)
+* Fixed AMD definition.
+
+# async-each 0.1.3 (25 July 2013)
+* Fixed double wrapping of errors.
+
+# async-each 0.1.2 (7 July 2013)
+* Fixed behaviour on empty arrays.
+
+# async-each 0.1.1 (14 June 2013)
+* Wrapped function in closure, enabled strict mode.
+
+# async-each 0.1.0 (14 June 2013)
+* Initial release.
diff --git a/node_modules/async-each/README.md b/node_modules/async-each/README.md
new file mode 100644
index 0000000..a79cbd7
--- /dev/null
+++ b/node_modules/async-each/README.md
@@ -0,0 +1,38 @@
+# async-each
+
+No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach function for JavaScript.
+
+We don't need junky 30K async libs. Really.
+
+For browsers and node.js.
+
+## Installation
+* Just include async-each before your scripts.
+* `npm install async-each` if you’re using node.js.
+* `bower install async-each` if you’re using [Bower](http://bower.io).
+
+## Usage
+
+* `each(array, iterator, callback);` — `Array`, `Function`, `(optional) Function`
+* `iterator(item, next)` receives current item and a callback that will mark the item as done. `next` callback receives optional `error, transformedItem` arguments.
+* `callback(error, transformedArray)` optionally receives first error and transformed result `Array`.
+
+Node.js:
+
+```javascript
+var each = require('async-each');
+each(['a.js', 'b.js', 'c.js'], fs.readFile, function(error, contents) {
+ if (error) console.error(error);
+ console.log('Contents for a, b and c:', contents);
+});
+```
+
+Browser:
+
+```javascript
+window.asyncEach(list, fn, callback);
+```
+
+## License
+
+[The MIT License](https://raw.githubusercontent.com/paulmillr/mit/master/README.md)
diff --git a/node_modules/async-each/index.js b/node_modules/async-each/index.js
new file mode 100644
index 0000000..1c51c95
--- /dev/null
+++ b/node_modules/async-each/index.js
@@ -0,0 +1,38 @@
+// async-each MIT license (by Paul Miller from http://paulmillr.com).
+(function(globals) {
+ 'use strict';
+ var each = function(items, next, callback) {
+ if (!Array.isArray(items)) throw new TypeError('each() expects array as first argument');
+ if (typeof next !== 'function') throw new TypeError('each() expects function as second argument');
+ if (typeof callback !== 'function') callback = Function.prototype; // no-op
+
+ if (items.length === 0) return callback(undefined, items);
+
+ var transformed = new Array(items.length);
+ var count = 0;
+ var returned = false;
+
+ items.forEach(function(item, index) {
+ next(item, function(error, transformedItem) {
+ if (returned) return;
+ if (error) {
+ returned = true;
+ return callback(error);
+ }
+ transformed[index] = transformedItem;
+ count += 1;
+ if (count === items.length) return callback(undefined, transformed);
+ });
+ });
+ };
+
+ if (typeof define !== 'undefined' && define.amd) {
+ define([], function() {
+ return each;
+ }); // RequireJS
+ } else if (typeof module !== 'undefined' && module.exports) {
+ module.exports = each; // CommonJS
+ } else {
+ globals.asyncEach = each; //
+
+```
+
+## Documentation
+
+Some functions are also available in the following forms:
+* `Series` - the same as `` but runs only a single async operation at a time
+* `Limit` - the same as `` but runs a maximum of `limit` async operations at a time
+
+### Collections
+
+* [`each`](#each), `eachSeries`, `eachLimit`
+* [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit`
+* [`map`](#map), `mapSeries`, `mapLimit`
+* [`filter`](#filter), `filterSeries`, `filterLimit`
+* [`reject`](#reject), `rejectSeries`, `rejectLimit`
+* [`reduce`](#reduce), [`reduceRight`](#reduceRight)
+* [`detect`](#detect), `detectSeries`, `detectLimit`
+* [`sortBy`](#sortBy)
+* [`some`](#some), `someLimit`
+* [`every`](#every), `everyLimit`
+* [`concat`](#concat), `concatSeries`
+
+### Control Flow
+
+* [`series`](#seriestasks-callback)
+* [`parallel`](#parallel), `parallelLimit`
+* [`whilst`](#whilst), [`doWhilst`](#doWhilst)
+* [`until`](#until), [`doUntil`](#doUntil)
+* [`during`](#during), [`doDuring`](#doDuring)
+* [`forever`](#forever)
+* [`waterfall`](#waterfall)
+* [`compose`](#compose)
+* [`seq`](#seq)
+* [`applyEach`](#applyEach), `applyEachSeries`
+* [`queue`](#queue), [`priorityQueue`](#priorityQueue)
+* [`cargo`](#cargo)
+* [`auto`](#auto)
+* [`retry`](#retry)
+* [`iterator`](#iterator)
+* [`times`](#times), `timesSeries`, `timesLimit`
+
+### Utils
+
+* [`apply`](#apply)
+* [`nextTick`](#nextTick)
+* [`memoize`](#memoize)
+* [`unmemoize`](#unmemoize)
+* [`ensureAsync`](#ensureAsync)
+* [`constant`](#constant)
+* [`asyncify`](#asyncify)
+* [`wrapSync`](#wrapSync)
+* [`log`](#log)
+* [`dir`](#dir)
+* [`noConflict`](#noConflict)
+
+## Collections
+
+
+
+### each(arr, iterator, [callback])
+
+Applies the function `iterator` to each item in `arr`, in parallel.
+The `iterator` is called with an item from the list, and a callback for when it
+has finished. If the `iterator` passes an error to its `callback`, the main
+`callback` (for the `each` function) is immediately called with the error.
+
+Note, that since this function applies `iterator` to each item in parallel,
+there is no guarantee that the iterator functions will complete in order.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err)` which must be called once it has
+ completed. If no error has occurred, the `callback` should be run without
+ arguments or with an explicit `null` argument. The array index is not passed
+ to the iterator. If you need the index, use [`forEachOf`](#forEachOf).
+* `callback(err)` - *Optional* A callback which is called when all `iterator` functions
+ have finished, or an error occurs.
+
+__Examples__
+
+
+```js
+// assuming openFiles is an array of file names and saveFile is a function
+// to save the modified contents of that file:
+
+async.each(openFiles, saveFile, function(err){
+ // if any of the saves produced an error, err would equal that error
+});
+```
+
+```js
+// assuming openFiles is an array of file names
+
+async.each(openFiles, function(file, callback) {
+
+ // Perform operation on file here.
+ console.log('Processing file ' + file);
+
+ if( file.length > 32 ) {
+ console.log('This file name is too long');
+ callback('File name too long');
+ } else {
+ // Do work to process file here
+ console.log('File processed');
+ callback();
+ }
+}, function(err){
+ // if any of the file processing produced an error, err would equal that error
+ if( err ) {
+ // One of the iterations produced an error.
+ // All processing will now stop.
+ console.log('A file failed to process');
+ } else {
+ console.log('All files have been processed successfully');
+ }
+});
+```
+
+__Related__
+
+* eachSeries(arr, iterator, [callback])
+* eachLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+
+
+
+### forEachOf(obj, iterator, [callback])
+
+Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator.
+
+__Arguments__
+
+* `obj` - An object or array to iterate over.
+* `iterator(item, key, callback)` - A function to apply to each item in `obj`.
+The `key` is the item's key, or index in the case of an array. The iterator is
+passed a `callback(err)` which must be called once it has completed. If no
+error has occurred, the callback should be run without arguments or with an
+explicit `null` argument.
+* `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs.
+
+__Example__
+
+```js
+var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
+var configs = {};
+
+async.forEachOf(obj, function (value, key, callback) {
+ fs.readFile(__dirname + value, "utf8", function (err, data) {
+ if (err) return callback(err);
+ try {
+ configs[key] = JSON.parse(data);
+ } catch (e) {
+ return callback(e);
+ }
+ callback();
+ })
+}, function (err) {
+ if (err) console.error(err.message);
+ // configs is now a map of JSON data
+ doSomethingWith(configs);
+})
+```
+
+__Related__
+
+* forEachOfSeries(obj, iterator, [callback])
+* forEachOfLimit(obj, limit, iterator, [callback])
+
+---------------------------------------
+
+
+### map(arr, iterator, [callback])
+
+Produces a new array of values by mapping each value in `arr` through
+the `iterator` function. The `iterator` is called with an item from `arr` and a
+callback for when it has finished processing. Each of these callback takes 2 arguments:
+an `error`, and the transformed item from `arr`. If `iterator` passes an error to its
+callback, the main `callback` (for the `map` function) is immediately called with the error.
+
+Note, that since this function applies the `iterator` to each item in parallel,
+there is no guarantee that the `iterator` functions will complete in order.
+However, the results array will be in the same order as the original `arr`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, transformed)` which must be called once
+ it has completed with an error (which can be `null`) and a transformed item.
+* `callback(err, results)` - *Optional* A callback which is called when all `iterator`
+ functions have finished, or an error occurs. Results is an array of the
+ transformed items from the `arr`.
+
+__Example__
+
+```js
+async.map(['file1','file2','file3'], fs.stat, function(err, results){
+ // results is now an array of stats for each file
+});
+```
+
+__Related__
+* mapSeries(arr, iterator, [callback])
+* mapLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+
+
+### filter(arr, iterator, [callback])
+
+__Alias:__ `select`
+
+Returns a new array of all the values in `arr` which pass an async truth test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. This operation is
+performed in parallel, but the results array will be in the same order as the
+original.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The `iterator` is passed a `callback(truthValue)`, which must be called with a
+ boolean argument once it has completed.
+* `callback(results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished.
+
+__Example__
+
+```js
+async.filter(['file1','file2','file3'], fs.exists, function(results){
+ // results now equals an array of the existing files
+});
+```
+
+__Related__
+
+* filterSeries(arr, iterator, [callback])
+* filterLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+
+### reject(arr, iterator, [callback])
+
+The opposite of [`filter`](#filter). Removes values that pass an `async` truth test.
+
+__Related__
+
+* rejectSeries(arr, iterator, [callback])
+* rejectLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+
+### reduce(arr, memo, iterator, [callback])
+
+__Aliases:__ `inject`, `foldl`
+
+Reduces `arr` into a single value using an async `iterator` to return
+each successive step. `memo` is the initial state of the reduction.
+This function only operates in series.
+
+For performance reasons, it may make sense to split a call to this function into
+a parallel map, and then use the normal `Array.prototype.reduce` on the results.
+This function is for situations where each step in the reduction needs to be async;
+if you can get the data before reducing it, then it's probably a good idea to do so.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `memo` - The initial state of the reduction.
+* `iterator(memo, item, callback)` - A function applied to each item in the
+ array to produce the next step in the reduction. The `iterator` is passed a
+ `callback(err, reduction)` which accepts an optional error as its first
+ argument, and the state of the reduction as the second. If an error is
+ passed to the callback, the reduction is stopped and the main `callback` is
+ immediately called with the error.
+* `callback(err, result)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished. Result is the reduced value.
+
+__Example__
+
+```js
+async.reduce([1,2,3], 0, function(memo, item, callback){
+ // pointless async:
+ process.nextTick(function(){
+ callback(null, memo + item)
+ });
+}, function(err, result){
+ // result is now equal to the last value of memo, which is 6
+});
+```
+
+---------------------------------------
+
+
+### reduceRight(arr, memo, iterator, [callback])
+
+__Alias:__ `foldr`
+
+Same as [`reduce`](#reduce), only operates on `arr` in reverse order.
+
+
+---------------------------------------
+
+
+### detect(arr, iterator, [callback])
+
+Returns the first value in `arr` that passes an async truth test. The
+`iterator` is applied in parallel, meaning the first iterator to return `true` will
+fire the detect `callback` with that result. That means the result might not be
+the first item in the original `arr` (in terms of order) that passes the test.
+
+If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries).
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in `arr`.
+ The iterator is passed a `callback(truthValue)` which must be called with a
+ boolean argument once it has completed. **Note: this callback does not take an error as its first argument.**
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `true`, or after all the `iterator` functions have finished. Result will be
+ the first item in the array that passes the truth test (iterator) or the
+ value `undefined` if none passed. **Note: this callback does not take an error as its first argument.**
+
+__Example__
+
+```js
+async.detect(['file1','file2','file3'], fs.exists, function(result){
+ // result now equals the first file in the list that exists
+});
+```
+
+__Related__
+
+* detectSeries(arr, iterator, [callback])
+* detectLimit(arr, limit, iterator, [callback])
+
+---------------------------------------
+
+
+### sortBy(arr, iterator, [callback])
+
+Sorts a list by the results of running each `arr` value through an async `iterator`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, sortValue)` which must be called once it
+ has completed with an error (which can be `null`) and a value to use as the sort
+ criteria.
+* `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is the items from
+ the original `arr` sorted by the values returned by the `iterator` calls.
+
+__Example__
+
+```js
+async.sortBy(['file1','file2','file3'], function(file, callback){
+ fs.stat(file, function(err, stats){
+ callback(err, stats.mtime);
+ });
+}, function(err, results){
+ // results is now the original array of files sorted by
+ // modified date
+});
+```
+
+__Sort Order__
+
+By modifying the callback parameter the sorting order can be influenced:
+
+```js
+//ascending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(null, x);
+}, function(err,result){
+ //result callback
+} );
+
+//descending order
+async.sortBy([1,9,3,5], function(x, callback){
+ callback(null, x*-1); //<- x*-1 instead of x, turns the order around
+}, function(err,result){
+ //result callback
+} );
+```
+
+---------------------------------------
+
+
+### some(arr, iterator, [callback])
+
+__Alias:__ `any`
+
+Returns `true` if at least one element in the `arr` satisfies an async test.
+_The callback for each iterator call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`. Once any iterator
+call returns `true`, the main `callback` is immediately called.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a `callback(truthValue)`` which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `true`, or after all the iterator functions have finished. Result will be
+ either `true` or `false` depending on the values of the async tests.
+
+ **Note: the callbacks do not take an error as their first argument.**
+__Example__
+
+```js
+async.some(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then at least one of the files exists
+});
+```
+
+__Related__
+
+* someLimit(arr, limit, iterator, callback)
+
+---------------------------------------
+
+
+### every(arr, iterator, [callback])
+
+__Alias:__ `all`
+
+Returns `true` if every element in `arr` satisfies an async test.
+_The callback for each `iterator` call only accepts a single argument of `true` or
+`false`; it does not accept an error argument first!_ This is in-line with the
+way node libraries work with truth tests like `fs.exists`.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A truth test to apply to each item in the array
+ in parallel. The iterator is passed a `callback(truthValue)` which must be
+ called with a boolean argument once it has completed.
+* `callback(result)` - *Optional* A callback which is called as soon as any iterator returns
+ `false`, or after all the iterator functions have finished. Result will be
+ either `true` or `false` depending on the values of the async tests.
+
+ **Note: the callbacks do not take an error as their first argument.**
+
+__Example__
+
+```js
+async.every(['file1','file2','file3'], fs.exists, function(result){
+ // if result is true then every file exists
+});
+```
+
+__Related__
+
+* everyLimit(arr, limit, iterator, callback)
+
+---------------------------------------
+
+
+### concat(arr, iterator, [callback])
+
+Applies `iterator` to each item in `arr`, concatenating the results. Returns the
+concatenated list. The `iterator`s are called in parallel, and the results are
+concatenated as they return. There is no guarantee that the results array will
+be returned in the original order of `arr` passed to the `iterator` function.
+
+__Arguments__
+
+* `arr` - An array to iterate over.
+* `iterator(item, callback)` - A function to apply to each item in `arr`.
+ The iterator is passed a `callback(err, results)` which must be called once it
+ has completed with an error (which can be `null`) and an array of results.
+* `callback(err, results)` - *Optional* A callback which is called after all the `iterator`
+ functions have finished, or an error occurs. Results is an array containing
+ the concatenated results of the `iterator` function.
+
+__Example__
+
+```js
+async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){
+ // files is now a list of filenames that exist in the 3 directories
+});
+```
+
+__Related__
+
+* concatSeries(arr, iterator, [callback])
+
+
+## Control Flow
+
+
+### series(tasks, [callback])
+
+Run the functions in the `tasks` array in series, each one running once the previous
+function has completed. If any functions in the series pass an error to its
+callback, no more functions are run, and `callback` is immediately called with the value of the error.
+Otherwise, `callback` receives an array of results when `tasks` have completed.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function, and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`series`](#series).
+
+**Note** that while many implementations preserve the order of object properties, the
+[ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
+explicitly states that
+
+> The mechanics and order of enumerating the properties is not specified.
+
+So if you rely on the order in which your series of functions are executed, and want
+this to work on all platforms, consider using an array.
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run, each function is passed
+ a `callback(err, result)` it must call on completion with an error `err` (which can
+ be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed. This function gets a results array (or object) containing all
+ the result arguments passed to the `task` callbacks.
+
+__Example__
+
+```js
+async.series([
+ function(callback){
+ // do some stuff ...
+ callback(null, 'one');
+ },
+ function(callback){
+ // do some more stuff ...
+ callback(null, 'two');
+ }
+],
+// optional callback
+function(err, results){
+ // results is now equal to ['one', 'two']
+});
+
+
+// an example using an object instead of an array
+async.series({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equal to: {one: 1, two: 2}
+});
+```
+
+---------------------------------------
+
+
+### parallel(tasks, [callback])
+
+Run the `tasks` array of functions in parallel, without waiting until the previous
+function has completed. If any of the functions pass an error to its
+callback, the main `callback` is immediately called with the value of the error.
+Once the `tasks` have completed, the results are passed to the final `callback` as an
+array.
+
+**Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.
+
+It is also possible to use an object instead of an array. Each property will be
+run as a function and the results will be passed to the final `callback` as an object
+instead of an array. This can be a more readable way of handling results from
+[`parallel`](#parallel).
+
+
+__Arguments__
+
+* `tasks` - An array or object containing functions to run. Each function is passed
+ a `callback(err, result)` which it must call on completion with an error `err`
+ (which can be `null`) and an optional `result` value.
+* `callback(err, results)` - An optional callback to run once all the functions
+ have completed successfully. This function gets a results array (or object) containing all
+ the result arguments passed to the task callbacks.
+
+__Example__
+
+```js
+async.parallel([
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'one');
+ }, 200);
+ },
+ function(callback){
+ setTimeout(function(){
+ callback(null, 'two');
+ }, 100);
+ }
+],
+// optional callback
+function(err, results){
+ // the results array will equal ['one','two'] even though
+ // the second function had a shorter timeout.
+});
+
+
+// an example using an object instead of an array
+async.parallel({
+ one: function(callback){
+ setTimeout(function(){
+ callback(null, 1);
+ }, 200);
+ },
+ two: function(callback){
+ setTimeout(function(){
+ callback(null, 2);
+ }, 100);
+ }
+},
+function(err, results) {
+ // results is now equals to: {one: 1, two: 2}
+});
+```
+
+__Related__
+
+* parallelLimit(tasks, limit, [callback])
+
+---------------------------------------
+
+
+### whilst(test, fn, callback)
+
+Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped,
+or an error occurs.
+
+__Arguments__
+
+* `test()` - synchronous truth test to perform before each execution of `fn`.
+* `fn(callback)` - A function which is called each time `test` passes. The function is
+ passed a `callback(err)`, which must be called once it has completed with an
+ optional `err` argument.
+* `callback(err, [results])` - A callback which is called after the test
+ function has failed and repeated execution of `fn` has stopped. `callback`
+ will be passed an error and any arguments passed to the final `fn`'s callback.
+
+__Example__
+
+```js
+var count = 0;
+
+async.whilst(
+ function () { return count < 5; },
+ function (callback) {
+ count++;
+ setTimeout(function () {
+ callback(null, count);
+ }, 1000);
+ },
+ function (err, n) {
+ // 5 seconds have passed, n = 5
+ }
+);
+```
+
+---------------------------------------
+
+
+### doWhilst(fn, test, callback)
+
+The post-check version of [`whilst`](#whilst). To reflect the difference in
+the order of operations, the arguments `test` and `fn` are switched.
+
+`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
+
+---------------------------------------
+
+
+### until(test, fn, callback)
+
+Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped,
+or an error occurs. `callback` will be passed an error and any arguments passed
+to the final `fn`'s callback.
+
+The inverse of [`whilst`](#whilst).
+
+---------------------------------------
+
+
+### doUntil(fn, test, callback)
+
+Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`.
+
+---------------------------------------
+
+
+### during(test, fn, callback)
+
+Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error.
+
+__Example__
+
+```js
+var count = 0;
+
+async.during(
+ function (callback) {
+ return callback(null, count < 5);
+ },
+ function (callback) {
+ count++;
+ setTimeout(callback, 1000);
+ },
+ function (err) {
+ // 5 seconds have passed
+ }
+);
+```
+
+---------------------------------------
+
+
+### doDuring(fn, test, callback)
+
+The post-check version of [`during`](#during). To reflect the difference in
+the order of operations, the arguments `test` and `fn` are switched.
+
+Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function.
+
+---------------------------------------
+
+
+### forever(fn, [errback])
+
+Calls the asynchronous function `fn` with a callback parameter that allows it to
+call itself again, in series, indefinitely.
+
+If an error is passed to the callback then `errback` is called with the
+error, and execution stops, otherwise it will never be called.
+
+```js
+async.forever(
+ function(next) {
+ // next is suitable for passing to things that need a callback(err [, whatever]);
+ // it will result in this function being called again.
+ },
+ function(err) {
+ // if next is called with a value in its first parameter, it will appear
+ // in here as 'err', and execution will stop.
+ }
+);
+```
+
+---------------------------------------
+
+
+### waterfall(tasks, [callback])
+
+Runs the `tasks` array of functions in series, each passing their results to the next in
+the array. However, if any of the `tasks` pass an error to their own callback, the
+next function is not executed, and the main `callback` is immediately called with
+the error.
+
+__Arguments__
+
+* `tasks` - An array of functions to run, each function is passed a
+ `callback(err, result1, result2, ...)` it must call on completion. The first
+ argument is an error (which can be `null`) and any further arguments will be
+ passed as arguments in order to the next task.
+* `callback(err, [results])` - An optional callback to run once all the functions
+ have completed. This will be passed the results of the last task's callback.
+
+
+
+__Example__
+
+```js
+async.waterfall([
+ function(callback) {
+ callback(null, 'one', 'two');
+ },
+ function(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+ },
+ function(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+ }
+], function (err, result) {
+ // result now equals 'done'
+});
+```
+Or, with named functions:
+
+```js
+async.waterfall([
+ myFirstFunction,
+ mySecondFunction,
+ myLastFunction,
+], function (err, result) {
+ // result now equals 'done'
+});
+function myFirstFunction(callback) {
+ callback(null, 'one', 'two');
+}
+function mySecondFunction(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+}
+function myLastFunction(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+}
+```
+
+Or, if you need to pass any argument to the first function:
+
+```js
+async.waterfall([
+ async.apply(myFirstFunction, 'zero'),
+ mySecondFunction,
+ myLastFunction,
+], function (err, result) {
+ // result now equals 'done'
+});
+function myFirstFunction(arg1, callback) {
+ // arg1 now equals 'zero'
+ callback(null, 'one', 'two');
+}
+function mySecondFunction(arg1, arg2, callback) {
+ // arg1 now equals 'one' and arg2 now equals 'two'
+ callback(null, 'three');
+}
+function myLastFunction(arg1, callback) {
+ // arg1 now equals 'three'
+ callback(null, 'done');
+}
+```
+
+---------------------------------------
+
+### compose(fn1, fn2...)
+
+Creates a function which is a composition of the passed asynchronous
+functions. Each function consumes the return value of the function that
+follows. Composing functions `f()`, `g()`, and `h()` would produce the result of
+`f(g(h()))`, only this version uses callbacks to obtain the return values.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* `functions...` - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+function add1(n, callback) {
+ setTimeout(function () {
+ callback(null, n + 1);
+ }, 10);
+}
+
+function mul3(n, callback) {
+ setTimeout(function () {
+ callback(null, n * 3);
+ }, 10);
+}
+
+var add1mul3 = async.compose(mul3, add1);
+
+add1mul3(4, function (err, result) {
+ // result now equals 15
+});
+```
+
+---------------------------------------
+
+### seq(fn1, fn2...)
+
+Version of the compose function that is more natural to read.
+Each function consumes the return value of the previous function.
+It is the equivalent of [`compose`](#compose) with the arguments reversed.
+
+Each function is executed with the `this` binding of the composed function.
+
+__Arguments__
+
+* `functions...` - the asynchronous functions to compose
+
+
+__Example__
+
+```js
+// Requires lodash (or underscore), express3 and dresende's orm2.
+// Part of an app, that fetches cats of the logged user.
+// This example uses `seq` function to avoid overnesting and error
+// handling clutter.
+app.get('/cats', function(request, response) {
+ var User = request.models.User;
+ async.seq(
+ _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
+ function(user, fn) {
+ user.getCats(fn); // 'getCats' has signature (callback(err, data))
+ }
+ )(req.session.user_id, function (err, cats) {
+ if (err) {
+ console.error(err);
+ response.json({ status: 'error', message: err.message });
+ } else {
+ response.json({ status: 'ok', message: 'Cats found', data: cats });
+ }
+ });
+});
+```
+
+---------------------------------------
+
+### applyEach(fns, args..., callback)
+
+Applies the provided arguments to each function in the array, calling
+`callback` after all functions have completed. If you only provide the first
+argument, then it will return a function which lets you pass in the
+arguments as if it were a single function call.
+
+__Arguments__
+
+* `fns` - the asynchronous functions to all call with the same arguments
+* `args...` - any number of separate arguments to pass to the function
+* `callback` - the final argument should be the callback, called when all
+ functions have completed processing
+
+
+__Example__
+
+```js
+async.applyEach([enableSearch, updateSchema], 'bucket', callback);
+
+// partial application example:
+async.each(
+ buckets,
+ async.applyEach([enableSearch, updateSchema]),
+ callback
+);
+```
+
+__Related__
+
+* applyEachSeries(tasks, args..., [callback])
+
+---------------------------------------
+
+
+### queue(worker, [concurrency])
+
+Creates a `queue` object with the specified `concurrency`. Tasks added to the
+`queue` are processed in parallel (up to the `concurrency` limit). If all
+`worker`s are in progress, the task is queued until one becomes available.
+Once a `worker` completes a `task`, that `task`'s callback is called.
+
+__Arguments__
+
+* `worker(task, callback)` - An asynchronous function for processing a queued
+ task, which must call its `callback(err)` argument when finished, with an
+ optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`.
+* `concurrency` - An `integer` for determining how many `worker` functions should be
+ run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown.
+
+__Queue objects__
+
+The `queue` object returned by this function has the following properties and
+methods:
+
+* `length()` - a function returning the number of items waiting to be processed.
+* `started` - a function returning whether or not any items have been pushed and processed by the queue
+* `running()` - a function returning the number of items currently being processed.
+* `workersList()` - a function returning the array of items currently being processed.
+* `idle()` - a function returning false if there are items waiting or being processed, or true if not.
+* `concurrency` - an integer for determining how many `worker` functions should be
+ run in parallel. This property can be changed after a `queue` is created to
+ alter the concurrency on-the-fly.
+* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once
+ the `worker` has finished processing the task. Instead of a single task, a `tasks` array
+ can be submitted. The respective callback is used for every task in the list.
+* `unshift(task, [callback])` - add a new task to the front of the `queue`.
+* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit,
+ and further tasks will be queued.
+* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`.
+* `paused` - a boolean for determining whether the queue is in a paused state
+* `pause()` - a function that pauses the processing of tasks until `resume()` is called.
+* `resume()` - a function that resumes the processing of queued tasks when the queue is paused.
+* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle.
+
+__Example__
+
+```js
+// create a queue object with concurrency 2
+
+var q = async.queue(function (task, callback) {
+ console.log('hello ' + task.name);
+ callback();
+}, 2);
+
+
+// assign a callback
+q.drain = function() {
+ console.log('all items have been processed');
+}
+
+// add some items to the queue
+
+q.push({name: 'foo'}, function (err) {
+ console.log('finished processing foo');
+});
+q.push({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+
+// add some items to the queue (batch-wise)
+
+q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {
+ console.log('finished processing item');
+});
+
+// add some items to the front of the queue
+
+q.unshift({name: 'bar'}, function (err) {
+ console.log('finished processing bar');
+});
+```
+
+
+---------------------------------------
+
+
+### priorityQueue(worker, concurrency)
+
+The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects:
+
+* `push(task, priority, [callback])` - `priority` should be a number. If an array of
+ `tasks` is given, all tasks will be assigned the same priority.
+* The `unshift` method was removed.
+
+---------------------------------------
+
+
+### cargo(worker, [payload])
+
+Creates a `cargo` object with the specified payload. Tasks added to the
+cargo will be processed altogether (up to the `payload` limit). If the
+`worker` is in progress, the task is queued until it becomes available. Once
+the `worker` has completed some tasks, each callback of those tasks is called.
+Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work.
+
+While [queue](#queue) passes only one task to one of a group of workers
+at a time, cargo passes an array of tasks to a single worker, repeating
+when the worker is finished.
+
+__Arguments__
+
+* `worker(tasks, callback)` - An asynchronous function for processing an array of
+ queued tasks, which must call its `callback(err)` argument when finished, with
+ an optional `err` argument.
+* `payload` - An optional `integer` for determining how many tasks should be
+ processed per round; if omitted, the default is unlimited.
+
+__Cargo objects__
+
+The `cargo` object returned by this function has the following properties and
+methods:
+
+* `length()` - A function returning the number of items waiting to be processed.
+* `payload` - An `integer` for determining how many tasks should be
+ process per round. This property can be changed after a `cargo` is created to
+ alter the payload on-the-fly.
+* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called
+ once the `worker` has finished processing the task. Instead of a single task, an array of `tasks`
+ can be submitted. The respective callback is used for every task in the list.
+* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued.
+* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`.
+* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`.
+* `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue)
+
+__Example__
+
+```js
+// create a cargo object with payload 2
+
+var cargo = async.cargo(function (tasks, callback) {
+ for(var i=0; i
+### auto(tasks, [concurrency], [callback])
+
+Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied.
+
+If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far.
+
+Note, all functions are called with a `results` object as a second argument,
+so it is unsafe to pass functions in the `tasks` object which cannot handle the
+extra argument.
+
+For example, this snippet of code:
+
+```js
+async.auto({
+ readData: async.apply(fs.readFile, 'data.txt', 'utf-8')
+}, callback);
+```
+
+will have the effect of calling `readFile` with the results object as the last
+argument, which will fail:
+
+```js
+fs.readFile('data.txt', 'utf-8', cb, {});
+```
+
+Instead, wrap the call to `readFile` in a function which does not forward the
+`results` object:
+
+```js
+async.auto({
+ readData: function(cb, results){
+ fs.readFile('data.txt', 'utf-8', cb);
+ }
+}, callback);
+```
+
+__Arguments__
+
+* `tasks` - An object. Each of its properties is either a function or an array of
+ requirements, with the function itself the last item in the array. The object's key
+ of a property serves as the name of the task defined by that property,
+ i.e. can be used when specifying requirements for other tasks.
+ The function receives two arguments: (1) a `callback(err, result)` which must be
+ called when finished, passing an `error` (which can be `null`) and the result of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions.
+* `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible.
+* `callback(err, results)` - An optional callback which is called when all the
+ tasks have been completed. It receives the `err` argument if any `tasks`
+ pass an error to their callback. Results are always returned; however, if
+ an error occurs, no further `tasks` will be performed, and the results
+ object will only contain partial results.
+
+
+__Example__
+
+```js
+async.auto({
+ get_data: function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ make_folder: function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ },
+ write_file: ['get_data', 'make_folder', function(callback, results){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ callback(null, 'filename');
+ }],
+ email_link: ['write_file', function(callback, results){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ // results.write_file contains the filename returned by write_file.
+ callback(null, {'file':results.write_file, 'email':'user@example.com'});
+ }]
+}, function(err, results) {
+ console.log('err = ', err);
+ console.log('results = ', results);
+});
+```
+
+This is a fairly trivial example, but to do this using the basic parallel and
+series functions would look like this:
+
+```js
+async.parallel([
+ function(callback){
+ console.log('in get_data');
+ // async code to get some data
+ callback(null, 'data', 'converted to array');
+ },
+ function(callback){
+ console.log('in make_folder');
+ // async code to create a directory to store a file in
+ // this is run at the same time as getting the data
+ callback(null, 'folder');
+ }
+],
+function(err, results){
+ async.series([
+ function(callback){
+ console.log('in write_file', JSON.stringify(results));
+ // once there is some data and the directory exists,
+ // write the data to a file in the directory
+ results.push('filename');
+ callback(null);
+ },
+ function(callback){
+ console.log('in email_link', JSON.stringify(results));
+ // once the file is written let's email a link to it...
+ callback(null, {'file':results.pop(), 'email':'user@example.com'});
+ }
+ ]);
+});
+```
+
+For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding
+new tasks much easier (and the code more readable).
+
+
+---------------------------------------
+
+
+### retry([opts = {times: 5, interval: 0}| 5], task, [callback])
+
+Attempts to get a successful response from `task` no more than `times` times before
+returning an error. If the task is successful, the `callback` will be passed the result
+of the successful task. If all attempts fail, the callback will be passed the error and
+result (if any) of the final attempt.
+
+__Arguments__
+
+* `opts` - Can be either an object with `times` and `interval` or a number.
+ * `times` - The number of attempts to make before giving up. The default is `5`.
+ * `interval` - The time to wait between retries, in milliseconds. The default is `0`.
+ * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`.
+* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)`
+ which must be called when finished, passing `err` (which can be `null`) and the `result` of
+ the function's execution, and (2) a `results` object, containing the results of
+ the previously executed functions (if nested inside another control flow).
+* `callback(err, results)` - An optional callback which is called when the
+ task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`.
+
+The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below:
+
+```js
+// try calling apiMethod 3 times
+async.retry(3, apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+```js
+// try calling apiMethod 3 times, waiting 200 ms between each retry
+async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+```js
+// try calling apiMethod the default 5 times no delay between each retry
+async.retry(apiMethod, function(err, result) {
+ // do something with the result
+});
+```
+
+It can also be embedded within other control flow functions to retry individual methods
+that are not as reliable, like this:
+
+```js
+async.auto({
+ users: api.getUsers.bind(api),
+ payments: async.retry(3, api.getPayments.bind(api))
+}, function(err, results) {
+ // do something with the results
+});
+```
+
+
+---------------------------------------
+
+
+### iterator(tasks)
+
+Creates an iterator function which calls the next function in the `tasks` array,
+returning a continuation to call the next one after that. It's also possible to
+“peek” at the next iterator with `iterator.next()`.
+
+This function is used internally by the `async` module, but can be useful when
+you want to manually control the flow of functions in series.
+
+__Arguments__
+
+* `tasks` - An array of functions to run.
+
+__Example__
+
+```js
+var iterator = async.iterator([
+ function(){ sys.p('one'); },
+ function(){ sys.p('two'); },
+ function(){ sys.p('three'); }
+]);
+
+node> var iterator2 = iterator();
+'one'
+node> var iterator3 = iterator2();
+'two'
+node> iterator3();
+'three'
+node> var nextfn = iterator2.next();
+node> nextfn();
+'three'
+```
+
+---------------------------------------
+
+
+### apply(function, arguments..)
+
+Creates a continuation function with some arguments already applied.
+
+Useful as a shorthand when combined with other control flow functions. Any arguments
+passed to the returned function are added to the arguments originally passed
+to apply.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to automatically apply when the
+ continuation is called.
+
+__Example__
+
+```js
+// using apply
+
+async.parallel([
+ async.apply(fs.writeFile, 'testfile1', 'test1'),
+ async.apply(fs.writeFile, 'testfile2', 'test2'),
+]);
+
+
+// the same process without using apply
+
+async.parallel([
+ function(callback){
+ fs.writeFile('testfile1', 'test1', callback);
+ },
+ function(callback){
+ fs.writeFile('testfile2', 'test2', callback);
+ }
+]);
+```
+
+It's possible to pass any number of additional arguments when calling the
+continuation:
+
+```js
+node> var fn = async.apply(sys.puts, 'one');
+node> fn('two', 'three');
+one
+two
+three
+```
+
+---------------------------------------
+
+
+### nextTick(callback), setImmediate(callback)
+
+Calls `callback` on a later loop around the event loop. In Node.js this just
+calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)`
+if available, otherwise `setTimeout(callback, 0)`, which means other higher priority
+events may precede the execution of `callback`.
+
+This is used internally for browser-compatibility purposes.
+
+__Arguments__
+
+* `callback` - The function to call on a later loop around the event loop.
+
+__Example__
+
+```js
+var call_order = [];
+async.nextTick(function(){
+ call_order.push('two');
+ // call_order now equals ['one','two']
+});
+call_order.push('one')
+```
+
+
+### times(n, iterator, [callback])
+
+Calls the `iterator` function `n` times, and accumulates results in the same manner
+you would use with [`map`](#map).
+
+__Arguments__
+
+* `n` - The number of times to run the function.
+* `iterator` - The function to call `n` times.
+* `callback` - see [`map`](#map)
+
+__Example__
+
+```js
+// Pretend this is some complicated async factory
+var createUser = function(id, callback) {
+ callback(null, {
+ id: 'user' + id
+ })
+}
+// generate 5 users
+async.times(5, function(n, next){
+ createUser(n, function(err, user) {
+ next(err, user)
+ })
+}, function(err, users) {
+ // we should now have 5 users
+});
+```
+
+__Related__
+
+* timesSeries(n, iterator, [callback])
+* timesLimit(n, limit, iterator, [callback])
+
+
+## Utils
+
+
+### memoize(fn, [hasher])
+
+Caches the results of an `async` function. When creating a hash to store function
+results against, the callback is omitted from the hash and an optional hash
+function can be used.
+
+If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function.
+
+The cache of results is exposed as the `memo` property of the function returned
+by `memoize`.
+
+__Arguments__
+
+* `fn` - The function to proxy and cache results from.
+* `hasher` - An optional function for generating a custom hash for storing
+ results. It has all the arguments applied to it apart from the callback, and
+ must be synchronous.
+
+__Example__
+
+```js
+var slow_fn = function (name, callback) {
+ // do something
+ callback(null, result);
+};
+var fn = async.memoize(slow_fn);
+
+// fn can now be used as if it were slow_fn
+fn('some name', function () {
+ // callback
+});
+```
+
+
+### unmemoize(fn)
+
+Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized
+form. Handy for testing.
+
+__Arguments__
+
+* `fn` - the memoized function
+
+---------------------------------------
+
+
+### ensureAsync(fn)
+
+Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained.
+
+__Arguments__
+
+* `fn` - an async function, one that expects a node-style callback as its last argument
+
+Returns a wrapped function with the exact same call signature as the function passed in.
+
+__Example__
+
+```js
+function sometimesAsync(arg, callback) {
+ if (cache[arg]) {
+ return callback(null, cache[arg]); // this would be synchronous!!
+ } else {
+ doSomeIO(arg, callback); // this IO would be asynchronous
+ }
+}
+
+// this has a risk of stack overflows if many results are cached in a row
+async.mapSeries(args, sometimesAsync, done);
+
+// this will defer sometimesAsync's callback if necessary,
+// preventing stack overflows
+async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
+
+```
+
+---------------------------------------
+
+
+### constant(values...)
+
+Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`.
+
+__Example__
+
+```js
+async.waterfall([
+ async.constant(42),
+ function (value, next) {
+ // value === 42
+ },
+ //...
+], callback);
+
+async.waterfall([
+ async.constant(filename, "utf8"),
+ fs.readFile,
+ function (fileData, next) {
+ //...
+ }
+ //...
+], callback);
+
+async.auto({
+ hostname: async.constant("https://server.net/"),
+ port: findFreePort,
+ launchServer: ["hostname", "port", function (cb, options) {
+ startServer(options, cb);
+ }],
+ //...
+}, callback);
+
+```
+
+---------------------------------------
+
+
+
+### asyncify(func)
+
+__Alias:__ `wrapSync`
+
+Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback.
+
+__Example__
+
+```js
+async.waterfall([
+ async.apply(fs.readFile, filename, "utf8"),
+ async.asyncify(JSON.parse),
+ function (data, next) {
+ // data is the result of parsing the text.
+ // If there was a parsing error, it would have been caught.
+ }
+], callback)
+```
+
+If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example:
+
+```js
+async.waterfall([
+ async.apply(fs.readFile, filename, "utf8"),
+ async.asyncify(function (contents) {
+ return db.model.create(contents);
+ }),
+ function (model, next) {
+ // `model` is the instantiated model object.
+ // If there was an error, this function would be skipped.
+ }
+], callback)
+```
+
+This also means you can asyncify ES2016 `async` functions.
+
+```js
+var q = async.queue(async.asyncify(async function (file) {
+ var intermediateStep = await processFile(file);
+ return await somePromise(intermediateStep)
+}));
+
+q.push(files);
+```
+
+---------------------------------------
+
+
+### log(function, arguments)
+
+Logs the result of an `async` function to the `console`. Only works in Node.js or
+in browsers that support `console.log` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.log` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, 'hello ' + name);
+ }, 1000);
+};
+```
+```js
+node> async.log(hello, 'world');
+'hello world'
+```
+
+---------------------------------------
+
+
+### dir(function, arguments)
+
+Logs the result of an `async` function to the `console` using `console.dir` to
+display the properties of the resulting object. Only works in Node.js or
+in browsers that support `console.dir` and `console.error` (such as FF and Chrome).
+If multiple arguments are returned from the async function, `console.dir` is
+called on each argument in order.
+
+__Arguments__
+
+* `function` - The function you want to eventually apply all arguments to.
+* `arguments...` - Any number of arguments to apply to the function.
+
+__Example__
+
+```js
+var hello = function(name, callback){
+ setTimeout(function(){
+ callback(null, {hello: name});
+ }, 1000);
+};
+```
+```js
+node> async.dir(hello, 'world');
+{hello: 'world'}
+```
+
+---------------------------------------
+
+
+### noConflict()
+
+Changes the value of `async` back to its original value, returning a reference to the
+`async` object.
diff --git a/node_modules/async/dist/async.js b/node_modules/async/dist/async.js
new file mode 100644
index 0000000..31e7620
--- /dev/null
+++ b/node_modules/async/dist/async.js
@@ -0,0 +1,1265 @@
+/*!
+ * async
+ * https://github.com/caolan/async
+ *
+ * Copyright 2010-2014 Caolan McMahon
+ * Released under the MIT license
+ */
+(function () {
+
+ var async = {};
+ function noop() {}
+ function identity(v) {
+ return v;
+ }
+ function toBool(v) {
+ return !!v;
+ }
+ function notId(v) {
+ return !v;
+ }
+
+ // global on the server, window in the browser
+ var previous_async;
+
+ // Establish the root object, `window` (`self`) in the browser, `global`
+ // on the server, or `this` in some virtual machines. We use `self`
+ // instead of `window` for `WebWorker` support.
+ var root = typeof self === 'object' && self.self === self && self ||
+ typeof global === 'object' && global.global === global && global ||
+ this;
+
+ if (root != null) {
+ previous_async = root.async;
+ }
+
+ async.noConflict = function () {
+ root.async = previous_async;
+ return async;
+ };
+
+ function only_once(fn) {
+ return function() {
+ if (fn === null) throw new Error("Callback was already called.");
+ fn.apply(this, arguments);
+ fn = null;
+ };
+ }
+
+ function _once(fn) {
+ return function() {
+ if (fn === null) return;
+ fn.apply(this, arguments);
+ fn = null;
+ };
+ }
+
+ //// cross-browser compatiblity functions ////
+
+ var _toString = Object.prototype.toString;
+
+ var _isArray = Array.isArray || function (obj) {
+ return _toString.call(obj) === '[object Array]';
+ };
+
+ // Ported from underscore.js isObject
+ var _isObject = function(obj) {
+ var type = typeof obj;
+ return type === 'function' || type === 'object' && !!obj;
+ };
+
+ function _isArrayLike(arr) {
+ return _isArray(arr) || (
+ // has a positive integer length property
+ typeof arr.length === "number" &&
+ arr.length >= 0 &&
+ arr.length % 1 === 0
+ );
+ }
+
+ function _arrayEach(arr, iterator) {
+ var index = -1,
+ length = arr.length;
+
+ while (++index < length) {
+ iterator(arr[index], index, arr);
+ }
+ }
+
+ function _map(arr, iterator) {
+ var index = -1,
+ length = arr.length,
+ result = Array(length);
+
+ while (++index < length) {
+ result[index] = iterator(arr[index], index, arr);
+ }
+ return result;
+ }
+
+ function _range(count) {
+ return _map(Array(count), function (v, i) { return i; });
+ }
+
+ function _reduce(arr, iterator, memo) {
+ _arrayEach(arr, function (x, i, a) {
+ memo = iterator(memo, x, i, a);
+ });
+ return memo;
+ }
+
+ function _forEachOf(object, iterator) {
+ _arrayEach(_keys(object), function (key) {
+ iterator(object[key], key);
+ });
+ }
+
+ function _indexOf(arr, item) {
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] === item) return i;
+ }
+ return -1;
+ }
+
+ var _keys = Object.keys || function (obj) {
+ var keys = [];
+ for (var k in obj) {
+ if (obj.hasOwnProperty(k)) {
+ keys.push(k);
+ }
+ }
+ return keys;
+ };
+
+ function _keyIterator(coll) {
+ var i = -1;
+ var len;
+ var keys;
+ if (_isArrayLike(coll)) {
+ len = coll.length;
+ return function next() {
+ i++;
+ return i < len ? i : null;
+ };
+ } else {
+ keys = _keys(coll);
+ len = keys.length;
+ return function next() {
+ i++;
+ return i < len ? keys[i] : null;
+ };
+ }
+ }
+
+ // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
+ // This accumulates the arguments passed into an array, after a given index.
+ // From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
+ function _restParam(func, startIndex) {
+ startIndex = startIndex == null ? func.length - 1 : +startIndex;
+ return function() {
+ var length = Math.max(arguments.length - startIndex, 0);
+ var rest = Array(length);
+ for (var index = 0; index < length; index++) {
+ rest[index] = arguments[index + startIndex];
+ }
+ switch (startIndex) {
+ case 0: return func.call(this, rest);
+ case 1: return func.call(this, arguments[0], rest);
+ }
+ // Currently unused but handle cases outside of the switch statement:
+ // var args = Array(startIndex + 1);
+ // for (index = 0; index < startIndex; index++) {
+ // args[index] = arguments[index];
+ // }
+ // args[startIndex] = rest;
+ // return func.apply(this, args);
+ };
+ }
+
+ function _withoutIndex(iterator) {
+ return function (value, index, callback) {
+ return iterator(value, callback);
+ };
+ }
+
+ //// exported async module functions ////
+
+ //// nextTick implementation with browser-compatible fallback ////
+
+ // capture the global reference to guard against fakeTimer mocks
+ var _setImmediate = typeof setImmediate === 'function' && setImmediate;
+
+ var _delay = _setImmediate ? function(fn) {
+ // not a direct alias for IE10 compatibility
+ _setImmediate(fn);
+ } : function(fn) {
+ setTimeout(fn, 0);
+ };
+
+ if (typeof process === 'object' && typeof process.nextTick === 'function') {
+ async.nextTick = process.nextTick;
+ } else {
+ async.nextTick = _delay;
+ }
+ async.setImmediate = _setImmediate ? _delay : async.nextTick;
+
+
+ async.forEach =
+ async.each = function (arr, iterator, callback) {
+ return async.eachOf(arr, _withoutIndex(iterator), callback);
+ };
+
+ async.forEachSeries =
+ async.eachSeries = function (arr, iterator, callback) {
+ return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
+ };
+
+
+ async.forEachLimit =
+ async.eachLimit = function (arr, limit, iterator, callback) {
+ return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
+ };
+
+ async.forEachOf =
+ async.eachOf = function (object, iterator, callback) {
+ callback = _once(callback || noop);
+ object = object || [];
+
+ var iter = _keyIterator(object);
+ var key, completed = 0;
+
+ while ((key = iter()) != null) {
+ completed += 1;
+ iterator(object[key], key, only_once(done));
+ }
+
+ if (completed === 0) callback(null);
+
+ function done(err) {
+ completed--;
+ if (err) {
+ callback(err);
+ }
+ // Check key is null in case iterator isn't exhausted
+ // and done resolved synchronously.
+ else if (key === null && completed <= 0) {
+ callback(null);
+ }
+ }
+ };
+
+ async.forEachOfSeries =
+ async.eachOfSeries = function (obj, iterator, callback) {
+ callback = _once(callback || noop);
+ obj = obj || [];
+ var nextKey = _keyIterator(obj);
+ var key = nextKey();
+ function iterate() {
+ var sync = true;
+ if (key === null) {
+ return callback(null);
+ }
+ iterator(obj[key], key, only_once(function (err) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ key = nextKey();
+ if (key === null) {
+ return callback(null);
+ } else {
+ if (sync) {
+ async.setImmediate(iterate);
+ } else {
+ iterate();
+ }
+ }
+ }
+ }));
+ sync = false;
+ }
+ iterate();
+ };
+
+
+
+ async.forEachOfLimit =
+ async.eachOfLimit = function (obj, limit, iterator, callback) {
+ _eachOfLimit(limit)(obj, iterator, callback);
+ };
+
+ function _eachOfLimit(limit) {
+
+ return function (obj, iterator, callback) {
+ callback = _once(callback || noop);
+ obj = obj || [];
+ var nextKey = _keyIterator(obj);
+ if (limit <= 0) {
+ return callback(null);
+ }
+ var done = false;
+ var running = 0;
+ var errored = false;
+
+ (function replenish () {
+ if (done && running <= 0) {
+ return callback(null);
+ }
+
+ while (running < limit && !errored) {
+ var key = nextKey();
+ if (key === null) {
+ done = true;
+ if (running <= 0) {
+ callback(null);
+ }
+ return;
+ }
+ running += 1;
+ iterator(obj[key], key, only_once(function (err) {
+ running -= 1;
+ if (err) {
+ callback(err);
+ errored = true;
+ }
+ else {
+ replenish();
+ }
+ }));
+ }
+ })();
+ };
+ }
+
+
+ function doParallel(fn) {
+ return function (obj, iterator, callback) {
+ return fn(async.eachOf, obj, iterator, callback);
+ };
+ }
+ function doParallelLimit(fn) {
+ return function (obj, limit, iterator, callback) {
+ return fn(_eachOfLimit(limit), obj, iterator, callback);
+ };
+ }
+ function doSeries(fn) {
+ return function (obj, iterator, callback) {
+ return fn(async.eachOfSeries, obj, iterator, callback);
+ };
+ }
+
+ function _asyncMap(eachfn, arr, iterator, callback) {
+ callback = _once(callback || noop);
+ arr = arr || [];
+ var results = _isArrayLike(arr) ? [] : {};
+ eachfn(arr, function (value, index, callback) {
+ iterator(value, function (err, v) {
+ results[index] = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+
+ async.map = doParallel(_asyncMap);
+ async.mapSeries = doSeries(_asyncMap);
+ async.mapLimit = doParallelLimit(_asyncMap);
+
+ // reduce only has a series version, as doing reduce in parallel won't
+ // work in many situations.
+ async.inject =
+ async.foldl =
+ async.reduce = function (arr, memo, iterator, callback) {
+ async.eachOfSeries(arr, function (x, i, callback) {
+ iterator(memo, x, function (err, v) {
+ memo = v;
+ callback(err);
+ });
+ }, function (err) {
+ callback(err, memo);
+ });
+ };
+
+ async.foldr =
+ async.reduceRight = function (arr, memo, iterator, callback) {
+ var reversed = _map(arr, identity).reverse();
+ async.reduce(reversed, memo, iterator, callback);
+ };
+
+ async.transform = function (arr, memo, iterator, callback) {
+ if (arguments.length === 3) {
+ callback = iterator;
+ iterator = memo;
+ memo = _isArray(arr) ? [] : {};
+ }
+
+ async.eachOf(arr, function(v, k, cb) {
+ iterator(memo, v, k, cb);
+ }, function(err) {
+ callback(err, memo);
+ });
+ };
+
+ function _filter(eachfn, arr, iterator, callback) {
+ var results = [];
+ eachfn(arr, function (x, index, callback) {
+ iterator(x, function (v) {
+ if (v) {
+ results.push({index: index, value: x});
+ }
+ callback();
+ });
+ }, function () {
+ callback(_map(results.sort(function (a, b) {
+ return a.index - b.index;
+ }), function (x) {
+ return x.value;
+ }));
+ });
+ }
+
+ async.select =
+ async.filter = doParallel(_filter);
+
+ async.selectLimit =
+ async.filterLimit = doParallelLimit(_filter);
+
+ async.selectSeries =
+ async.filterSeries = doSeries(_filter);
+
+ function _reject(eachfn, arr, iterator, callback) {
+ _filter(eachfn, arr, function(value, cb) {
+ iterator(value, function(v) {
+ cb(!v);
+ });
+ }, callback);
+ }
+ async.reject = doParallel(_reject);
+ async.rejectLimit = doParallelLimit(_reject);
+ async.rejectSeries = doSeries(_reject);
+
+ function _createTester(eachfn, check, getResult) {
+ return function(arr, limit, iterator, cb) {
+ function done() {
+ if (cb) cb(getResult(false, void 0));
+ }
+ function iteratee(x, _, callback) {
+ if (!cb) return callback();
+ iterator(x, function (v) {
+ if (cb && check(v)) {
+ cb(getResult(true, x));
+ cb = iterator = false;
+ }
+ callback();
+ });
+ }
+ if (arguments.length > 3) {
+ eachfn(arr, limit, iteratee, done);
+ } else {
+ cb = iterator;
+ iterator = limit;
+ eachfn(arr, iteratee, done);
+ }
+ };
+ }
+
+ async.any =
+ async.some = _createTester(async.eachOf, toBool, identity);
+
+ async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
+
+ async.all =
+ async.every = _createTester(async.eachOf, notId, notId);
+
+ async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
+
+ function _findGetResult(v, x) {
+ return x;
+ }
+ async.detect = _createTester(async.eachOf, identity, _findGetResult);
+ async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
+ async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
+
+ async.sortBy = function (arr, iterator, callback) {
+ async.map(arr, function (x, callback) {
+ iterator(x, function (err, criteria) {
+ if (err) {
+ callback(err);
+ }
+ else {
+ callback(null, {value: x, criteria: criteria});
+ }
+ });
+ }, function (err, results) {
+ if (err) {
+ return callback(err);
+ }
+ else {
+ callback(null, _map(results.sort(comparator), function (x) {
+ return x.value;
+ }));
+ }
+
+ });
+
+ function comparator(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }
+ };
+
+ async.auto = function (tasks, concurrency, callback) {
+ if (typeof arguments[1] === 'function') {
+ // concurrency is optional, shift the args.
+ callback = concurrency;
+ concurrency = null;
+ }
+ callback = _once(callback || noop);
+ var keys = _keys(tasks);
+ var remainingTasks = keys.length;
+ if (!remainingTasks) {
+ return callback(null);
+ }
+ if (!concurrency) {
+ concurrency = remainingTasks;
+ }
+
+ var results = {};
+ var runningTasks = 0;
+
+ var hasError = false;
+
+ var listeners = [];
+ function addListener(fn) {
+ listeners.unshift(fn);
+ }
+ function removeListener(fn) {
+ var idx = _indexOf(listeners, fn);
+ if (idx >= 0) listeners.splice(idx, 1);
+ }
+ function taskComplete() {
+ remainingTasks--;
+ _arrayEach(listeners.slice(0), function (fn) {
+ fn();
+ });
+ }
+
+ addListener(function () {
+ if (!remainingTasks) {
+ callback(null, results);
+ }
+ });
+
+ _arrayEach(keys, function (k) {
+ if (hasError) return;
+ var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
+ var taskCallback = _restParam(function(err, args) {
+ runningTasks--;
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ if (err) {
+ var safeResults = {};
+ _forEachOf(results, function(val, rkey) {
+ safeResults[rkey] = val;
+ });
+ safeResults[k] = args;
+ hasError = true;
+
+ callback(err, safeResults);
+ }
+ else {
+ results[k] = args;
+ async.setImmediate(taskComplete);
+ }
+ });
+ var requires = task.slice(0, task.length - 1);
+ // prevent dead-locks
+ var len = requires.length;
+ var dep;
+ while (len--) {
+ if (!(dep = tasks[requires[len]])) {
+ throw new Error('Has nonexistent dependency in ' + requires.join(', '));
+ }
+ if (_isArray(dep) && _indexOf(dep, k) >= 0) {
+ throw new Error('Has cyclic dependencies');
+ }
+ }
+ function ready() {
+ return runningTasks < concurrency && _reduce(requires, function (a, x) {
+ return (a && results.hasOwnProperty(x));
+ }, true) && !results.hasOwnProperty(k);
+ }
+ if (ready()) {
+ runningTasks++;
+ task[task.length - 1](taskCallback, results);
+ }
+ else {
+ addListener(listener);
+ }
+ function listener() {
+ if (ready()) {
+ runningTasks++;
+ removeListener(listener);
+ task[task.length - 1](taskCallback, results);
+ }
+ }
+ });
+ };
+
+
+
+ async.retry = function(times, task, callback) {
+ var DEFAULT_TIMES = 5;
+ var DEFAULT_INTERVAL = 0;
+
+ var attempts = [];
+
+ var opts = {
+ times: DEFAULT_TIMES,
+ interval: DEFAULT_INTERVAL
+ };
+
+ function parseTimes(acc, t){
+ if(typeof t === 'number'){
+ acc.times = parseInt(t, 10) || DEFAULT_TIMES;
+ } else if(typeof t === 'object'){
+ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
+ acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
+ } else {
+ throw new Error('Unsupported argument type for \'times\': ' + typeof t);
+ }
+ }
+
+ var length = arguments.length;
+ if (length < 1 || length > 3) {
+ throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
+ } else if (length <= 2 && typeof times === 'function') {
+ callback = task;
+ task = times;
+ }
+ if (typeof times !== 'function') {
+ parseTimes(opts, times);
+ }
+ opts.callback = callback;
+ opts.task = task;
+
+ function wrappedTask(wrappedCallback, wrappedResults) {
+ function retryAttempt(task, finalAttempt) {
+ return function(seriesCallback) {
+ task(function(err, result){
+ seriesCallback(!err || finalAttempt, {err: err, result: result});
+ }, wrappedResults);
+ };
+ }
+
+ function retryInterval(interval){
+ return function(seriesCallback){
+ setTimeout(function(){
+ seriesCallback(null);
+ }, interval);
+ };
+ }
+
+ while (opts.times) {
+
+ var finalAttempt = !(opts.times-=1);
+ attempts.push(retryAttempt(opts.task, finalAttempt));
+ if(!finalAttempt && opts.interval > 0){
+ attempts.push(retryInterval(opts.interval));
+ }
+ }
+
+ async.series(attempts, function(done, data){
+ data = data[data.length - 1];
+ (wrappedCallback || opts.callback)(data.err, data.result);
+ });
+ }
+
+ // If a callback is passed, run this as a controll flow
+ return opts.callback ? wrappedTask() : wrappedTask;
+ };
+
+ async.waterfall = function (tasks, callback) {
+ callback = _once(callback || noop);
+ if (!_isArray(tasks)) {
+ var err = new Error('First argument to waterfall must be an array of functions');
+ return callback(err);
+ }
+ if (!tasks.length) {
+ return callback();
+ }
+ function wrapIterator(iterator) {
+ return _restParam(function (err, args) {
+ if (err) {
+ callback.apply(null, [err].concat(args));
+ }
+ else {
+ var next = iterator.next();
+ if (next) {
+ args.push(wrapIterator(next));
+ }
+ else {
+ args.push(callback);
+ }
+ ensureAsync(iterator).apply(null, args);
+ }
+ });
+ }
+ wrapIterator(async.iterator(tasks))();
+ };
+
+ function _parallel(eachfn, tasks, callback) {
+ callback = callback || noop;
+ var results = _isArrayLike(tasks) ? [] : {};
+
+ eachfn(tasks, function (task, key, callback) {
+ task(_restParam(function (err, args) {
+ if (args.length <= 1) {
+ args = args[0];
+ }
+ results[key] = args;
+ callback(err);
+ }));
+ }, function (err) {
+ callback(err, results);
+ });
+ }
+
+ async.parallel = function (tasks, callback) {
+ _parallel(async.eachOf, tasks, callback);
+ };
+
+ async.parallelLimit = function(tasks, limit, callback) {
+ _parallel(_eachOfLimit(limit), tasks, callback);
+ };
+
+ async.series = function(tasks, callback) {
+ _parallel(async.eachOfSeries, tasks, callback);
+ };
+
+ async.iterator = function (tasks) {
+ function makeCallback(index) {
+ function fn() {
+ if (tasks.length) {
+ tasks[index].apply(null, arguments);
+ }
+ return fn.next();
+ }
+ fn.next = function () {
+ return (index < tasks.length - 1) ? makeCallback(index + 1): null;
+ };
+ return fn;
+ }
+ return makeCallback(0);
+ };
+
+ async.apply = _restParam(function (fn, args) {
+ return _restParam(function (callArgs) {
+ return fn.apply(
+ null, args.concat(callArgs)
+ );
+ });
+ });
+
+ function _concat(eachfn, arr, fn, callback) {
+ var result = [];
+ eachfn(arr, function (x, index, cb) {
+ fn(x, function (err, y) {
+ result = result.concat(y || []);
+ cb(err);
+ });
+ }, function (err) {
+ callback(err, result);
+ });
+ }
+ async.concat = doParallel(_concat);
+ async.concatSeries = doSeries(_concat);
+
+ async.whilst = function (test, iterator, callback) {
+ callback = callback || noop;
+ if (test()) {
+ var next = _restParam(function(err, args) {
+ if (err) {
+ callback(err);
+ } else if (test.apply(this, args)) {
+ iterator(next);
+ } else {
+ callback.apply(null, [null].concat(args));
+ }
+ });
+ iterator(next);
+ } else {
+ callback(null);
+ }
+ };
+
+ async.doWhilst = function (iterator, test, callback) {
+ var calls = 0;
+ return async.whilst(function() {
+ return ++calls <= 1 || test.apply(this, arguments);
+ }, iterator, callback);
+ };
+
+ async.until = function (test, iterator, callback) {
+ return async.whilst(function() {
+ return !test.apply(this, arguments);
+ }, iterator, callback);
+ };
+
+ async.doUntil = function (iterator, test, callback) {
+ return async.doWhilst(iterator, function() {
+ return !test.apply(this, arguments);
+ }, callback);
+ };
+
+ async.during = function (test, iterator, callback) {
+ callback = callback || noop;
+
+ var next = _restParam(function(err, args) {
+ if (err) {
+ callback(err);
+ } else {
+ args.push(check);
+ test.apply(this, args);
+ }
+ });
+
+ var check = function(err, truth) {
+ if (err) {
+ callback(err);
+ } else if (truth) {
+ iterator(next);
+ } else {
+ callback(null);
+ }
+ };
+
+ test(check);
+ };
+
+ async.doDuring = function (iterator, test, callback) {
+ var calls = 0;
+ async.during(function(next) {
+ if (calls++ < 1) {
+ next(null, true);
+ } else {
+ test.apply(this, arguments);
+ }
+ }, iterator, callback);
+ };
+
+ function _queue(worker, concurrency, payload) {
+ if (concurrency == null) {
+ concurrency = 1;
+ }
+ else if(concurrency === 0) {
+ throw new Error('Concurrency must not be zero');
+ }
+ function _insert(q, data, pos, callback) {
+ if (callback != null && typeof callback !== "function") {
+ throw new Error("task callback must be a function");
+ }
+ q.started = true;
+ if (!_isArray(data)) {
+ data = [data];
+ }
+ if(data.length === 0 && q.idle()) {
+ // call drain immediately if there are no tasks
+ return async.setImmediate(function() {
+ q.drain();
+ });
+ }
+ _arrayEach(data, function(task) {
+ var item = {
+ data: task,
+ callback: callback || noop
+ };
+
+ if (pos) {
+ q.tasks.unshift(item);
+ } else {
+ q.tasks.push(item);
+ }
+
+ if (q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ });
+ async.setImmediate(q.process);
+ }
+ function _next(q, tasks) {
+ return function(){
+ workers -= 1;
+
+ var removed = false;
+ var args = arguments;
+ _arrayEach(tasks, function (task) {
+ _arrayEach(workersList, function (worker, index) {
+ if (worker === task && !removed) {
+ workersList.splice(index, 1);
+ removed = true;
+ }
+ });
+
+ task.callback.apply(task, args);
+ });
+ if (q.tasks.length + workers === 0) {
+ q.drain();
+ }
+ q.process();
+ };
+ }
+
+ var workers = 0;
+ var workersList = [];
+ var q = {
+ tasks: [],
+ concurrency: concurrency,
+ payload: payload,
+ saturated: noop,
+ empty: noop,
+ drain: noop,
+ started: false,
+ paused: false,
+ push: function (data, callback) {
+ _insert(q, data, false, callback);
+ },
+ kill: function () {
+ q.drain = noop;
+ q.tasks = [];
+ },
+ unshift: function (data, callback) {
+ _insert(q, data, true, callback);
+ },
+ process: function () {
+ while(!q.paused && workers < q.concurrency && q.tasks.length){
+
+ var tasks = q.payload ?
+ q.tasks.splice(0, q.payload) :
+ q.tasks.splice(0, q.tasks.length);
+
+ var data = _map(tasks, function (task) {
+ return task.data;
+ });
+
+ if (q.tasks.length === 0) {
+ q.empty();
+ }
+ workers += 1;
+ workersList.push(tasks[0]);
+ var cb = only_once(_next(q, tasks));
+ worker(data, cb);
+ }
+ },
+ length: function () {
+ return q.tasks.length;
+ },
+ running: function () {
+ return workers;
+ },
+ workersList: function () {
+ return workersList;
+ },
+ idle: function() {
+ return q.tasks.length + workers === 0;
+ },
+ pause: function () {
+ q.paused = true;
+ },
+ resume: function () {
+ if (q.paused === false) { return; }
+ q.paused = false;
+ var resumeCount = Math.min(q.concurrency, q.tasks.length);
+ // Need to call q.process once per concurrent
+ // worker to preserve full concurrency after pause
+ for (var w = 1; w <= resumeCount; w++) {
+ async.setImmediate(q.process);
+ }
+ }
+ };
+ return q;
+ }
+
+ async.queue = function (worker, concurrency) {
+ var q = _queue(function (items, cb) {
+ worker(items[0], cb);
+ }, concurrency, 1);
+
+ return q;
+ };
+
+ async.priorityQueue = function (worker, concurrency) {
+
+ function _compareTasks(a, b){
+ return a.priority - b.priority;
+ }
+
+ function _binarySearch(sequence, item, compare) {
+ var beg = -1,
+ end = sequence.length - 1;
+ while (beg < end) {
+ var mid = beg + ((end - beg + 1) >>> 1);
+ if (compare(item, sequence[mid]) >= 0) {
+ beg = mid;
+ } else {
+ end = mid - 1;
+ }
+ }
+ return beg;
+ }
+
+ function _insert(q, data, priority, callback) {
+ if (callback != null && typeof callback !== "function") {
+ throw new Error("task callback must be a function");
+ }
+ q.started = true;
+ if (!_isArray(data)) {
+ data = [data];
+ }
+ if(data.length === 0) {
+ // call drain immediately if there are no tasks
+ return async.setImmediate(function() {
+ q.drain();
+ });
+ }
+ _arrayEach(data, function(task) {
+ var item = {
+ data: task,
+ priority: priority,
+ callback: typeof callback === 'function' ? callback : noop
+ };
+
+ q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
+
+ if (q.tasks.length === q.concurrency) {
+ q.saturated();
+ }
+ async.setImmediate(q.process);
+ });
+ }
+
+ // Start with a normal queue
+ var q = async.queue(worker, concurrency);
+
+ // Override push to accept second parameter representing priority
+ q.push = function (data, priority, callback) {
+ _insert(q, data, priority, callback);
+ };
+
+ // Remove unshift function
+ delete q.unshift;
+
+ return q;
+ };
+
+ async.cargo = function (worker, payload) {
+ return _queue(worker, 1, payload);
+ };
+
+ function _console_fn(name) {
+ return _restParam(function (fn, args) {
+ fn.apply(null, args.concat([_restParam(function (err, args) {
+ if (typeof console === 'object') {
+ if (err) {
+ if (console.error) {
+ console.error(err);
+ }
+ }
+ else if (console[name]) {
+ _arrayEach(args, function (x) {
+ console[name](x);
+ });
+ }
+ }
+ })]));
+ });
+ }
+ async.log = _console_fn('log');
+ async.dir = _console_fn('dir');
+ /*async.info = _console_fn('info');
+ async.warn = _console_fn('warn');
+ async.error = _console_fn('error');*/
+
+ async.memoize = function (fn, hasher) {
+ var memo = {};
+ var queues = {};
+ var has = Object.prototype.hasOwnProperty;
+ hasher = hasher || identity;
+ var memoized = _restParam(function memoized(args) {
+ var callback = args.pop();
+ var key = hasher.apply(null, args);
+ if (has.call(memo, key)) {
+ async.setImmediate(function () {
+ callback.apply(null, memo[key]);
+ });
+ }
+ else if (has.call(queues, key)) {
+ queues[key].push(callback);
+ }
+ else {
+ queues[key] = [callback];
+ fn.apply(null, args.concat([_restParam(function (args) {
+ memo[key] = args;
+ var q = queues[key];
+ delete queues[key];
+ for (var i = 0, l = q.length; i < l; i++) {
+ q[i].apply(null, args);
+ }
+ })]));
+ }
+ });
+ memoized.memo = memo;
+ memoized.unmemoized = fn;
+ return memoized;
+ };
+
+ async.unmemoize = function (fn) {
+ return function () {
+ return (fn.unmemoized || fn).apply(null, arguments);
+ };
+ };
+
+ function _times(mapper) {
+ return function (count, iterator, callback) {
+ mapper(_range(count), iterator, callback);
+ };
+ }
+
+ async.times = _times(async.map);
+ async.timesSeries = _times(async.mapSeries);
+ async.timesLimit = function (count, limit, iterator, callback) {
+ return async.mapLimit(_range(count), limit, iterator, callback);
+ };
+
+ async.seq = function (/* functions... */) {
+ var fns = arguments;
+ return _restParam(function (args) {
+ var that = this;
+
+ var callback = args[args.length - 1];
+ if (typeof callback == 'function') {
+ args.pop();
+ } else {
+ callback = noop;
+ }
+
+ async.reduce(fns, args, function (newargs, fn, cb) {
+ fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
+ cb(err, nextargs);
+ })]));
+ },
+ function (err, results) {
+ callback.apply(that, [err].concat(results));
+ });
+ });
+ };
+
+ async.compose = function (/* functions... */) {
+ return async.seq.apply(null, Array.prototype.reverse.call(arguments));
+ };
+
+
+ function _applyEach(eachfn) {
+ return _restParam(function(fns, args) {
+ var go = _restParam(function(args) {
+ var that = this;
+ var callback = args.pop();
+ return eachfn(fns, function (fn, _, cb) {
+ fn.apply(that, args.concat([cb]));
+ },
+ callback);
+ });
+ if (args.length) {
+ return go.apply(this, args);
+ }
+ else {
+ return go;
+ }
+ });
+ }
+
+ async.applyEach = _applyEach(async.eachOf);
+ async.applyEachSeries = _applyEach(async.eachOfSeries);
+
+
+ async.forever = function (fn, callback) {
+ var done = only_once(callback || noop);
+ var task = ensureAsync(fn);
+ function next(err) {
+ if (err) {
+ return done(err);
+ }
+ task(next);
+ }
+ next();
+ };
+
+ function ensureAsync(fn) {
+ return _restParam(function (args) {
+ var callback = args.pop();
+ args.push(function () {
+ var innerArgs = arguments;
+ if (sync) {
+ async.setImmediate(function () {
+ callback.apply(null, innerArgs);
+ });
+ } else {
+ callback.apply(null, innerArgs);
+ }
+ });
+ var sync = true;
+ fn.apply(this, args);
+ sync = false;
+ });
+ }
+
+ async.ensureAsync = ensureAsync;
+
+ async.constant = _restParam(function(values) {
+ var args = [null].concat(values);
+ return function (callback) {
+ return callback.apply(this, args);
+ };
+ });
+
+ async.wrapSync =
+ async.asyncify = function asyncify(func) {
+ return _restParam(function (args) {
+ var callback = args.pop();
+ var result;
+ try {
+ result = func.apply(this, args);
+ } catch (e) {
+ return callback(e);
+ }
+ // if result is Promise object
+ if (_isObject(result) && typeof result.then === "function") {
+ result.then(function(value) {
+ callback(null, value);
+ })["catch"](function(err) {
+ callback(err.message ? err : new Error(err));
+ });
+ } else {
+ callback(null, result);
+ }
+ });
+ };
+
+ // Node.js
+ if (typeof module === 'object' && module.exports) {
+ module.exports = async;
+ }
+ // AMD / RequireJS
+ else if (typeof define === 'function' && define.amd) {
+ define([], function () {
+ return async;
+ });
+ }
+ // included directly via
+
+or as a CommonJS, [Node.js](http://nodejs.org) or AMD module using `require`.
+
+ var Big = require('big.js');
+
+For Node.js, the library is available from the npm registry:
+
+ $ npm install big.js
+
+
+
+## Use
+
+*In all examples below, `var`, semicolons and `toString` calls are not shown.
+If a commented-out value is in quotes it means `toString` has been called on the preceding expression.*
+
+The library exports a single function: Big, the constructor of Big number instances.
+It accepts a value of type Number, String or Big number Object.
+
+ x = new Big(123.4567)
+ y = Big('123456.7e-3') // 'new' is optional
+ z = new Big(x)
+ x.eq(y) && x.eq(z) && y.eq(z) // true
+
+A Big number is immutable in the sense that it is not changed by its methods.
+
+ 0.3 - 0.1 // 0.19999999999999998
+ x = new Big(0.3)
+ x.minus(0.1) // "0.2"
+ x // "0.3"
+
+The methods that return a Big number can be chained.
+
+ x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')
+ x.sqrt().div(y).pow(3).gt(y.mod(z)) // true
+
+Like JavaScript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods.
+
+ x = new Big(255.5)
+ x.toExponential(5) // "2.55500e+2"
+ x.toFixed(5) // "255.50000"
+ x.toPrecision(5) // "255.50"
+
+The maximum number of decimal places and the rounding mode used to round the results of the `div`, `sqrt` and `pow`
+(with negative exponent) methods is determined by the value of the `DP` and `RM` properties of the `Big` number constructor.
+
+The other methods always give the exact result.
+
+(From *v3.0.0*, multiple Big number constructors can be created, see Change Log below.)
+
+ Big.DP = 10
+ Big.RM = 1
+
+ x = new Big(2);
+ y = new Big(3);
+ z = x.div(y) // "0.6666666667"
+ z.sqrt() // "0.8164965809"
+ z.pow(-3) // "3.3749999995"
+ z.times(z) // "0.44444444448888888889"
+ z.times(z).round(10) // "0.4444444445"
+
+
+The value of a Big number is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
+
+ x = new Big(-123.456);
+ x.c // [1,2,3,4,5,6] coefficient (i.e. significand)
+ x.e // 2 exponent
+ x.s // -1 sign
+
+For further information see the [API](http://mikemcl.github.io/big.js/) reference from the *doc* folder.
+
+## Test
+
+The *test* directory contains the test scripts for each Big number method.
+
+The tests can be run with Node or a browser.
+
+To test a single method, from a command-line shell at the *test* directory, use e.g.
+
+ $ node toFixed
+
+To test all the methods
+
+ $ node every-test
+
+For the browser, see *single-test.html* and *every-test.html* in the *test/browser* directory.
+
+*big-vs-number.html* enables some of the methods of big.js to be compared with those of JavaScript's Number type.
+
+## Performance
+
+The *perf* directory contains two applications and a *lib* directory containing the BigDecimal libraries used by both.
+
+*big-vs-bigdecimal.html* tests the performance of big.js against the JavaScript translations of two versions of BigDecimal, its use should be more or less self-explanatory.
+(The GWT version doesn't work in IE 6.)
+
+* GWT: java.math.BigDecimal
+
+* ICU4J: com.ibm.icu.math.BigDecimal
+
+
+The BigDecimal in Node's npm registry is the GWT version. Despite its seeming popularity I have found it to have some serious bugs, see the Node script *perf/lib/bigdecimal_GWT/bugs.js* for examples of flaws in its *remainder*, *divide* and *compareTo* methods.
+
+*bigtime.js* is a Node command-line application which tests the performance of big.js against the GWT version of
+BigDecimal from the npm registry.
+
+For example, to compare the time taken by the big.js `plus` method and the BigDecimal `add` method:
+
+ $ node bigtime plus 10000 40
+
+This will time 10000 calls to each, using operands of up to 40 random digits and will check that the results match.
+
+For help:
+
+ $ node bigtime -h
+
+## Build
+
+I.e. minify.
+
+For Node, if uglify-js is installed globally ( `npm install uglify-js -g` ) then
+
+ uglifyjs -o ./big.min.js ./big.js
+
+will create *big.min.js*.
+
+The *big.min.js* already present was created with *Microsoft Ajax Minifier 5.11*.
+
+## TypeScript
+
+The [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) project has a TypeScript [definitions file](https://github.com/borisyankov/DefinitelyTyped/blob/master/big.js/big.js.d.ts) for big.js.
+
+The definitions file can be added to your project via the [big.js.TypeScript.DefinitelyTyped](https://www.nuget.org/packages/big.js.TypeScript.DefinitelyTyped/0.0.1) NuGet package or via [tsd](http://definitelytyped.org/tsd/).
+
+ tsd query big.js --action install
+
+Any questions about the TypeScript definitions file should be addressed to the DefinitelyTyped project.
+
+## Feedback
+
+Feedback is welcome.
+
+Bugs/comments/questions?
+Open an issue, or email
+
+Michael
+M8ch88l@gmail.com
+
+Bitcoin donation to:
+**1DppGRQSjVSMgGxuygDEHQuWEdTiVEzJYG**
+Thank you
+
+## Licence
+
+See LICENCE.
+
+## Change Log
+
+####3.1.3
+
+* Minor documentation updates.
+
+####3.1.2
+
+* README typo.
+
+####3.1.1
+
+* API documentation update, including FAQ additions.
+
+####3.1.0
+
+* Renamed and exposed `TO_EXP_NEG` and `TO_EXP_POS` as `Big.E_NEG` and
+ `Big.E_POS`.
+
+####3.0.2
+
+* Remove *.npmignore*, use `files` field in *package.json* instead.
+
+####3.0.1
+
+* Added `sub`, `add` and `mul` aliases.
+* Clean-up after lint.
+
+####3.0.0
+
+* 10/12/14 Added [multiple constructor functionality](http://mikemcl.github.io/big.js/#faq).
+* No breaking changes or other additions, but a major code reorganisation,
+ so *v3* seemed appropiate.
+
+####2.5.2
+
+* 1/11/14 Added bower.json.
+
+####2.5.1
+
+* 8/06/14 Amend README requires.
+
+####2.5.0
+
+* 26/01/14 Added `toJSON` method so serialization uses `toString`.
+
+####2.4.1
+
+* 17/10/13 Conform signed zero to IEEEE 754 (2008).
+
+####2.4.0
+
+* 19/09/13 Throw instances of `Error`.
+
+####2.3.0
+
+* 16/09/13 Added `cmp` method.
+
+####2.2.0
+
+* 11/07/13 Added 'round up' mode.
+
+####2.1.0
+
+* 26/06/13 Allow e.g. `.1` and `2.`.
+
+####2.0.0
+
+* 12/05/13 Added `abs` method and replaced `cmp` with `eq`, `gt`, `gte`, `lt`, and `lte` methods.
+
+####1.0.1
+
+* Changed default value of MAX_DP to 1E6
+
+####1.0.0
+
+* 7/11/2012 Initial release
diff --git a/node_modules/big.js/big.js b/node_modules/big.js/big.js
new file mode 100644
index 0000000..4db5b3e
--- /dev/null
+++ b/node_modules/big.js/big.js
@@ -0,0 +1,1142 @@
+/* big.js v3.1.3 https://github.com/MikeMcl/big.js/LICENCE */
+;(function (global) {
+ 'use strict';
+
+/*
+ big.js v3.1.3
+ A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic.
+ https://github.com/MikeMcl/big.js/
+ Copyright (c) 2014 Michael Mclaughlin
+ MIT Expat Licence
+*/
+
+/***************************** EDITABLE DEFAULTS ******************************/
+
+ // The default values below must be integers within the stated ranges.
+
+ /*
+ * The maximum number of decimal places of the results of operations
+ * involving division: div and sqrt, and pow with negative exponents.
+ */
+ var DP = 20, // 0 to MAX_DP
+
+ /*
+ * The rounding mode used when rounding to the above decimal places.
+ *
+ * 0 Towards zero (i.e. truncate, no rounding). (ROUND_DOWN)
+ * 1 To nearest neighbour. If equidistant, round up. (ROUND_HALF_UP)
+ * 2 To nearest neighbour. If equidistant, to even. (ROUND_HALF_EVEN)
+ * 3 Away from zero. (ROUND_UP)
+ */
+ RM = 1, // 0, 1, 2 or 3
+
+ // The maximum value of DP and Big.DP.
+ MAX_DP = 1E6, // 0 to 1000000
+
+ // The maximum magnitude of the exponent argument to the pow method.
+ MAX_POWER = 1E6, // 1 to 1000000
+
+ /*
+ * The exponent value at and beneath which toString returns exponential
+ * notation.
+ * JavaScript's Number type: -7
+ * -1000000 is the minimum recommended exponent value of a Big.
+ */
+ E_NEG = -7, // 0 to -1000000
+
+ /*
+ * The exponent value at and above which toString returns exponential
+ * notation.
+ * JavaScript's Number type: 21
+ * 1000000 is the maximum recommended exponent value of a Big.
+ * (This limit is not enforced or checked.)
+ */
+ E_POS = 21, // 0 to 1000000
+
+/******************************************************************************/
+
+ // The shared prototype object.
+ P = {},
+ isValid = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
+ Big;
+
+
+ /*
+ * Create and return a Big constructor.
+ *
+ */
+ function bigFactory() {
+
+ /*
+ * The Big constructor and exported function.
+ * Create and return a new instance of a Big number object.
+ *
+ * n {number|string|Big} A numeric value.
+ */
+ function Big(n) {
+ var x = this;
+
+ // Enable constructor usage without new.
+ if (!(x instanceof Big)) {
+ return n === void 0 ? bigFactory() : new Big(n);
+ }
+
+ // Duplicate.
+ if (n instanceof Big) {
+ x.s = n.s;
+ x.e = n.e;
+ x.c = n.c.slice();
+ } else {
+ parse(x, n);
+ }
+
+ /*
+ * Retain a reference to this Big constructor, and shadow
+ * Big.prototype.constructor which points to Object.
+ */
+ x.constructor = Big;
+ }
+
+ Big.prototype = P;
+ Big.DP = DP;
+ Big.RM = RM;
+ Big.E_NEG = E_NEG;
+ Big.E_POS = E_POS;
+
+ return Big;
+ }
+
+
+ // Private functions
+
+
+ /*
+ * Return a string representing the value of Big x in normal or exponential
+ * notation to dp fixed decimal places or significant digits.
+ *
+ * x {Big} The Big to format.
+ * dp {number} Integer, 0 to MAX_DP inclusive.
+ * toE {number} 1 (toExponential), 2 (toPrecision) or undefined (toFixed).
+ */
+ function format(x, dp, toE) {
+ var Big = x.constructor,
+
+ // The index (normal notation) of the digit that may be rounded up.
+ i = dp - (x = new Big(x)).e,
+ c = x.c;
+
+ // Round?
+ if (c.length > ++dp) {
+ rnd(x, i, Big.RM);
+ }
+
+ if (!c[0]) {
+ ++i;
+ } else if (toE) {
+ i = dp;
+
+ // toFixed
+ } else {
+ c = x.c;
+
+ // Recalculate i as x.e may have changed if value rounded up.
+ i = x.e + i + 1;
+ }
+
+ // Append zeros?
+ for (; c.length < i; c.push(0)) {
+ }
+ i = x.e;
+
+ /*
+ * toPrecision returns exponential notation if the number of
+ * significant digits specified is less than the number of digits
+ * necessary to represent the integer part of the value in normal
+ * notation.
+ */
+ return toE === 1 || toE && (dp <= i || i <= Big.E_NEG) ?
+
+ // Exponential notation.
+ (x.s < 0 && c[0] ? '-' : '') +
+ (c.length > 1 ? c[0] + '.' + c.join('').slice(1) : c[0]) +
+ (i < 0 ? 'e' : 'e+') + i
+
+ // Normal notation.
+ : x.toString();
+ }
+
+
+ /*
+ * Parse the number or string value passed to a Big constructor.
+ *
+ * x {Big} A Big number instance.
+ * n {number|string} A numeric value.
+ */
+ function parse(x, n) {
+ var e, i, nL;
+
+ // Minus zero?
+ if (n === 0 && 1 / n < 0) {
+ n = '-0';
+
+ // Ensure n is string and check validity.
+ } else if (!isValid.test(n += '')) {
+ throwErr(NaN);
+ }
+
+ // Determine sign.
+ x.s = n.charAt(0) == '-' ? (n = n.slice(1), -1) : 1;
+
+ // Decimal point?
+ if ((e = n.indexOf('.')) > -1) {
+ n = n.replace('.', '');
+ }
+
+ // Exponential form?
+ if ((i = n.search(/e/i)) > 0) {
+
+ // Determine exponent.
+ if (e < 0) {
+ e = i;
+ }
+ e += +n.slice(i + 1);
+ n = n.substring(0, i);
+
+ } else if (e < 0) {
+
+ // Integer.
+ e = n.length;
+ }
+
+ // Determine leading zeros.
+ for (i = 0; n.charAt(i) == '0'; i++) {
+ }
+
+ if (i == (nL = n.length)) {
+
+ // Zero.
+ x.c = [ x.e = 0 ];
+ } else {
+
+ // Determine trailing zeros.
+ for (; n.charAt(--nL) == '0';) {
+ }
+
+ x.e = e - i - 1;
+ x.c = [];
+
+ // Convert string to array of digits without leading/trailing zeros.
+ for (e = 0; i <= nL; x.c[e++] = +n.charAt(i++)) {
+ }
+ }
+
+ return x;
+ }
+
+
+ /*
+ * Round Big x to a maximum of dp decimal places using rounding mode rm.
+ * Called by div, sqrt and round.
+ *
+ * x {Big} The Big to round.
+ * dp {number} Integer, 0 to MAX_DP inclusive.
+ * rm {number} 0, 1, 2 or 3 (DOWN, HALF_UP, HALF_EVEN, UP)
+ * [more] {boolean} Whether the result of division was truncated.
+ */
+ function rnd(x, dp, rm, more) {
+ var u,
+ xc = x.c,
+ i = x.e + dp + 1;
+
+ if (rm === 1) {
+
+ // xc[i] is the digit after the digit that may be rounded up.
+ more = xc[i] >= 5;
+ } else if (rm === 2) {
+ more = xc[i] > 5 || xc[i] == 5 &&
+ (more || i < 0 || xc[i + 1] !== u || xc[i - 1] & 1);
+ } else if (rm === 3) {
+ more = more || xc[i] !== u || i < 0;
+ } else {
+ more = false;
+
+ if (rm !== 0) {
+ throwErr('!Big.RM!');
+ }
+ }
+
+ if (i < 1 || !xc[0]) {
+
+ if (more) {
+
+ // 1, 0.1, 0.01, 0.001, 0.0001 etc.
+ x.e = -dp;
+ x.c = [1];
+ } else {
+
+ // Zero.
+ x.c = [x.e = 0];
+ }
+ } else {
+
+ // Remove any digits after the required decimal places.
+ xc.length = i--;
+
+ // Round up?
+ if (more) {
+
+ // Rounding up may mean the previous digit has to be rounded up.
+ for (; ++xc[i] > 9;) {
+ xc[i] = 0;
+
+ if (!i--) {
+ ++x.e;
+ xc.unshift(1);
+ }
+ }
+ }
+
+ // Remove trailing zeros.
+ for (i = xc.length; !xc[--i]; xc.pop()) {
+ }
+ }
+
+ return x;
+ }
+
+
+ /*
+ * Throw a BigError.
+ *
+ * message {string} The error message.
+ */
+ function throwErr(message) {
+ var err = new Error(message);
+ err.name = 'BigError';
+
+ throw err;
+ }
+
+
+ // Prototype/instance methods
+
+
+ /*
+ * Return a new Big whose value is the absolute value of this Big.
+ */
+ P.abs = function () {
+ var x = new this.constructor(this);
+ x.s = 1;
+
+ return x;
+ };
+
+
+ /*
+ * Return
+ * 1 if the value of this Big is greater than the value of Big y,
+ * -1 if the value of this Big is less than the value of Big y, or
+ * 0 if they have the same value.
+ */
+ P.cmp = function (y) {
+ var xNeg,
+ x = this,
+ xc = x.c,
+ yc = (y = new x.constructor(y)).c,
+ i = x.s,
+ j = y.s,
+ k = x.e,
+ l = y.e;
+
+ // Either zero?
+ if (!xc[0] || !yc[0]) {
+ return !xc[0] ? !yc[0] ? 0 : -j : i;
+ }
+
+ // Signs differ?
+ if (i != j) {
+ return i;
+ }
+ xNeg = i < 0;
+
+ // Compare exponents.
+ if (k != l) {
+ return k > l ^ xNeg ? 1 : -1;
+ }
+
+ i = -1;
+ j = (k = xc.length) < (l = yc.length) ? k : l;
+
+ // Compare digit by digit.
+ for (; ++i < j;) {
+
+ if (xc[i] != yc[i]) {
+ return xc[i] > yc[i] ^ xNeg ? 1 : -1;
+ }
+ }
+
+ // Compare lengths.
+ return k == l ? 0 : k > l ^ xNeg ? 1 : -1;
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big divided by the
+ * value of Big y, rounded, if necessary, to a maximum of Big.DP decimal
+ * places using rounding mode Big.RM.
+ */
+ P.div = function (y) {
+ var x = this,
+ Big = x.constructor,
+ // dividend
+ dvd = x.c,
+ //divisor
+ dvs = (y = new Big(y)).c,
+ s = x.s == y.s ? 1 : -1,
+ dp = Big.DP;
+
+ if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
+ throwErr('!Big.DP!');
+ }
+
+ // Either 0?
+ if (!dvd[0] || !dvs[0]) {
+
+ // If both are 0, throw NaN
+ if (dvd[0] == dvs[0]) {
+ throwErr(NaN);
+ }
+
+ // If dvs is 0, throw +-Infinity.
+ if (!dvs[0]) {
+ throwErr(s / 0);
+ }
+
+ // dvd is 0, return +-0.
+ return new Big(s * 0);
+ }
+
+ var dvsL, dvsT, next, cmp, remI, u,
+ dvsZ = dvs.slice(),
+ dvdI = dvsL = dvs.length,
+ dvdL = dvd.length,
+ // remainder
+ rem = dvd.slice(0, dvsL),
+ remL = rem.length,
+ // quotient
+ q = y,
+ qc = q.c = [],
+ qi = 0,
+ digits = dp + (q.e = x.e - y.e) + 1;
+
+ q.s = s;
+ s = digits < 0 ? 0 : digits;
+
+ // Create version of divisor with leading zero.
+ dvsZ.unshift(0);
+
+ // Add zeros to make remainder as long as divisor.
+ for (; remL++ < dvsL; rem.push(0)) {
+ }
+
+ do {
+
+ // 'next' is how many times the divisor goes into current remainder.
+ for (next = 0; next < 10; next++) {
+
+ // Compare divisor and remainder.
+ if (dvsL != (remL = rem.length)) {
+ cmp = dvsL > remL ? 1 : -1;
+ } else {
+
+ for (remI = -1, cmp = 0; ++remI < dvsL;) {
+
+ if (dvs[remI] != rem[remI]) {
+ cmp = dvs[remI] > rem[remI] ? 1 : -1;
+ break;
+ }
+ }
+ }
+
+ // If divisor < remainder, subtract divisor from remainder.
+ if (cmp < 0) {
+
+ // Remainder can't be more than 1 digit longer than divisor.
+ // Equalise lengths using divisor with extra leading zero?
+ for (dvsT = remL == dvsL ? dvs : dvsZ; remL;) {
+
+ if (rem[--remL] < dvsT[remL]) {
+ remI = remL;
+
+ for (; remI && !rem[--remI]; rem[remI] = 9) {
+ }
+ --rem[remI];
+ rem[remL] += 10;
+ }
+ rem[remL] -= dvsT[remL];
+ }
+ for (; !rem[0]; rem.shift()) {
+ }
+ } else {
+ break;
+ }
+ }
+
+ // Add the 'next' digit to the result array.
+ qc[qi++] = cmp ? next : ++next;
+
+ // Update the remainder.
+ if (rem[0] && cmp) {
+ rem[remL] = dvd[dvdI] || 0;
+ } else {
+ rem = [ dvd[dvdI] ];
+ }
+
+ } while ((dvdI++ < dvdL || rem[0] !== u) && s--);
+
+ // Leading zero? Do not remove if result is simply zero (qi == 1).
+ if (!qc[0] && qi != 1) {
+
+ // There can't be more than one zero.
+ qc.shift();
+ q.e--;
+ }
+
+ // Round?
+ if (qi > digits) {
+ rnd(q, dp, Big.RM, rem[0] !== u);
+ }
+
+ return q;
+ };
+
+
+ /*
+ * Return true if the value of this Big is equal to the value of Big y,
+ * otherwise returns false.
+ */
+ P.eq = function (y) {
+ return !this.cmp(y);
+ };
+
+
+ /*
+ * Return true if the value of this Big is greater than the value of Big y,
+ * otherwise returns false.
+ */
+ P.gt = function (y) {
+ return this.cmp(y) > 0;
+ };
+
+
+ /*
+ * Return true if the value of this Big is greater than or equal to the
+ * value of Big y, otherwise returns false.
+ */
+ P.gte = function (y) {
+ return this.cmp(y) > -1;
+ };
+
+
+ /*
+ * Return true if the value of this Big is less than the value of Big y,
+ * otherwise returns false.
+ */
+ P.lt = function (y) {
+ return this.cmp(y) < 0;
+ };
+
+
+ /*
+ * Return true if the value of this Big is less than or equal to the value
+ * of Big y, otherwise returns false.
+ */
+ P.lte = function (y) {
+ return this.cmp(y) < 1;
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big minus the value
+ * of Big y.
+ */
+ P.sub = P.minus = function (y) {
+ var i, j, t, xLTy,
+ x = this,
+ Big = x.constructor,
+ a = x.s,
+ b = (y = new Big(y)).s;
+
+ // Signs differ?
+ if (a != b) {
+ y.s = -b;
+ return x.plus(y);
+ }
+
+ var xc = x.c.slice(),
+ xe = x.e,
+ yc = y.c,
+ ye = y.e;
+
+ // Either zero?
+ if (!xc[0] || !yc[0]) {
+
+ // y is non-zero? x is non-zero? Or both are zero.
+ return yc[0] ? (y.s = -b, y) : new Big(xc[0] ? x : 0);
+ }
+
+ // Determine which is the bigger number.
+ // Prepend zeros to equalise exponents.
+ if (a = xe - ye) {
+
+ if (xLTy = a < 0) {
+ a = -a;
+ t = xc;
+ } else {
+ ye = xe;
+ t = yc;
+ }
+
+ t.reverse();
+ for (b = a; b--; t.push(0)) {
+ }
+ t.reverse();
+ } else {
+
+ // Exponents equal. Check digit by digit.
+ j = ((xLTy = xc.length < yc.length) ? xc : yc).length;
+
+ for (a = b = 0; b < j; b++) {
+
+ if (xc[b] != yc[b]) {
+ xLTy = xc[b] < yc[b];
+ break;
+ }
+ }
+ }
+
+ // x < y? Point xc to the array of the bigger number.
+ if (xLTy) {
+ t = xc;
+ xc = yc;
+ yc = t;
+ y.s = -y.s;
+ }
+
+ /*
+ * Append zeros to xc if shorter. No need to add zeros to yc if shorter
+ * as subtraction only needs to start at yc.length.
+ */
+ if (( b = (j = yc.length) - (i = xc.length) ) > 0) {
+
+ for (; b--; xc[i++] = 0) {
+ }
+ }
+
+ // Subtract yc from xc.
+ for (b = i; j > a;){
+
+ if (xc[--j] < yc[j]) {
+
+ for (i = j; i && !xc[--i]; xc[i] = 9) {
+ }
+ --xc[i];
+ xc[j] += 10;
+ }
+ xc[j] -= yc[j];
+ }
+
+ // Remove trailing zeros.
+ for (; xc[--b] === 0; xc.pop()) {
+ }
+
+ // Remove leading zeros and adjust exponent accordingly.
+ for (; xc[0] === 0;) {
+ xc.shift();
+ --ye;
+ }
+
+ if (!xc[0]) {
+
+ // n - n = +0
+ y.s = 1;
+
+ // Result must be zero.
+ xc = [ye = 0];
+ }
+
+ y.c = xc;
+ y.e = ye;
+
+ return y;
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big modulo the
+ * value of Big y.
+ */
+ P.mod = function (y) {
+ var yGTx,
+ x = this,
+ Big = x.constructor,
+ a = x.s,
+ b = (y = new Big(y)).s;
+
+ if (!y.c[0]) {
+ throwErr(NaN);
+ }
+
+ x.s = y.s = 1;
+ yGTx = y.cmp(x) == 1;
+ x.s = a;
+ y.s = b;
+
+ if (yGTx) {
+ return new Big(x);
+ }
+
+ a = Big.DP;
+ b = Big.RM;
+ Big.DP = Big.RM = 0;
+ x = x.div(y);
+ Big.DP = a;
+ Big.RM = b;
+
+ return this.minus( x.times(y) );
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big plus the value
+ * of Big y.
+ */
+ P.add = P.plus = function (y) {
+ var t,
+ x = this,
+ Big = x.constructor,
+ a = x.s,
+ b = (y = new Big(y)).s;
+
+ // Signs differ?
+ if (a != b) {
+ y.s = -b;
+ return x.minus(y);
+ }
+
+ var xe = x.e,
+ xc = x.c,
+ ye = y.e,
+ yc = y.c;
+
+ // Either zero?
+ if (!xc[0] || !yc[0]) {
+
+ // y is non-zero? x is non-zero? Or both are zero.
+ return yc[0] ? y : new Big(xc[0] ? x : a * 0);
+ }
+ xc = xc.slice();
+
+ // Prepend zeros to equalise exponents.
+ // Note: Faster to use reverse then do unshifts.
+ if (a = xe - ye) {
+
+ if (a > 0) {
+ ye = xe;
+ t = yc;
+ } else {
+ a = -a;
+ t = xc;
+ }
+
+ t.reverse();
+ for (; a--; t.push(0)) {
+ }
+ t.reverse();
+ }
+
+ // Point xc to the longer array.
+ if (xc.length - yc.length < 0) {
+ t = yc;
+ yc = xc;
+ xc = t;
+ }
+ a = yc.length;
+
+ /*
+ * Only start adding at yc.length - 1 as the further digits of xc can be
+ * left as they are.
+ */
+ for (b = 0; a;) {
+ b = (xc[--a] = xc[a] + yc[a] + b) / 10 | 0;
+ xc[a] %= 10;
+ }
+
+ // No need to check for zero, as +x + +y != 0 && -x + -y != 0
+
+ if (b) {
+ xc.unshift(b);
+ ++ye;
+ }
+
+ // Remove trailing zeros.
+ for (a = xc.length; xc[--a] === 0; xc.pop()) {
+ }
+
+ y.c = xc;
+ y.e = ye;
+
+ return y;
+ };
+
+
+ /*
+ * Return a Big whose value is the value of this Big raised to the power n.
+ * If n is negative, round, if necessary, to a maximum of Big.DP decimal
+ * places using rounding mode Big.RM.
+ *
+ * n {number} Integer, -MAX_POWER to MAX_POWER inclusive.
+ */
+ P.pow = function (n) {
+ var x = this,
+ one = new x.constructor(1),
+ y = one,
+ isNeg = n < 0;
+
+ if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) {
+ throwErr('!pow!');
+ }
+
+ n = isNeg ? -n : n;
+
+ for (;;) {
+
+ if (n & 1) {
+ y = y.times(x);
+ }
+ n >>= 1;
+
+ if (!n) {
+ break;
+ }
+ x = x.times(x);
+ }
+
+ return isNeg ? one.div(y) : y;
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big rounded to a
+ * maximum of dp decimal places using rounding mode rm.
+ * If dp is not specified, round to 0 decimal places.
+ * If rm is not specified, use Big.RM.
+ *
+ * [dp] {number} Integer, 0 to MAX_DP inclusive.
+ * [rm] 0, 1, 2 or 3 (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_UP)
+ */
+ P.round = function (dp, rm) {
+ var x = this,
+ Big = x.constructor;
+
+ if (dp == null) {
+ dp = 0;
+ } else if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
+ throwErr('!round!');
+ }
+ rnd(x = new Big(x), dp, rm == null ? Big.RM : rm);
+
+ return x;
+ };
+
+
+ /*
+ * Return a new Big whose value is the square root of the value of this Big,
+ * rounded, if necessary, to a maximum of Big.DP decimal places using
+ * rounding mode Big.RM.
+ */
+ P.sqrt = function () {
+ var estimate, r, approx,
+ x = this,
+ Big = x.constructor,
+ xc = x.c,
+ i = x.s,
+ e = x.e,
+ half = new Big('0.5');
+
+ // Zero?
+ if (!xc[0]) {
+ return new Big(x);
+ }
+
+ // If negative, throw NaN.
+ if (i < 0) {
+ throwErr(NaN);
+ }
+
+ // Estimate.
+ i = Math.sqrt(x.toString());
+
+ // Math.sqrt underflow/overflow?
+ // Pass x to Math.sqrt as integer, then adjust the result exponent.
+ if (i === 0 || i === 1 / 0) {
+ estimate = xc.join('');
+
+ if (!(estimate.length + e & 1)) {
+ estimate += '0';
+ }
+
+ r = new Big( Math.sqrt(estimate).toString() );
+ r.e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
+ } else {
+ r = new Big(i.toString());
+ }
+
+ i = r.e + (Big.DP += 4);
+
+ // Newton-Raphson iteration.
+ do {
+ approx = r;
+ r = half.times( approx.plus( x.div(approx) ) );
+ } while ( approx.c.slice(0, i).join('') !==
+ r.c.slice(0, i).join('') );
+
+ rnd(r, Big.DP -= 4, Big.RM);
+
+ return r;
+ };
+
+
+ /*
+ * Return a new Big whose value is the value of this Big times the value of
+ * Big y.
+ */
+ P.mul = P.times = function (y) {
+ var c,
+ x = this,
+ Big = x.constructor,
+ xc = x.c,
+ yc = (y = new Big(y)).c,
+ a = xc.length,
+ b = yc.length,
+ i = x.e,
+ j = y.e;
+
+ // Determine sign of result.
+ y.s = x.s == y.s ? 1 : -1;
+
+ // Return signed 0 if either 0.
+ if (!xc[0] || !yc[0]) {
+ return new Big(y.s * 0);
+ }
+
+ // Initialise exponent of result as x.e + y.e.
+ y.e = i + j;
+
+ // If array xc has fewer digits than yc, swap xc and yc, and lengths.
+ if (a < b) {
+ c = xc;
+ xc = yc;
+ yc = c;
+ j = a;
+ a = b;
+ b = j;
+ }
+
+ // Initialise coefficient array of result with zeros.
+ for (c = new Array(j = a + b); j--; c[j] = 0) {
+ }
+
+ // Multiply.
+
+ // i is initially xc.length.
+ for (i = b; i--;) {
+ b = 0;
+
+ // a is yc.length.
+ for (j = a + i; j > i;) {
+
+ // Current sum of products at this digit position, plus carry.
+ b = c[j] + yc[i] * xc[j - i - 1] + b;
+ c[j--] = b % 10;
+
+ // carry
+ b = b / 10 | 0;
+ }
+ c[j] = (c[j] + b) % 10;
+ }
+
+ // Increment result exponent if there is a final carry.
+ if (b) {
+ ++y.e;
+ }
+
+ // Remove any leading zero.
+ if (!c[0]) {
+ c.shift();
+ }
+
+ // Remove trailing zeros.
+ for (i = c.length; !c[--i]; c.pop()) {
+ }
+ y.c = c;
+
+ return y;
+ };
+
+
+ /*
+ * Return a string representing the value of this Big.
+ * Return exponential notation if this Big has a positive exponent equal to
+ * or greater than Big.E_POS, or a negative exponent equal to or less than
+ * Big.E_NEG.
+ */
+ P.toString = P.valueOf = P.toJSON = function () {
+ var x = this,
+ Big = x.constructor,
+ e = x.e,
+ str = x.c.join(''),
+ strL = str.length;
+
+ // Exponential notation?
+ if (e <= Big.E_NEG || e >= Big.E_POS) {
+ str = str.charAt(0) + (strL > 1 ? '.' + str.slice(1) : '') +
+ (e < 0 ? 'e' : 'e+') + e;
+
+ // Negative exponent?
+ } else if (e < 0) {
+
+ // Prepend zeros.
+ for (; ++e; str = '0' + str) {
+ }
+ str = '0.' + str;
+
+ // Positive exponent?
+ } else if (e > 0) {
+
+ if (++e > strL) {
+
+ // Append zeros.
+ for (e -= strL; e-- ; str += '0') {
+ }
+ } else if (e < strL) {
+ str = str.slice(0, e) + '.' + str.slice(e);
+ }
+
+ // Exponent zero.
+ } else if (strL > 1) {
+ str = str.charAt(0) + '.' + str.slice(1);
+ }
+
+ // Avoid '-0'
+ return x.s < 0 && x.c[0] ? '-' + str : str;
+ };
+
+
+ /*
+ ***************************************************************************
+ * If toExponential, toFixed, toPrecision and format are not required they
+ * can safely be commented-out or deleted. No redundant code will be left.
+ * format is used only by toExponential, toFixed and toPrecision.
+ ***************************************************************************
+ */
+
+
+ /*
+ * Return a string representing the value of this Big in exponential
+ * notation to dp fixed decimal places and rounded, if necessary, using
+ * Big.RM.
+ *
+ * [dp] {number} Integer, 0 to MAX_DP inclusive.
+ */
+ P.toExponential = function (dp) {
+
+ if (dp == null) {
+ dp = this.c.length - 1;
+ } else if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
+ throwErr('!toExp!');
+ }
+
+ return format(this, dp, 1);
+ };
+
+
+ /*
+ * Return a string representing the value of this Big in normal notation
+ * to dp fixed decimal places and rounded, if necessary, using Big.RM.
+ *
+ * [dp] {number} Integer, 0 to MAX_DP inclusive.
+ */
+ P.toFixed = function (dp) {
+ var str,
+ x = this,
+ Big = x.constructor,
+ neg = Big.E_NEG,
+ pos = Big.E_POS;
+
+ // Prevent the possibility of exponential notation.
+ Big.E_NEG = -(Big.E_POS = 1 / 0);
+
+ if (dp == null) {
+ str = x.toString();
+ } else if (dp === ~~dp && dp >= 0 && dp <= MAX_DP) {
+ str = format(x, x.e + dp);
+
+ // (-0).toFixed() is '0', but (-0.1).toFixed() is '-0'.
+ // (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
+ if (x.s < 0 && x.c[0] && str.indexOf('-') < 0) {
+ //E.g. -0.5 if rounded to -0 will cause toString to omit the minus sign.
+ str = '-' + str;
+ }
+ }
+ Big.E_NEG = neg;
+ Big.E_POS = pos;
+
+ if (!str) {
+ throwErr('!toFix!');
+ }
+
+ return str;
+ };
+
+
+ /*
+ * Return a string representing the value of this Big rounded to sd
+ * significant digits using Big.RM. Use exponential notation if sd is less
+ * than the number of digits necessary to represent the integer part of the
+ * value in normal notation.
+ *
+ * sd {number} Integer, 1 to MAX_DP inclusive.
+ */
+ P.toPrecision = function (sd) {
+
+ if (sd == null) {
+ return this.toString();
+ } else if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
+ throwErr('!toPre!');
+ }
+
+ return format(this, sd - 1, 2);
+ };
+
+
+ // Export
+
+
+ Big = bigFactory();
+
+ //AMD.
+ if (typeof define === 'function' && define.amd) {
+ define(function () {
+ return Big;
+ });
+
+ // Node and other CommonJS-like environments that support module.exports.
+ } else if (typeof module !== 'undefined' && module.exports) {
+ module.exports = Big;
+
+ //Browser.
+ } else {
+ global.Big = Big;
+ }
+})(this);
diff --git a/node_modules/big.js/big.min.js b/node_modules/big.js/big.min.js
new file mode 100644
index 0000000..aeef27f
--- /dev/null
+++ b/node_modules/big.js/big.min.js
@@ -0,0 +1 @@
+/* big.js v3.1.3 https://github.com/MikeMcl/big.js/LICENCE */(function(global){"use strict";var DP=20,RM=1,MAX_DP=1e6,MAX_POWER=1e6,E_NEG=-7,E_POS=21,P={},isValid=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,Big;function bigFactory(){function Big(n){var x=this;if(!(x instanceof Big)){return n===void 0?bigFactory():new Big(n)}if(n instanceof Big){x.s=n.s;x.e=n.e;x.c=n.c.slice()}else{parse(x,n)}x.constructor=Big}Big.prototype=P;Big.DP=DP;Big.RM=RM;Big.E_NEG=E_NEG;Big.E_POS=E_POS;return Big}function format(x,dp,toE){var Big=x.constructor,i=dp-(x=new Big(x)).e,c=x.c;if(c.length>++dp){rnd(x,i,Big.RM)}if(!c[0]){++i}else if(toE){i=dp}else{c=x.c;i=x.e+i+1}for(;c.length1?c[0]+"."+c.join("").slice(1):c[0])+(i<0?"e":"e+")+i:x.toString()}function parse(x,n){var e,i,nL;if(n===0&&1/n<0){n="-0"}else if(!isValid.test(n+="")){throwErr(NaN)}x.s=n.charAt(0)=="-"?(n=n.slice(1),-1):1;if((e=n.indexOf("."))>-1){n=n.replace(".","")}if((i=n.search(/e/i))>0){if(e<0){e=i}e+=+n.slice(i+1);n=n.substring(0,i)}else if(e<0){e=n.length}for(i=0;n.charAt(i)=="0";i++){}if(i==(nL=n.length)){x.c=[x.e=0]}else{for(;n.charAt(--nL)=="0";){}x.e=e-i-1;x.c=[];for(e=0;i<=nL;x.c[e++]=+n.charAt(i++)){}}return x}function rnd(x,dp,rm,more){var u,xc=x.c,i=x.e+dp+1;if(rm===1){more=xc[i]>=5}else if(rm===2){more=xc[i]>5||xc[i]==5&&(more||i<0||xc[i+1]!==u||xc[i-1]&1)}else if(rm===3){more=more||xc[i]!==u||i<0}else{more=false;if(rm!==0){throwErr("!Big.RM!")}}if(i<1||!xc[0]){if(more){x.e=-dp;x.c=[1]}else{x.c=[x.e=0]}}else{xc.length=i--;if(more){for(;++xc[i]>9;){xc[i]=0;if(!i--){++x.e;xc.unshift(1)}}}for(i=xc.length;!xc[--i];xc.pop()){}}return x}function throwErr(message){var err=new Error(message);err.name="BigError";throw err}P.abs=function(){var x=new this.constructor(this);x.s=1;return x};P.cmp=function(y){var xNeg,x=this,xc=x.c,yc=(y=new x.constructor(y)).c,i=x.s,j=y.s,k=x.e,l=y.e;if(!xc[0]||!yc[0]){return!xc[0]?!yc[0]?0:-j:i}if(i!=j){return i}xNeg=i<0;if(k!=l){return k>l^xNeg?1:-1}i=-1;j=(k=xc.length)<(l=yc.length)?k:l;for(;++iyc[i]^xNeg?1:-1}}return k==l?0:k>l^xNeg?1:-1};P.div=function(y){var x=this,Big=x.constructor,dvd=x.c,dvs=(y=new Big(y)).c,s=x.s==y.s?1:-1,dp=Big.DP;if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!Big.DP!")}if(!dvd[0]||!dvs[0]){if(dvd[0]==dvs[0]){throwErr(NaN)}if(!dvs[0]){throwErr(s/0)}return new Big(s*0)}var dvsL,dvsT,next,cmp,remI,u,dvsZ=dvs.slice(),dvdI=dvsL=dvs.length,dvdL=dvd.length,rem=dvd.slice(0,dvsL),remL=rem.length,q=y,qc=q.c=[],qi=0,digits=dp+(q.e=x.e-y.e)+1;q.s=s;s=digits<0?0:digits;dvsZ.unshift(0);for(;remL++remL?1:-1}else{for(remI=-1,cmp=0;++remIrem[remI]?1:-1;break}}}if(cmp<0){for(dvsT=remL==dvsL?dvs:dvsZ;remL;){if(rem[--remL]digits){rnd(q,dp,Big.RM,rem[0]!==u)}return q};P.eq=function(y){return!this.cmp(y)};P.gt=function(y){return this.cmp(y)>0};P.gte=function(y){return this.cmp(y)>-1};P.lt=function(y){return this.cmp(y)<0};P.lte=function(y){return this.cmp(y)<1};P.sub=P.minus=function(y){var i,j,t,xLTy,x=this,Big=x.constructor,a=x.s,b=(y=new Big(y)).s;if(a!=b){y.s=-b;return x.plus(y)}var xc=x.c.slice(),xe=x.e,yc=y.c,ye=y.e;if(!xc[0]||!yc[0]){return yc[0]?(y.s=-b,y):new Big(xc[0]?x:0)}if(a=xe-ye){if(xLTy=a<0){a=-a;t=xc}else{ye=xe;t=yc}t.reverse();for(b=a;b--;t.push(0)){}t.reverse()}else{j=((xLTy=xc.length0){for(;b--;xc[i++]=0){}}for(b=i;j>a;){if(xc[--j]0){ye=xe;t=yc}else{a=-a;t=xc}t.reverse();for(;a--;t.push(0)){}t.reverse()}if(xc.length-yc.length<0){t=yc;yc=xc;xc=t}a=yc.length;for(b=0;a;){b=(xc[--a]=xc[a]+yc[a]+b)/10|0;xc[a]%=10}if(b){xc.unshift(b);++ye}for(a=xc.length;xc[--a]===0;xc.pop()){}y.c=xc;y.e=ye;return y};P.pow=function(n){var x=this,one=new x.constructor(1),y=one,isNeg=n<0;if(n!==~~n||n<-MAX_POWER||n>MAX_POWER){throwErr("!pow!")}n=isNeg?-n:n;for(;;){if(n&1){y=y.times(x)}n>>=1;if(!n){break}x=x.times(x)}return isNeg?one.div(y):y};P.round=function(dp,rm){var x=this,Big=x.constructor;if(dp==null){dp=0}else if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!round!")}rnd(x=new Big(x),dp,rm==null?Big.RM:rm);return x};P.sqrt=function(){var estimate,r,approx,x=this,Big=x.constructor,xc=x.c,i=x.s,e=x.e,half=new Big("0.5");if(!xc[0]){return new Big(x)}if(i<0){throwErr(NaN)}i=Math.sqrt(x.toString());if(i===0||i===1/0){estimate=xc.join("");if(!(estimate.length+e&1)){estimate+="0"}r=new Big(Math.sqrt(estimate).toString());r.e=((e+1)/2|0)-(e<0||e&1)}else{r=new Big(i.toString())}i=r.e+(Big.DP+=4);do{approx=r;r=half.times(approx.plus(x.div(approx)))}while(approx.c.slice(0,i).join("")!==r.c.slice(0,i).join(""));rnd(r,Big.DP-=4,Big.RM);return r};P.mul=P.times=function(y){var c,x=this,Big=x.constructor,xc=x.c,yc=(y=new Big(y)).c,a=xc.length,b=yc.length,i=x.e,j=y.e;y.s=x.s==y.s?1:-1;if(!xc[0]||!yc[0]){return new Big(y.s*0)}y.e=i+j;if(ai;){b=c[j]+yc[i]*xc[j-i-1]+b;c[j--]=b%10;b=b/10|0}c[j]=(c[j]+b)%10}if(b){++y.e}if(!c[0]){c.shift()}for(i=c.length;!c[--i];c.pop()){}y.c=c;return y};P.toString=P.valueOf=P.toJSON=function(){var x=this,Big=x.constructor,e=x.e,str=x.c.join(""),strL=str.length;if(e<=Big.E_NEG||e>=Big.E_POS){str=str.charAt(0)+(strL>1?"."+str.slice(1):"")+(e<0?"e":"e+")+e}else if(e<0){for(;++e;str="0"+str){}str="0."+str}else if(e>0){if(++e>strL){for(e-=strL;e--;str+="0"){}}else if(e1){str=str.charAt(0)+"."+str.slice(1)}return x.s<0&&x.c[0]?"-"+str:str};P.toExponential=function(dp){if(dp==null){dp=this.c.length-1}else if(dp!==~~dp||dp<0||dp>MAX_DP){throwErr("!toExp!")}return format(this,dp,1)};P.toFixed=function(dp){var str,x=this,Big=x.constructor,neg=Big.E_NEG,pos=Big.E_POS;Big.E_NEG=-(Big.E_POS=1/0);if(dp==null){str=x.toString()}else if(dp===~~dp&&dp>=0&&dp<=MAX_DP){str=format(x,x.e+dp);if(x.s<0&&x.c[0]&&str.indexOf("-")<0){str="-"+str}}Big.E_NEG=neg;Big.E_POS=pos;if(!str){throwErr("!toFix!")}return str};P.toPrecision=function(sd){if(sd==null){return this.toString()}else if(sd!==~~sd||sd<1||sd>MAX_DP){throwErr("!toPre!")}return format(this,sd-1,2)};Big=bigFactory();if(typeof define==="function"&&define.amd){define(function(){return Big})}else if(typeof module!=="undefined"&&module.exports){module.exports=Big}else{global.Big=Big}})(this);
diff --git a/node_modules/big.js/package.json b/node_modules/big.js/package.json
new file mode 100644
index 0000000..af09fef
--- /dev/null
+++ b/node_modules/big.js/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "big.js",
+ "description": "A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic",
+ "version": "3.1.3",
+ "keywords": [
+ "arbitrary",
+ "precision",
+ "arithmetic",
+ "big",
+ "number",
+ "decimal",
+ "float",
+ "biginteger",
+ "bigdecimal",
+ "bignumber",
+ "bigint",
+ "bignum"
+ ],
+ "repository" : {
+ "type": "git",
+ "url": "https://github.com/MikeMcl/big.js.git"
+ },
+ "main": "./big",
+ "author": {
+ "name": "Michael Mclaughlin",
+ "email": "M8ch88l@gmail.com"
+ },
+ "bugs": {
+ "url": "https://github.com/MikeMcl/big.js/issues"
+ },
+ "engines": {
+ "node": "*"
+ },
+ "license": "MIT",
+ "scripts": {
+ "test": "node ./test/every-test.js",
+ "build": "uglifyjs -o ./big.min.js ./big.js"
+ },
+ "files": [
+ "big.js",
+ "big.min.js"
+ ]
+}
diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json
new file mode 100644
index 0000000..ad98e2a
--- /dev/null
+++ b/node_modules/binary-extensions/binary-extensions.json
@@ -0,0 +1,239 @@
+[
+ "3ds",
+ "3g2",
+ "3gp",
+ "7z",
+ "a",
+ "aac",
+ "adp",
+ "ai",
+ "aif",
+ "aiff",
+ "alz",
+ "ape",
+ "apk",
+ "ar",
+ "arj",
+ "asf",
+ "au",
+ "avi",
+ "bak",
+ "bh",
+ "bin",
+ "bk",
+ "bmp",
+ "btif",
+ "bz2",
+ "bzip2",
+ "cab",
+ "caf",
+ "cgm",
+ "class",
+ "cmx",
+ "cpio",
+ "cr2",
+ "csv",
+ "cur",
+ "dat",
+ "deb",
+ "dex",
+ "djvu",
+ "dll",
+ "dmg",
+ "dng",
+ "doc",
+ "docm",
+ "docx",
+ "dot",
+ "dotm",
+ "dra",
+ "DS_Store",
+ "dsk",
+ "dts",
+ "dtshd",
+ "dvb",
+ "dwg",
+ "dxf",
+ "ecelp4800",
+ "ecelp7470",
+ "ecelp9600",
+ "egg",
+ "eol",
+ "eot",
+ "epub",
+ "exe",
+ "f4v",
+ "fbs",
+ "fh",
+ "fla",
+ "flac",
+ "fli",
+ "flv",
+ "fpx",
+ "fst",
+ "fvt",
+ "g3",
+ "gif",
+ "graffle",
+ "gz",
+ "gzip",
+ "h261",
+ "h263",
+ "h264",
+ "ico",
+ "ief",
+ "img",
+ "ipa",
+ "iso",
+ "jar",
+ "jpeg",
+ "jpg",
+ "jpgv",
+ "jpm",
+ "jxr",
+ "key",
+ "ktx",
+ "lha",
+ "lvp",
+ "lz",
+ "lzh",
+ "lzma",
+ "lzo",
+ "m3u",
+ "m4a",
+ "m4v",
+ "mar",
+ "mdi",
+ "mht",
+ "mid",
+ "midi",
+ "mj2",
+ "mka",
+ "mkv",
+ "mmr",
+ "mng",
+ "mobi",
+ "mov",
+ "movie",
+ "mp3",
+ "mp4",
+ "mp4a",
+ "mpeg",
+ "mpg",
+ "mpga",
+ "mxu",
+ "nef",
+ "npx",
+ "numbers",
+ "o",
+ "oga",
+ "ogg",
+ "ogv",
+ "otf",
+ "pages",
+ "pbm",
+ "pcx",
+ "pdf",
+ "pea",
+ "pgm",
+ "pic",
+ "png",
+ "pnm",
+ "pot",
+ "potm",
+ "potx",
+ "ppa",
+ "ppam",
+ "ppm",
+ "pps",
+ "ppsm",
+ "ppsx",
+ "ppt",
+ "pptm",
+ "pptx",
+ "psd",
+ "pya",
+ "pyc",
+ "pyo",
+ "pyv",
+ "qt",
+ "rar",
+ "ras",
+ "raw",
+ "rgb",
+ "rip",
+ "rlc",
+ "rmf",
+ "rmvb",
+ "rtf",
+ "rz",
+ "s3m",
+ "s7z",
+ "scpt",
+ "sgi",
+ "shar",
+ "sil",
+ "slk",
+ "smv",
+ "so",
+ "sub",
+ "swf",
+ "tar",
+ "tbz",
+ "tbz2",
+ "tga",
+ "tgz",
+ "thmx",
+ "tif",
+ "tiff",
+ "tlz",
+ "ttc",
+ "ttf",
+ "txz",
+ "udf",
+ "uvh",
+ "uvi",
+ "uvm",
+ "uvp",
+ "uvs",
+ "uvu",
+ "viv",
+ "vob",
+ "war",
+ "wav",
+ "wax",
+ "wbmp",
+ "wdp",
+ "weba",
+ "webm",
+ "webp",
+ "whl",
+ "wim",
+ "wm",
+ "wma",
+ "wmv",
+ "wmx",
+ "woff",
+ "woff2",
+ "wvx",
+ "xbm",
+ "xif",
+ "xla",
+ "xlam",
+ "xls",
+ "xlsb",
+ "xlsm",
+ "xlsx",
+ "xlt",
+ "xltm",
+ "xltx",
+ "xm",
+ "xmind",
+ "xpi",
+ "xpm",
+ "xwd",
+ "xz",
+ "z",
+ "zip",
+ "zipx"
+]
diff --git a/node_modules/binary-extensions/license b/node_modules/binary-extensions/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/binary-extensions/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus (sindresorhus.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/binary-extensions/package.json b/node_modules/binary-extensions/package.json
new file mode 100644
index 0000000..1760b09
--- /dev/null
+++ b/node_modules/binary-extensions/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "binary-extensions",
+ "version": "1.7.0",
+ "description": "List of binary file extensions",
+ "license": "MIT",
+ "repository": "sindresorhus/binary-extensions",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "ava"
+ },
+ "main": "binary-extensions.json",
+ "files": [
+ "binary-extensions.json"
+ ],
+ "keywords": [
+ "bin",
+ "binary",
+ "ext",
+ "extensions",
+ "extension",
+ "file",
+ "json",
+ "list",
+ "array"
+ ],
+ "devDependencies": {
+ "ava": "*"
+ }
+}
diff --git a/node_modules/binary-extensions/readme.md b/node_modules/binary-extensions/readme.md
new file mode 100644
index 0000000..4f8f284
--- /dev/null
+++ b/node_modules/binary-extensions/readme.md
@@ -0,0 +1,33 @@
+# binary-extensions [![Build Status](https://travis-ci.org/sindresorhus/binary-extensions.svg?branch=master)](https://travis-ci.org/sindresorhus/binary-extensions)
+
+> List of binary file extensions
+
+The list is just a [JSON file](binary-extensions.json) and can be used wherever.
+
+
+## Install
+
+```
+$ npm install --save binary-extensions
+```
+
+
+## Usage
+
+```js
+var binaryExtensions = require('binary-extensions');
+
+console.log(binaryExtensions);
+//=> ['3ds', '3g2', ...]
+```
+
+
+## Related
+
+- [`is-binary-path`](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file
+- [`text-extensions`](https://github.com/sindresorhus/text-extensions) - List of text file extensions
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/node_modules/block-stream/LICENCE b/node_modules/block-stream/LICENCE
new file mode 100644
index 0000000..74489e2
--- /dev/null
+++ b/node_modules/block-stream/LICENCE
@@ -0,0 +1,25 @@
+Copyright (c) Isaac Z. Schlueter
+All rights reserved.
+
+The BSD License
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
diff --git a/node_modules/block-stream/LICENSE b/node_modules/block-stream/LICENSE
new file mode 100644
index 0000000..19129e3
--- /dev/null
+++ b/node_modules/block-stream/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+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/block-stream/README.md b/node_modules/block-stream/README.md
new file mode 100644
index 0000000..c16e9c4
--- /dev/null
+++ b/node_modules/block-stream/README.md
@@ -0,0 +1,14 @@
+# block-stream
+
+A stream of blocks.
+
+Write data into it, and it'll output data in buffer blocks the size you
+specify, padding with zeroes if necessary.
+
+```javascript
+var block = new BlockStream(512)
+fs.createReadStream("some-file").pipe(block)
+block.pipe(fs.createWriteStream("block-file"))
+```
+
+When `.end()` or `.flush()` is called, it'll pad the block with zeroes.
diff --git a/node_modules/block-stream/block-stream.js b/node_modules/block-stream/block-stream.js
new file mode 100644
index 0000000..008de03
--- /dev/null
+++ b/node_modules/block-stream/block-stream.js
@@ -0,0 +1,209 @@
+// write data to it, and it'll emit data in 512 byte blocks.
+// if you .end() or .flush(), it'll emit whatever it's got,
+// padded with nulls to 512 bytes.
+
+module.exports = BlockStream
+
+var Stream = require("stream").Stream
+ , inherits = require("inherits")
+ , assert = require("assert").ok
+ , debug = process.env.DEBUG ? console.error : function () {}
+
+function BlockStream (size, opt) {
+ this.writable = this.readable = true
+ this._opt = opt || {}
+ this._chunkSize = size || 512
+ this._offset = 0
+ this._buffer = []
+ this._bufferLength = 0
+ if (this._opt.nopad) this._zeroes = false
+ else {
+ this._zeroes = new Buffer(this._chunkSize)
+ for (var i = 0; i < this._chunkSize; i ++) {
+ this._zeroes[i] = 0
+ }
+ }
+}
+
+inherits(BlockStream, Stream)
+
+BlockStream.prototype.write = function (c) {
+ // debug(" BS write", c)
+ if (this._ended) throw new Error("BlockStream: write after end")
+ if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "")
+ if (c.length) {
+ this._buffer.push(c)
+ this._bufferLength += c.length
+ }
+ // debug("pushed onto buffer", this._bufferLength)
+ if (this._bufferLength >= this._chunkSize) {
+ if (this._paused) {
+ // debug(" BS paused, return false, need drain")
+ this._needDrain = true
+ return false
+ }
+ this._emitChunk()
+ }
+ return true
+}
+
+BlockStream.prototype.pause = function () {
+ // debug(" BS pausing")
+ this._paused = true
+}
+
+BlockStream.prototype.resume = function () {
+ // debug(" BS resume")
+ this._paused = false
+ return this._emitChunk()
+}
+
+BlockStream.prototype.end = function (chunk) {
+ // debug("end", chunk)
+ if (typeof chunk === "function") cb = chunk, chunk = null
+ if (chunk) this.write(chunk)
+ this._ended = true
+ this.flush()
+}
+
+BlockStream.prototype.flush = function () {
+ this._emitChunk(true)
+}
+
+BlockStream.prototype._emitChunk = function (flush) {
+ // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused)
+
+ // emit a chunk
+ if (flush && this._zeroes) {
+ // debug(" BS push zeroes", this._bufferLength)
+ // push a chunk of zeroes
+ var padBytes = (this._bufferLength % this._chunkSize)
+ if (padBytes !== 0) padBytes = this._chunkSize - padBytes
+ if (padBytes > 0) {
+ // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes))
+ this._buffer.push(this._zeroes.slice(0, padBytes))
+ this._bufferLength += padBytes
+ // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength)
+ }
+ }
+
+ if (this._emitting || this._paused) return
+ this._emitting = true
+
+ // debug(" BS entering loops")
+ var bufferIndex = 0
+ while (this._bufferLength >= this._chunkSize &&
+ (flush || !this._paused)) {
+ // debug(" BS data emission loop", this._bufferLength)
+
+ var out
+ , outOffset = 0
+ , outHas = this._chunkSize
+
+ while (outHas > 0 && (flush || !this._paused) ) {
+ // debug(" BS data inner emit loop", this._bufferLength)
+ var cur = this._buffer[bufferIndex]
+ , curHas = cur.length - this._offset
+ // debug("cur=", cur)
+ // debug("curHas=%j", curHas)
+ // If it's not big enough to fill the whole thing, then we'll need
+ // to copy multiple buffers into one. However, if it is big enough,
+ // then just slice out the part we want, to save unnecessary copying.
+ // Also, need to copy if we've already done some copying, since buffers
+ // can't be joined like cons strings.
+ if (out || curHas < outHas) {
+ out = out || new Buffer(this._chunkSize)
+ cur.copy(out, outOffset,
+ this._offset, this._offset + Math.min(curHas, outHas))
+ } else if (cur.length === outHas && this._offset === 0) {
+ // shortcut -- cur is exactly long enough, and no offset.
+ out = cur
+ } else {
+ // slice out the piece of cur that we need.
+ out = cur.slice(this._offset, this._offset + outHas)
+ }
+
+ if (curHas > outHas) {
+ // means that the current buffer couldn't be completely output
+ // update this._offset to reflect how much WAS written
+ this._offset += outHas
+ outHas = 0
+ } else {
+ // output the entire current chunk.
+ // toss it away
+ outHas -= curHas
+ outOffset += curHas
+ bufferIndex ++
+ this._offset = 0
+ }
+ }
+
+ this._bufferLength -= this._chunkSize
+ assert(out.length === this._chunkSize)
+ // debug("emitting data", out)
+ // debug(" BS emitting, paused=%j", this._paused, this._bufferLength)
+ this.emit("data", out)
+ out = null
+ }
+ // debug(" BS out of loops", this._bufferLength)
+
+ // whatever is left, it's not enough to fill up a block, or we're paused
+ this._buffer = this._buffer.slice(bufferIndex)
+ if (this._paused) {
+ // debug(" BS paused, leaving", this._bufferLength)
+ this._needsDrain = true
+ this._emitting = false
+ return
+ }
+
+ // if flushing, and not using null-padding, then need to emit the last
+ // chunk(s) sitting in the queue. We know that it's not enough to
+ // fill up a whole block, because otherwise it would have been emitted
+ // above, but there may be some offset.
+ var l = this._buffer.length
+ if (flush && !this._zeroes && l) {
+ if (l === 1) {
+ if (this._offset) {
+ this.emit("data", this._buffer[0].slice(this._offset))
+ } else {
+ this.emit("data", this._buffer[0])
+ }
+ } else {
+ var outHas = this._bufferLength
+ , out = new Buffer(outHas)
+ , outOffset = 0
+ for (var i = 0; i < l; i ++) {
+ var cur = this._buffer[i]
+ , curHas = cur.length - this._offset
+ cur.copy(out, outOffset, this._offset)
+ this._offset = 0
+ outOffset += curHas
+ this._bufferLength -= curHas
+ }
+ this.emit("data", out)
+ }
+ // truncate
+ this._buffer.length = 0
+ this._bufferLength = 0
+ this._offset = 0
+ }
+
+ // now either drained or ended
+ // debug("either draining, or ended", this._bufferLength, this._ended)
+ // means that we've flushed out all that we can so far.
+ if (this._needDrain) {
+ // debug("emitting drain", this._bufferLength)
+ this._needDrain = false
+ this.emit("drain")
+ }
+
+ if ((this._bufferLength === 0) && this._ended && !this._endEmitted) {
+ // debug("emitting end", this._bufferLength)
+ this._endEmitted = true
+ this.emit("end")
+ }
+
+ this._emitting = false
+
+ // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize)
+}
diff --git a/node_modules/block-stream/package.json b/node_modules/block-stream/package.json
new file mode 100644
index 0000000..1971213
--- /dev/null
+++ b/node_modules/block-stream/package.json
@@ -0,0 +1,27 @@
+{
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "name": "block-stream",
+ "description": "a stream of blocks",
+ "version": "0.0.9",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/isaacs/block-stream.git"
+ },
+ "engines": {
+ "node": "0.4 || >=0.5.8"
+ },
+ "main": "block-stream.js",
+ "dependencies": {
+ "inherits": "~2.0.0"
+ },
+ "devDependencies": {
+ "tap": "^5.7.1"
+ },
+ "scripts": {
+ "test": "tap test/*.js --cov"
+ },
+ "license": "ISC",
+ "files": [
+ "block-stream.js"
+ ]
+}
diff --git a/node_modules/bluebird/LICENSE b/node_modules/bluebird/LICENSE
new file mode 100644
index 0000000..4182a1e
--- /dev/null
+++ b/node_modules/bluebird/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013-2015 Petka Antonov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/node_modules/bluebird/README.md b/node_modules/bluebird/README.md
new file mode 100644
index 0000000..3772161
--- /dev/null
+++ b/node_modules/bluebird/README.md
@@ -0,0 +1,51 @@
+
+
+
+[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
+[![coverage-98%](http://img.shields.io/badge/coverage-98%-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-2016 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..b63d53a
--- /dev/null
+++ b/node_modules/bluebird/js/browser/bluebird.core.js
@@ -0,0 +1,3756 @@
+/* @preserve
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013-2015 Petka Antonov
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+/**
+ * bluebird build version 3.4.6
+ * Features enabled: core
+ * 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();
+ async.invokeLater(this._notifyUnhandledRejection, this, undefined);
+};
+
+Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
+ fireRejectionEvent("rejectionHandled",
+ unhandledRejectionHandled, undefined, this);
+};
+
+Promise.prototype._setReturnedNonUndefined = function() {
+ this._bitField = this._bitField | 268435456;
+};
+
+Promise.prototype._returnedNonUndefined = function() {
+ return (this._bitField & 268435456) !== 0;
+};
+
+Promise.prototype._notifyUnhandledRejection = function () {
+ if (this._isRejectionUnhandled()) {
+ var reason = this._settledValue();
+ this._setUnhandledRejectionIsNotified();
+ fireRejectionEvent("unhandledRejection",
+ possiblyUnhandledRejection, reason, this);
+ }
+};
+
+Promise.prototype._setUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField | 262144;
+};
+
+Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField & (~262144);
+};
+
+Promise.prototype._isUnhandledRejectionNotified = function () {
+ return (this._bitField & 262144) > 0;
+};
+
+Promise.prototype._setRejectionIsUnhandled = function () {
+ this._bitField = this._bitField | 1048576;
+};
+
+Promise.prototype._unsetRejectionIsUnhandled = function () {
+ this._bitField = this._bitField & (~1048576);
+ if (this._isUnhandledRejectionNotified()) {
+ this._unsetUnhandledRejectionIsNotified();
+ this._notifyUnhandledRejectionIsHandled();
+ }
+};
+
+Promise.prototype._isRejectionUnhandled = function () {
+ return (this._bitField & 1048576) > 0;
+};
+
+Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
+ return warn(message, shouldUseOwnTrace, promise || this);
+};
+
+Promise.onPossiblyUnhandledRejection = function (fn) {
+ var domain = getDomain();
+ possiblyUnhandledRejection =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+Promise.onUnhandledRejectionHandled = function (fn) {
+ var domain = getDomain();
+ unhandledRejectionHandled =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+var disableLongStackTraces = function() {};
+Promise.longStackTraces = function () {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ if (!config.longStackTraces && longStackTracesIsSupported()) {
+ var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
+ var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
+ config.longStackTraces = true;
+ disableLongStackTraces = function() {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ Promise.prototype._captureStackTrace = Promise_captureStackTrace;
+ Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
+ Context.deactivateLongStackTraces();
+ async.enableTrampoline();
+ config.longStackTraces = false;
+ };
+ Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
+ Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
+ Context.activateLongStackTraces();
+ async.disableTrampolineIfNecessary();
+ }
+};
+
+Promise.hasLongStackTraces = function () {
+ return config.longStackTraces && longStackTracesIsSupported();
+};
+
+var fireDomEvent = (function() {
+ try {
+ if (typeof CustomEvent === "function") {
+ var event = new CustomEvent("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new CustomEvent(name.toLowerCase(), {
+ detail: event,
+ cancelable: true
+ });
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else if (typeof Event === "function") {
+ var event = new Event("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new Event(name.toLowerCase(), {
+ cancelable: true
+ });
+ domEvent.detail = event;
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else {
+ var event = document.createEvent("CustomEvent");
+ event.initCustomEvent("testingtheevent", false, true, {});
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = document.createEvent("CustomEvent");
+ domEvent.initCustomEvent(name.toLowerCase(), false, true,
+ event);
+ return !util.global.dispatchEvent(domEvent);
+ };
+ }
+ } catch (e) {}
+ return function() {
+ return false;
+ };
+})();
+
+var fireGlobalEvent = (function() {
+ if (util.isNode) {
+ return function() {
+ return process.emit.apply(process, arguments);
+ };
+ } else {
+ if (!util.global) {
+ return function() {
+ return false;
+ };
+ }
+ return function(name) {
+ var methodName = "on" + name.toLowerCase();
+ var method = util.global[methodName];
+ if (!method) return false;
+ method.apply(util.global, [].slice.call(arguments, 1));
+ return true;
+ };
+ }
+})();
+
+function generatePromiseLifecycleEventObject(name, promise) {
+ return {promise: promise};
+}
+
+var eventToObjectGenerator = {
+ promiseCreated: generatePromiseLifecycleEventObject,
+ promiseFulfilled: generatePromiseLifecycleEventObject,
+ promiseRejected: generatePromiseLifecycleEventObject,
+ promiseResolved: generatePromiseLifecycleEventObject,
+ promiseCancelled: generatePromiseLifecycleEventObject,
+ promiseChained: function(name, promise, child) {
+ return {promise: promise, child: child};
+ },
+ warning: function(name, warning) {
+ return {warning: warning};
+ },
+ unhandledRejection: function (name, reason, promise) {
+ return {reason: reason, promise: promise};
+ },
+ rejectionHandled: generatePromiseLifecycleEventObject
+};
+
+var activeFireEvent = function (name) {
+ var globalEventFired = false;
+ try {
+ globalEventFired = fireGlobalEvent.apply(null, arguments);
+ } catch (e) {
+ async.throwLater(e);
+ globalEventFired = true;
+ }
+
+ var domEventFired = false;
+ try {
+ domEventFired = fireDomEvent(name,
+ eventToObjectGenerator[name].apply(null, arguments));
+ } catch (e) {
+ async.throwLater(e);
+ domEventFired = true;
+ }
+
+ return domEventFired || globalEventFired;
+};
+
+Promise.config = function(opts) {
+ opts = Object(opts);
+ if ("longStackTraces" in opts) {
+ if (opts.longStackTraces) {
+ Promise.longStackTraces();
+ } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
+ disableLongStackTraces();
+ }
+ }
+ if ("warnings" in opts) {
+ var warningsOption = opts.warnings;
+ config.warnings = !!warningsOption;
+ wForgottenReturn = config.warnings;
+
+ if (util.isObject(warningsOption)) {
+ if ("wForgottenReturn" in warningsOption) {
+ wForgottenReturn = !!warningsOption.wForgottenReturn;
+ }
+ }
+ }
+ if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
+ if (async.haveItemsQueued()) {
+ throw new Error(
+ "cannot enable cancellation after promises are in use");
+ }
+ Promise.prototype._clearCancellationData =
+ cancellationClearCancellationData;
+ Promise.prototype._propagateFrom = cancellationPropagateFrom;
+ Promise.prototype._onCancel = cancellationOnCancel;
+ Promise.prototype._setOnCancel = cancellationSetOnCancel;
+ Promise.prototype._attachCancellationCallback =
+ cancellationAttachCancellationCallback;
+ Promise.prototype._execute = cancellationExecute;
+ propagateFromFunction = cancellationPropagateFrom;
+ config.cancellation = true;
+ }
+ if ("monitoring" in opts) {
+ if (opts.monitoring && !config.monitoring) {
+ config.monitoring = true;
+ Promise.prototype._fireEvent = activeFireEvent;
+ } else if (!opts.monitoring && config.monitoring) {
+ config.monitoring = false;
+ Promise.prototype._fireEvent = defaultFireEvent;
+ }
+ }
+};
+
+function defaultFireEvent() { return false; }
+
+Promise.prototype._fireEvent = defaultFireEvent;
+Promise.prototype._execute = function(executor, resolve, reject) {
+ try {
+ executor(resolve, reject);
+ } catch (e) {
+ return e;
+ }
+};
+Promise.prototype._onCancel = function () {};
+Promise.prototype._setOnCancel = function (handler) { ; };
+Promise.prototype._attachCancellationCallback = function(onCancel) {
+ ;
+};
+Promise.prototype._captureStackTrace = function () {};
+Promise.prototype._attachExtraTrace = function () {};
+Promise.prototype._clearCancellationData = function() {};
+Promise.prototype._propagateFrom = function (parent, flags) {
+ ;
+ ;
+};
+
+function cancellationExecute(executor, resolve, reject) {
+ var promise = this;
+ try {
+ executor(resolve, reject, function(onCancel) {
+ if (typeof onCancel !== "function") {
+ throw new TypeError("onCancel must be a function, got: " +
+ util.toString(onCancel));
+ }
+ promise._attachCancellationCallback(onCancel);
+ });
+ } catch (e) {
+ return e;
+ }
+}
+
+function cancellationAttachCancellationCallback(onCancel) {
+ if (!this._isCancellable()) return this;
+
+ var previousOnCancel = this._onCancel();
+ if (previousOnCancel !== undefined) {
+ if (util.isArray(previousOnCancel)) {
+ previousOnCancel.push(onCancel);
+ } else {
+ this._setOnCancel([previousOnCancel, onCancel]);
+ }
+ } else {
+ this._setOnCancel(onCancel);
+ }
+}
+
+function cancellationOnCancel() {
+ return this._onCancelField;
+}
+
+function cancellationSetOnCancel(onCancel) {
+ this._onCancelField = onCancel;
+}
+
+function cancellationClearCancellationData() {
+ this._cancellationParent = undefined;
+ this._onCancelField = undefined;
+}
+
+function cancellationPropagateFrom(parent, flags) {
+ if ((flags & 1) !== 0) {
+ this._cancellationParent = parent;
+ var branchesRemainingToCancel = parent._branchesRemainingToCancel;
+ if (branchesRemainingToCancel === undefined) {
+ branchesRemainingToCancel = 0;
+ }
+ parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
+ }
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+
+function bindingPropagateFrom(parent, flags) {
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+var propagateFromFunction = bindingPropagateFrom;
+
+function boundValueFunction() {
+ var ret = this._boundTo;
+ if (ret !== undefined) {
+ if (ret instanceof Promise) {
+ if (ret.isFulfilled()) {
+ return ret.value();
+ } else {
+ return undefined;
+ }
+ }
+ }
+ return ret;
+}
+
+function longStackTracesCaptureStackTrace() {
+ this._trace = new CapturedTrace(this._peekContext());
+}
+
+function longStackTracesAttachExtraTrace(error, ignoreSelf) {
+ if (canAttachTrace(error)) {
+ var trace = this._trace;
+ if (trace !== undefined) {
+ if (ignoreSelf) trace = trace._parent;
+ }
+ if (trace !== undefined) {
+ trace.attachExtraTrace(error);
+ } else if (!error.__stackCleaned__) {
+ var parsed = parseStackAndMessage(error);
+ util.notEnumerableProp(error, "stack",
+ parsed.message + "\n" + parsed.stack.join("\n"));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+ }
+ }
+}
+
+function checkForgottenReturns(returnValue, promiseCreated, name, promise,
+ parent) {
+ if (returnValue === undefined && promiseCreated !== null &&
+ wForgottenReturn) {
+ if (parent !== undefined && parent._returnedNonUndefined()) return;
+ if ((promise._bitField & 65535) === 0) return;
+
+ if (name) name = name + " ";
+ var handlerLine = "";
+ var creatorLine = "";
+ if (promiseCreated._trace) {
+ var traceLines = promiseCreated._trace.stack.split("\n");
+ var stack = cleanStack(traceLines);
+ for (var i = stack.length - 1; i >= 0; --i) {
+ var line = stack[i];
+ if (!nodeFramePattern.test(line)) {
+ var lineMatches = line.match(parseLinePattern);
+ if (lineMatches) {
+ handlerLine = "at " + lineMatches[1] +
+ ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
+ }
+ break;
+ }
+ }
+
+ if (stack.length > 0) {
+ var firstUserLine = stack[0];
+ for (var i = 0; i < traceLines.length; ++i) {
+
+ if (traceLines[i] === firstUserLine) {
+ if (i > 0) {
+ creatorLine = "\n" + traceLines[i - 1];
+ }
+ break;
+ }
+ }
+
+ }
+ }
+ var msg = "a promise was created in a " + name +
+ "handler " + handlerLine + "but was not returned from it, " +
+ "see http://goo.gl/rRqMUw" +
+ creatorLine;
+ promise._warn(msg, true, promiseCreated);
+ }
+}
+
+function deprecated(name, replacement) {
+ var message = name +
+ " is deprecated and will be removed in a future version.";
+ if (replacement) message += " Use " + replacement + " instead.";
+ return warn(message);
+}
+
+function warn(message, shouldUseOwnTrace, promise) {
+ if (!config.warnings) return;
+ var warning = new Warning(message);
+ var ctx;
+ if (shouldUseOwnTrace) {
+ promise._attachExtraTrace(warning);
+ } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
+ ctx.attachExtraTrace(warning);
+ } else {
+ var parsed = parseStackAndMessage(warning);
+ warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
+ }
+
+ if (!activeFireEvent("warning", warning)) {
+ formatAndLogError(warning, "", true);
+ }
+}
+
+function reconstructStack(message, stacks) {
+ for (var i = 0; i < stacks.length - 1; ++i) {
+ stacks[i].push("From previous event:");
+ stacks[i] = stacks[i].join("\n");
+ }
+ if (i < stacks.length) {
+ stacks[i] = stacks[i].join("\n");
+ }
+ return message + "\n" + stacks.join("\n");
+}
+
+function removeDuplicateOrEmptyJumps(stacks) {
+ for (var i = 0; i < stacks.length; ++i) {
+ if (stacks[i].length === 0 ||
+ ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
+ stacks.splice(i, 1);
+ i--;
+ }
+ }
+}
+
+function removeCommonRoots(stacks) {
+ var current = stacks[0];
+ for (var i = 1; i < stacks.length; ++i) {
+ var prev = stacks[i];
+ var currentLastIndex = current.length - 1;
+ var currentLastLine = current[currentLastIndex];
+ var commonRootMeetPoint = -1;
+
+ for (var j = prev.length - 1; j >= 0; --j) {
+ if (prev[j] === currentLastLine) {
+ commonRootMeetPoint = j;
+ break;
+ }
+ }
+
+ for (var j = commonRootMeetPoint; j >= 0; --j) {
+ var line = prev[j];
+ if (current[currentLastIndex] === line) {
+ current.pop();
+ currentLastIndex--;
+ } else {
+ break;
+ }
+ }
+ current = prev;
+ }
+}
+
+function cleanStack(stack) {
+ var ret = [];
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ var isTraceLine = " (No stack trace)" === line ||
+ stackFramePattern.test(line);
+ var isInternalFrame = isTraceLine && shouldIgnore(line);
+ if (isTraceLine && !isInternalFrame) {
+ if (indentStackFrames && line.charAt(0) !== " ") {
+ line = " " + line;
+ }
+ ret.push(line);
+ }
+ }
+ return ret;
+}
+
+function stackFramesAsArray(error) {
+ var stack = error.stack.replace(/\s+$/g, "").split("\n");
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ if (" (No stack trace)" === line || stackFramePattern.test(line)) {
+ break;
+ }
+ }
+ if (i > 0) {
+ stack = stack.slice(i);
+ }
+ return stack;
+}
+
+function parseStackAndMessage(error) {
+ var stack = error.stack;
+ var message = error.toString();
+ stack = typeof stack === "string" && stack.length > 0
+ ? stackFramesAsArray(error) : [" (No stack trace)"];
+ return {
+ message: message,
+ stack: cleanStack(stack)
+ };
+}
+
+function formatAndLogError(error, title, isSoft) {
+ if (typeof console !== "undefined") {
+ var message;
+ if (util.isObject(error)) {
+ var stack = error.stack;
+ message = title + formatStack(stack, error);
+ } else {
+ message = title + String(error);
+ }
+ if (typeof printWarning === "function") {
+ printWarning(message, isSoft);
+ } else if (typeof console.log === "function" ||
+ typeof console.log === "object") {
+ console.log(message);
+ }
+ }
+}
+
+function fireRejectionEvent(name, localHandler, reason, promise) {
+ var localEventFired = false;
+ try {
+ if (typeof localHandler === "function") {
+ localEventFired = true;
+ if (name === "rejectionHandled") {
+ localHandler(promise);
+ } else {
+ localHandler(reason, promise);
+ }
+ }
+ } catch (e) {
+ async.throwLater(e);
+ }
+
+ if (name === "unhandledRejection") {
+ if (!activeFireEvent(name, reason, promise) && !localEventFired) {
+ formatAndLogError(reason, "Unhandled rejection ");
+ }
+ } else {
+ activeFireEvent(name, promise);
+ }
+}
+
+function formatNonError(obj) {
+ var str;
+ if (typeof obj === "function") {
+ str = "[function " +
+ (obj.name || "anonymous") +
+ "]";
+ } else {
+ str = obj && typeof obj.toString === "function"
+ ? obj.toString() : util.toString(obj);
+ var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
+ if (ruselessToString.test(str)) {
+ try {
+ var newStr = JSON.stringify(obj);
+ str = newStr;
+ }
+ catch(e) {
+
+ }
+ }
+ if (str.length === 0) {
+ str = "(empty array)";
+ }
+ }
+ return ("(<" + snip(str) + ">, no stack trace)");
+}
+
+function snip(str) {
+ var maxChars = 41;
+ if (str.length < maxChars) {
+ return str;
+ }
+ return str.substr(0, maxChars - 3) + "...";
+}
+
+function longStackTracesIsSupported() {
+ return typeof captureStackTrace === "function";
+}
+
+var shouldIgnore = function() { return false; };
+var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
+function parseLineInfo(line) {
+ var matches = line.match(parseLineInfoRegex);
+ if (matches) {
+ return {
+ fileName: matches[1],
+ line: parseInt(matches[2], 10)
+ };
+ }
+}
+
+function setBounds(firstLineError, lastLineError) {
+ if (!longStackTracesIsSupported()) return;
+ var firstStackLines = firstLineError.stack.split("\n");
+ var lastStackLines = lastLineError.stack.split("\n");
+ var firstIndex = -1;
+ var lastIndex = -1;
+ var firstFileName;
+ var lastFileName;
+ for (var i = 0; i < firstStackLines.length; ++i) {
+ var result = parseLineInfo(firstStackLines[i]);
+ if (result) {
+ firstFileName = result.fileName;
+ firstIndex = result.line;
+ break;
+ }
+ }
+ for (var i = 0; i < lastStackLines.length; ++i) {
+ var result = parseLineInfo(lastStackLines[i]);
+ if (result) {
+ lastFileName = result.fileName;
+ lastIndex = result.line;
+ break;
+ }
+ }
+ if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
+ firstFileName !== lastFileName || firstIndex >= lastIndex) {
+ return;
+ }
+
+ shouldIgnore = function(line) {
+ if (bluebirdFramePattern.test(line)) return true;
+ var info = parseLineInfo(line);
+ if (info) {
+ if (info.fileName === firstFileName &&
+ (firstIndex <= info.line && info.line <= lastIndex)) {
+ return true;
+ }
+ }
+ return false;
+ };
+}
+
+function CapturedTrace(parent) {
+ this._parent = parent;
+ this._promisesCreated = 0;
+ var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
+ captureStackTrace(this, CapturedTrace);
+ if (length > 32) this.uncycle();
+}
+util.inherits(CapturedTrace, Error);
+Context.CapturedTrace = CapturedTrace;
+
+CapturedTrace.prototype.uncycle = function() {
+ var length = this._length;
+ if (length < 2) return;
+ var nodes = [];
+ var stackToIndex = {};
+
+ for (var i = 0, node = this; node !== undefined; ++i) {
+ nodes.push(node);
+ node = node._parent;
+ }
+ length = this._length = i;
+ for (var i = length - 1; i >= 0; --i) {
+ var stack = nodes[i].stack;
+ if (stackToIndex[stack] === undefined) {
+ stackToIndex[stack] = i;
+ }
+ }
+ for (var i = 0; i < length; ++i) {
+ var currentStack = nodes[i].stack;
+ var index = stackToIndex[currentStack];
+ if (index !== undefined && index !== i) {
+ if (index > 0) {
+ nodes[index - 1]._parent = undefined;
+ nodes[index - 1]._length = 1;
+ }
+ nodes[i]._parent = undefined;
+ nodes[i]._length = 1;
+ var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
+
+ if (index < length - 1) {
+ cycleEdgeNode._parent = nodes[index + 1];
+ cycleEdgeNode._parent.uncycle();
+ cycleEdgeNode._length =
+ cycleEdgeNode._parent._length + 1;
+ } else {
+ cycleEdgeNode._parent = undefined;
+ cycleEdgeNode._length = 1;
+ }
+ var currentChildLength = cycleEdgeNode._length + 1;
+ for (var j = i - 2; j >= 0; --j) {
+ nodes[j]._length = currentChildLength;
+ currentChildLength++;
+ }
+ return;
+ }
+ }
+};
+
+CapturedTrace.prototype.attachExtraTrace = function(error) {
+ if (error.__stackCleaned__) return;
+ this.uncycle();
+ var parsed = parseStackAndMessage(error);
+ var message = parsed.message;
+ var stacks = [parsed.stack];
+
+ var trace = this;
+ while (trace !== undefined) {
+ stacks.push(cleanStack(trace.stack.split("\n")));
+ trace = trace._parent;
+ }
+ removeCommonRoots(stacks);
+ removeDuplicateOrEmptyJumps(stacks);
+ util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+};
+
+var captureStackTrace = (function stackDetection() {
+ var v8stackFramePattern = /^\s*at\s*/;
+ var v8stackFormatter = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if (error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ if (typeof Error.stackTraceLimit === "number" &&
+ typeof Error.captureStackTrace === "function") {
+ Error.stackTraceLimit += 6;
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ var captureStackTrace = Error.captureStackTrace;
+
+ shouldIgnore = function(line) {
+ return bluebirdFramePattern.test(line);
+ };
+ return function(receiver, ignoreUntil) {
+ Error.stackTraceLimit += 6;
+ captureStackTrace(receiver, ignoreUntil);
+ Error.stackTraceLimit -= 6;
+ };
+ }
+ var err = new Error();
+
+ if (typeof err.stack === "string" &&
+ err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
+ stackFramePattern = /@/;
+ formatStack = v8stackFormatter;
+ indentStackFrames = true;
+ return function captureStackTrace(o) {
+ o.stack = new Error().stack;
+ };
+ }
+
+ var hasStackAfterThrow;
+ try { throw new Error(); }
+ catch(e) {
+ hasStackAfterThrow = ("stack" in e);
+ }
+ if (!("stack" in err) && hasStackAfterThrow &&
+ typeof Error.stackTraceLimit === "number") {
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ return function captureStackTrace(o) {
+ Error.stackTraceLimit += 6;
+ try { throw new Error(); }
+ catch(e) { o.stack = e.stack; }
+ Error.stackTraceLimit -= 6;
+ };
+ }
+
+ formatStack = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if ((typeof error === "object" ||
+ typeof error === "function") &&
+ error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ return null;
+
+})([]);
+
+if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
+ printWarning = function (message) {
+ console.warn(message);
+ };
+ if (util.isNode && process.stderr.isTTY) {
+ printWarning = function(message, isSoft) {
+ var color = isSoft ? "\u001b[33m" : "\u001b[31m";
+ console.warn(color + message + "\u001b[0m\n");
+ };
+ } else if (!util.isNode && typeof (new Error().stack) === "string") {
+ printWarning = function(message, isSoft) {
+ console.warn("%c" + message,
+ isSoft ? "color: darkorange" : "color: red");
+ };
+ }
+}
+
+var config = {
+ warnings: warnings,
+ longStackTraces: false,
+ cancellation: false,
+ monitoring: false
+};
+
+if (longStackTraces) Promise.longStackTraces();
+
+return {
+ longStackTraces: function() {
+ return config.longStackTraces;
+ },
+ warnings: function() {
+ return config.warnings;
+ },
+ cancellation: function() {
+ return config.cancellation;
+ },
+ monitoring: function() {
+ return config.monitoring;
+ },
+ propagateFromFunction: function() {
+ return propagateFromFunction;
+ },
+ boundValueFunction: function() {
+ return boundValueFunction;
+ },
+ checkForgottenReturns: checkForgottenReturns,
+ setBounds: setBounds,
+ warn: warn,
+ deprecated: deprecated,
+ CapturedTrace: CapturedTrace,
+ fireDomEvent: fireDomEvent,
+ fireGlobalEvent: fireGlobalEvent
+};
+};
+
+},{"./errors":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) {
+var util = _dereq_("./util");
+var CancellationError = Promise.CancellationError;
+var errorObj = util.errorObj;
+
+function PassThroughHandlerContext(promise, type, handler) {
+ this.promise = promise;
+ this.type = type;
+ this.handler = handler;
+ this.called = false;
+ this.cancelPromise = null;
+}
+
+PassThroughHandlerContext.prototype.isFinallyHandler = function() {
+ return this.type === 0;
+};
+
+function FinallyHandlerCancelReaction(finallyHandler) {
+ this.finallyHandler = finallyHandler;
+}
+
+FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
+ checkCancel(this.finallyHandler);
+};
+
+function checkCancel(ctx, reason) {
+ if (ctx.cancelPromise != null) {
+ if (arguments.length > 1) {
+ ctx.cancelPromise._reject(reason);
+ } else {
+ ctx.cancelPromise._cancel();
+ }
+ ctx.cancelPromise = null;
+ return true;
+ }
+ return false;
+}
+
+function succeed() {
+ return finallyHandler.call(this, this.promise._target()._settledValue());
+}
+function fail(reason) {
+ if (checkCancel(this, reason)) return;
+ errorObj.e = reason;
+ return errorObj;
+}
+function finallyHandler(reasonOrValue) {
+ var promise = this.promise;
+ var handler = this.handler;
+
+ if (!this.called) {
+ this.called = true;
+ var ret = this.isFinallyHandler()
+ ? handler.call(promise._boundValue())
+ : handler.call(promise._boundValue(), reasonOrValue);
+ if (ret !== undefined) {
+ promise._setReturnedNonUndefined();
+ var maybePromise = tryConvertToPromise(ret, promise);
+ if (maybePromise instanceof Promise) {
+ if (this.cancelPromise != null) {
+ if (maybePromise._isCancelled()) {
+ var reason =
+ new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ errorObj.e = reason;
+ return errorObj;
+ } else if (maybePromise.isPending()) {
+ maybePromise._attachCancellationCallback(
+ new FinallyHandlerCancelReaction(this));
+ }
+ }
+ return maybePromise._then(
+ succeed, fail, undefined, this, undefined);
+ }
+ }
+ }
+
+ if (promise.isRejected()) {
+ checkCancel(this);
+ errorObj.e = reasonOrValue;
+ return errorObj;
+ } else {
+ checkCancel(this);
+ return reasonOrValue;
+ }
+}
+
+Promise.prototype._passThrough = function(handler, type, success, fail) {
+ if (typeof handler !== "function") return this.then();
+ return this._then(success,
+ fail,
+ undefined,
+ new PassThroughHandlerContext(this, type, handler),
+ undefined);
+};
+
+Promise.prototype.lastly =
+Promise.prototype["finally"] = function (handler) {
+ return this._passThrough(handler,
+ 0,
+ finallyHandler,
+ finallyHandler);
+};
+
+Promise.prototype.tap = function (handler) {
+ return this._passThrough(handler, 1, finallyHandler);
+};
+
+return PassThroughHandlerContext;
+};
+
+},{"./util":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);
+var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
+var nodebackForPromise = _dereq_("./nodeback");
+var errorObj = util.errorObj;
+var tryCatch = util.tryCatch;
+function check(self, executor) {
+ if (typeof executor !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(executor));
+ }
+ if (self.constructor !== Promise) {
+ throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+}
+
+function Promise(executor) {
+ this._bitField = 0;
+ this._fulfillmentHandler0 = undefined;
+ this._rejectionHandler0 = undefined;
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ if (executor !== INTERNAL) {
+ check(this, executor);
+ this._resolveFromExecutor(executor);
+ }
+ this._promiseCreated();
+ this._fireEvent("promiseCreated", this);
+}
+
+Promise.prototype.toString = function () {
+ return "[object Promise]";
+};
+
+Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
+ var len = arguments.length;
+ if (len > 1) {
+ var catchInstances = new Array(len - 1),
+ j = 0, i;
+ for (i = 0; i < len - 1; ++i) {
+ var item = arguments[i];
+ if (util.isObject(item)) {
+ catchInstances[j++] = item;
+ } else {
+ return apiRejection("expecting an object but got " +
+ "A catch statement predicate " + util.classString(item));
+ }
+ }
+ catchInstances.length = j;
+ fn = arguments[i];
+ return this.then(undefined, catchFilter(catchInstances, fn, this));
+ }
+ return this.then(undefined, fn);
+};
+
+Promise.prototype.reflect = function () {
+ return this._then(reflectHandler,
+ reflectHandler, undefined, this, undefined);
+};
+
+Promise.prototype.then = function (didFulfill, didReject) {
+ if (debug.warnings() && arguments.length > 0 &&
+ typeof didFulfill !== "function" &&
+ typeof didReject !== "function") {
+ var msg = ".then() only accepts functions but was passed: " +
+ util.classString(didFulfill);
+ if (arguments.length > 1) {
+ msg += ", " + util.classString(didReject);
+ }
+ this._warn(msg);
+ }
+ return this._then(didFulfill, didReject, undefined, undefined, undefined);
+};
+
+Promise.prototype.done = function (didFulfill, didReject) {
+ var promise =
+ this._then(didFulfill, didReject, undefined, undefined, undefined);
+ promise._setIsFinal();
+};
+
+Promise.prototype.spread = function (fn) {
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ return this.all()._then(fn, undefined, undefined, APPLY, undefined);
+};
+
+Promise.prototype.toJSON = function () {
+ var ret = {
+ isFulfilled: false,
+ isRejected: false,
+ fulfillmentValue: undefined,
+ rejectionReason: undefined
+ };
+ if (this.isFulfilled()) {
+ ret.fulfillmentValue = this.value();
+ ret.isFulfilled = true;
+ } else if (this.isRejected()) {
+ ret.rejectionReason = this.reason();
+ ret.isRejected = true;
+ }
+ return ret;
+};
+
+Promise.prototype.all = function () {
+ if (arguments.length > 0) {
+ this._warn(".all() was passed arguments but it does not take any");
+ }
+ return new PromiseArray(this).promise();
+};
+
+Promise.prototype.error = function (fn) {
+ return this.caught(util.originatesFromRejection, fn);
+};
+
+Promise.getNewLibraryCopy = module.exports;
+
+Promise.is = function (val) {
+ return val instanceof Promise;
+};
+
+Promise.fromNode = Promise.fromCallback = function(fn) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
+ : false;
+ var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
+ if (result === errorObj) {
+ ret._rejectCallback(result.e, true);
+ }
+ if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
+ return ret;
+};
+
+Promise.all = function (promises) {
+ return new PromiseArray(promises).promise();
+};
+
+Promise.cast = function (obj) {
+ var ret = tryConvertToPromise(obj);
+ if (!(ret instanceof Promise)) {
+ ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._setFulfilled();
+ ret._rejectionHandler0 = obj;
+ }
+ return ret;
+};
+
+Promise.resolve = Promise.fulfilled = Promise.cast;
+
+Promise.reject = Promise.rejected = function (reason) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._rejectCallback(reason, true);
+ return ret;
+};
+
+Promise.setScheduler = function(fn) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ return async.setScheduler(fn);
+};
+
+Promise.prototype._then = function (
+ didFulfill,
+ didReject,
+ _, receiver,
+ internalData
+) {
+ var haveInternalData = internalData !== undefined;
+ var promise = haveInternalData ? internalData : new Promise(INTERNAL);
+ var target = this._target();
+ var bitField = target._bitField;
+
+ if (!haveInternalData) {
+ promise._propagateFrom(this, 3);
+ promise._captureStackTrace();
+ if (receiver === undefined &&
+ ((this._bitField & 2097152) !== 0)) {
+ if (!((bitField & 50397184) === 0)) {
+ receiver = this._boundValue();
+ } else {
+ receiver = target === this ? undefined : this._boundTo;
+ }
+ }
+ this._fireEvent("promiseChained", this, promise);
+ }
+
+ var domain = getDomain();
+ if (!((bitField & 50397184) === 0)) {
+ var handler, value, settler = target._settlePromiseCtx;
+ if (((bitField & 33554432) !== 0)) {
+ value = target._rejectionHandler0;
+ handler = didFulfill;
+ } else if (((bitField & 16777216) !== 0)) {
+ value = target._fulfillmentHandler0;
+ handler = didReject;
+ target._unsetRejectionIsUnhandled();
+ } else {
+ settler = target._settlePromiseLateCancellationObserver;
+ value = new CancellationError("late cancellation observer");
+ target._attachExtraTrace(value);
+ handler = didReject;
+ }
+
+ async.invoke(settler, target, {
+ handler: domain === null ? handler
+ : (typeof handler === "function" &&
+ util.domainBind(domain, handler)),
+ promise: promise,
+ receiver: receiver,
+ value: value
+ });
+ } else {
+ target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
+ }
+
+ return promise;
+};
+
+Promise.prototype._length = function () {
+ return this._bitField & 65535;
+};
+
+Promise.prototype._isFateSealed = function () {
+ return (this._bitField & 117506048) !== 0;
+};
+
+Promise.prototype._isFollowing = function () {
+ return (this._bitField & 67108864) === 67108864;
+};
+
+Promise.prototype._setLength = function (len) {
+ this._bitField = (this._bitField & -65536) |
+ (len & 65535);
+};
+
+Promise.prototype._setFulfilled = function () {
+ this._bitField = this._bitField | 33554432;
+ this._fireEvent("promiseFulfilled", this);
+};
+
+Promise.prototype._setRejected = function () {
+ this._bitField = this._bitField | 16777216;
+ this._fireEvent("promiseRejected", this);
+};
+
+Promise.prototype._setFollowing = function () {
+ this._bitField = this._bitField | 67108864;
+ this._fireEvent("promiseResolved", this);
+};
+
+Promise.prototype._setIsFinal = function () {
+ this._bitField = this._bitField | 4194304;
+};
+
+Promise.prototype._isFinal = function () {
+ return (this._bitField & 4194304) > 0;
+};
+
+Promise.prototype._unsetCancelled = function() {
+ this._bitField = this._bitField & (~65536);
+};
+
+Promise.prototype._setCancelled = function() {
+ this._bitField = this._bitField | 65536;
+ this._fireEvent("promiseCancelled", this);
+};
+
+Promise.prototype._setWillBeCancelled = function() {
+ this._bitField = this._bitField | 8388608;
+};
+
+Promise.prototype._setAsyncGuaranteed = function() {
+ if (async.hasCustomScheduler()) return;
+ this._bitField = this._bitField | 134217728;
+};
+
+Promise.prototype._receiverAt = function (index) {
+ var ret = index === 0 ? this._receiver0 : this[
+ index * 4 - 4 + 3];
+ if (ret === UNDEFINED_BINDING) {
+ return undefined;
+ } else if (ret === undefined && this._isBound()) {
+ return this._boundValue();
+ }
+ return ret;
+};
+
+Promise.prototype._promiseAt = function (index) {
+ return this[
+ index * 4 - 4 + 2];
+};
+
+Promise.prototype._fulfillmentHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 0];
+};
+
+Promise.prototype._rejectionHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 1];
+};
+
+Promise.prototype._boundValue = function() {};
+
+Promise.prototype._migrateCallback0 = function (follower) {
+ var bitField = follower._bitField;
+ var fulfill = follower._fulfillmentHandler0;
+ var reject = follower._rejectionHandler0;
+ var promise = follower._promise0;
+ var receiver = follower._receiverAt(0);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._migrateCallbackAt = function (follower, index) {
+ var fulfill = follower._fulfillmentHandlerAt(index);
+ var reject = follower._rejectionHandlerAt(index);
+ var promise = follower._promiseAt(index);
+ var receiver = follower._receiverAt(index);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._addCallbacks = function (
+ fulfill,
+ reject,
+ promise,
+ receiver,
+ domain
+) {
+ var index = this._length();
+
+ if (index >= 65535 - 4) {
+ index = 0;
+ this._setLength(0);
+ }
+
+ if (index === 0) {
+ this._promise0 = promise;
+ this._receiver0 = receiver;
+ if (typeof fulfill === "function") {
+ this._fulfillmentHandler0 =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this._rejectionHandler0 =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ } else {
+ var base = index * 4 - 4;
+ this[base + 2] = promise;
+ this[base + 3] = receiver;
+ if (typeof fulfill === "function") {
+ this[base + 0] =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this[base + 1] =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ }
+ this._setLength(index + 1);
+ return index;
+};
+
+Promise.prototype._proxy = function (proxyable, arg) {
+ this._addCallbacks(undefined, undefined, arg, proxyable, null);
+};
+
+Promise.prototype._resolveCallback = function(value, shouldBind) {
+ if (((this._bitField & 117506048) !== 0)) return;
+ if (value === this)
+ return this._rejectCallback(makeSelfResolutionError(), false);
+ var maybePromise = tryConvertToPromise(value, this);
+ if (!(maybePromise instanceof Promise)) return this._fulfill(value);
+
+ if (shouldBind) this._propagateFrom(maybePromise, 2);
+
+ var promise = maybePromise._target();
+
+ if (promise === this) {
+ this._reject(makeSelfResolutionError());
+ return;
+ }
+
+ var bitField = promise._bitField;
+ if (((bitField & 50397184) === 0)) {
+ var len = this._length();
+ if (len > 0) promise._migrateCallback0(this);
+ for (var i = 1; i < len; ++i) {
+ promise._migrateCallbackAt(this, i);
+ }
+ this._setFollowing();
+ this._setLength(0);
+ this._setFollowee(promise);
+ } else if (((bitField & 33554432) !== 0)) {
+ this._fulfill(promise._value());
+ } else if (((bitField & 16777216) !== 0)) {
+ this._reject(promise._reason());
+ } else {
+ var reason = new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ this._reject(reason);
+ }
+};
+
+Promise.prototype._rejectCallback =
+function(reason, synchronous, ignoreNonErrorWarnings) {
+ var trace = util.ensureErrorObject(reason);
+ var hasStack = trace === reason;
+ if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
+ var message = "a promise was rejected with a non-error: " +
+ util.classString(reason);
+ this._warn(message, true);
+ }
+ this._attachExtraTrace(trace, synchronous ? hasStack : false);
+ this._reject(reason);
+};
+
+Promise.prototype._resolveFromExecutor = function (executor) {
+ var promise = this;
+ this._captureStackTrace();
+ this._pushContext();
+ var synchronous = true;
+ var r = this._execute(executor, function(value) {
+ promise._resolveCallback(value);
+ }, function (reason) {
+ promise._rejectCallback(reason, synchronous);
+ });
+ synchronous = false;
+ this._popContext();
+
+ if (r !== undefined) {
+ promise._rejectCallback(r, true);
+ }
+};
+
+Promise.prototype._settlePromiseFromHandler = function (
+ handler, receiver, value, promise
+) {
+ var bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+ promise._pushContext();
+ var x;
+ if (receiver === APPLY) {
+ if (!value || typeof value.length !== "number") {
+ x = errorObj;
+ x.e = new TypeError("cannot .spread() a non-array: " +
+ util.classString(value));
+ } else {
+ x = tryCatch(handler).apply(this._boundValue(), value);
+ }
+ } else {
+ x = tryCatch(handler).call(receiver, value);
+ }
+ var promiseCreated = promise._popContext();
+ bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+
+ if (x === NEXT_FILTER) {
+ promise._reject(value);
+ } else if (x === errorObj) {
+ promise._rejectCallback(x.e, false);
+ } else {
+ debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
+ promise._resolveCallback(x);
+ }
+};
+
+Promise.prototype._target = function() {
+ var ret = this;
+ while (ret._isFollowing()) ret = ret._followee();
+ return ret;
+};
+
+Promise.prototype._followee = function() {
+ return this._rejectionHandler0;
+};
+
+Promise.prototype._setFollowee = function(promise) {
+ this._rejectionHandler0 = promise;
+};
+
+Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
+ var isPromise = promise instanceof Promise;
+ var bitField = this._bitField;
+ var asyncGuaranteed = ((bitField & 134217728) !== 0);
+ if (((bitField & 65536) !== 0)) {
+ if (isPromise) promise._invokeInternalOnCancel();
+
+ if (receiver instanceof PassThroughHandlerContext &&
+ receiver.isFinallyHandler()) {
+ receiver.cancelPromise = promise;
+ if (tryCatch(handler).call(receiver, value) === errorObj) {
+ promise._reject(errorObj.e);
+ }
+ } else if (handler === reflectHandler) {
+ promise._fulfill(reflectHandler.call(receiver));
+ } else if (receiver instanceof Proxyable) {
+ receiver._promiseCancelled(promise);
+ } else if (isPromise || promise instanceof PromiseArray) {
+ promise._cancel();
+ } else {
+ receiver.cancel();
+ }
+ } else if (typeof handler === "function") {
+ if (!isPromise) {
+ handler.call(receiver, value, promise);
+ } else {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (receiver instanceof Proxyable) {
+ if (!receiver._isResolved()) {
+ if (((bitField & 33554432) !== 0)) {
+ receiver._promiseFulfilled(value, promise);
+ } else {
+ receiver._promiseRejected(value, promise);
+ }
+ }
+ } else if (isPromise) {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ if (((bitField & 33554432) !== 0)) {
+ promise._fulfill(value);
+ } else {
+ promise._reject(value);
+ }
+ }
+};
+
+Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
+ var handler = ctx.handler;
+ var promise = ctx.promise;
+ var receiver = ctx.receiver;
+ var value = ctx.value;
+ if (typeof handler === "function") {
+ if (!(promise instanceof Promise)) {
+ handler.call(receiver, value, promise);
+ } else {
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (promise instanceof Promise) {
+ promise._reject(value);
+ }
+};
+
+Promise.prototype._settlePromiseCtx = function(ctx) {
+ this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
+};
+
+Promise.prototype._settlePromise0 = function(handler, value, bitField) {
+ var promise = this._promise0;
+ var receiver = this._receiverAt(0);
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ this._settlePromise(promise, handler, receiver, value);
+};
+
+Promise.prototype._clearCallbackDataAtIndex = function(index) {
+ var base = index * 4 - 4;
+ this[base + 2] =
+ this[base + 3] =
+ this[base + 0] =
+ this[base + 1] = undefined;
+};
+
+Promise.prototype._fulfill = function (value) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ if (value === this) {
+ var err = makeSelfResolutionError();
+ this._attachExtraTrace(err);
+ return this._reject(err);
+ }
+ this._setFulfilled();
+ this._rejectionHandler0 = value;
+
+ if ((bitField & 65535) > 0) {
+ if (((bitField & 134217728) !== 0)) {
+ this._settlePromises();
+ } else {
+ async.settlePromises(this);
+ }
+ }
+};
+
+Promise.prototype._reject = function (reason) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ this._setRejected();
+ this._fulfillmentHandler0 = reason;
+
+ if (this._isFinal()) {
+ return async.fatalError(reason, util.isNode);
+ }
+
+ if ((bitField & 65535) > 0) {
+ async.settlePromises(this);
+ } else {
+ this._ensurePossibleRejectionHandled();
+ }
+};
+
+Promise.prototype._fulfillPromises = function (len, value) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._fulfillmentHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, value);
+ }
+};
+
+Promise.prototype._rejectPromises = function (len, reason) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._rejectionHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, reason);
+ }
+};
+
+Promise.prototype._settlePromises = function () {
+ var bitField = this._bitField;
+ var len = (bitField & 65535);
+
+ if (len > 0) {
+ if (((bitField & 16842752) !== 0)) {
+ var reason = this._fulfillmentHandler0;
+ this._settlePromise0(this._rejectionHandler0, reason, bitField);
+ this._rejectPromises(len, reason);
+ } else {
+ var value = this._rejectionHandler0;
+ this._settlePromise0(this._fulfillmentHandler0, value, bitField);
+ this._fulfillPromises(len, value);
+ }
+ this._setLength(0);
+ }
+ this._clearCancellationData();
+};
+
+Promise.prototype._settledValue = function() {
+ var bitField = this._bitField;
+ if (((bitField & 33554432) !== 0)) {
+ return this._rejectionHandler0;
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._fulfillmentHandler0;
+ }
+};
+
+function deferResolve(v) {this.promise._resolveCallback(v);}
+function deferReject(v) {this.promise._rejectCallback(v, false);}
+
+Promise.defer = Promise.pending = function() {
+ debug.deprecated("Promise.defer", "new Promise");
+ var promise = new Promise(INTERNAL);
+ return {
+ promise: promise,
+ resolve: deferResolve,
+ reject: deferReject
+ };
+};
+
+util.notEnumerableProp(Promise,
+ "_makeSelfResolutionError",
+ makeSelfResolutionError);
+
+_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
+ debug);
+_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
+_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
+_dereq_("./direct_resolve")(Promise);
+_dereq_("./synchronous_inspection")(Promise);
+_dereq_("./join")(
+ Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
+Promise.Promise = Promise;
+Promise.version = "3.4.6";
+
+ 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 {};
+ }
+}
+
+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._unshiftOne = function(value) {
+ var capacity = this._capacity;
+ this._checkCapacity(this.length() + 1);
+ var front = this._front;
+ var i = (((( front - 1 ) &
+ ( capacity - 1) ) ^ capacity ) - capacity );
+ this[i] = value;
+ this._front = i;
+ this._length = this.length() + 1;
+};
+
+Queue.prototype.unshift = function(fn, receiver, arg) {
+ this._unshiftOne(arg);
+ this._unshiftOne(receiver);
+ this._unshiftOne(fn);
+};
+
+Queue.prototype.push = function (fn, receiver, arg) {
+ var length = this.length() + 3;
+ if (this._willBeOverCapacity(length)) {
+ this._pushOne(fn);
+ this._pushOne(receiver);
+ this._pushOne(arg);
+ return;
+ }
+ var j = this._front + length - 3;
+ this._checkCapacity(length);
+ var wrapMask = this._capacity - 1;
+ this[(j + 0) & wrapMask] = fn;
+ this[(j + 1) & wrapMask] = receiver;
+ this[(j + 2) & wrapMask] = arg;
+ this._length = length;
+};
+
+Queue.prototype.shift = function () {
+ var front = this._front,
+ ret = this[front];
+
+ this[front] = undefined;
+ this._front = (front + 1) & (this._capacity - 1);
+ this._length--;
+ return ret;
+};
+
+Queue.prototype.length = function () {
+ return this._length;
+};
+
+Queue.prototype._checkCapacity = function (size) {
+ if (this._capacity < size) {
+ this._resizeTo(this._capacity << 1);
+ }
+};
+
+Queue.prototype._resizeTo = function (capacity) {
+ var oldCapacity = this._capacity;
+ this._capacity = capacity;
+ var front = this._front;
+ var length = this._length;
+ var moveItemsCount = (front + length) & (oldCapacity - 1);
+ arrayMove(this, 0, this, oldCapacity, moveItemsCount);
+};
+
+module.exports = Queue;
+
+},{}],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 !== null &&
+ typeof obj === "object" &&
+ typeof obj.message === "string" &&
+ typeof obj.name === "string";
+}
+
+function markAsOriginatingFromRejection(e) {
+ try {
+ notEnumerableProp(e, "isOperational", true);
+ }
+ catch(ignore) {}
+}
+
+function originatesFromRejection(e) {
+ if (e == null) return false;
+ return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
+ e["isOperational"] === true);
+}
+
+function canAttachTrace(obj) {
+ return isError(obj) && es5.propertyIsWritable(obj, "stack");
+}
+
+var ensureErrorObject = (function() {
+ if (!("stack" in new Error())) {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ try {throw new Error(safeToString(value));}
+ catch(err) {return err;}
+ };
+ } else {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ return new Error(safeToString(value));
+ };
+ }
+})();
+
+function classString(obj) {
+ return {}.toString.call(obj);
+}
+
+function copyDescriptors(from, to, filter) {
+ var keys = es5.names(from);
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (filter(key)) {
+ try {
+ es5.defineProperty(to, key, es5.getDescriptor(from, key));
+ } catch (ignore) {}
+ }
+ }
+}
+
+var asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ }
+ return null;
+};
+
+if (typeof Symbol !== "undefined" && Symbol.iterator) {
+ var ArrayFrom = typeof Array.from === "function" ? function(v) {
+ return Array.from(v);
+ } : function(v) {
+ var ret = [];
+ var it = v[Symbol.iterator]();
+ var itResult;
+ while (!((itResult = it.next()).done)) {
+ ret.push(itResult.value);
+ }
+ return ret;
+ };
+
+ asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ } else if (v != null && typeof v[Symbol.iterator] === "function") {
+ return ArrayFrom(v);
+ }
+ return null;
+ };
+}
+
+var isNode = typeof process !== "undefined" &&
+ classString(process).toLowerCase() === "[object process]";
+
+function env(key, def) {
+ return isNode ? process.env[key] : def;
+}
+
+function getNativePromise() {
+ if (typeof Promise === "function") {
+ try {
+ var promise = new Promise(function(){});
+ if ({}.toString.call(promise) === "[object Promise]") {
+ return Promise;
+ }
+ } catch (e) {}
+ }
+}
+
+function domainBind(self, cb) {
+ return self.bind(cb);
+}
+
+var ret = {
+ isClass: isClass,
+ isIdentifier: isIdentifier,
+ inheritedDataKeys: inheritedDataKeys,
+ getDataPropertyOrDefault: getDataPropertyOrDefault,
+ thrower: thrower,
+ isArray: es5.isArray,
+ asArray: asArray,
+ notEnumerableProp: notEnumerableProp,
+ isPrimitive: isPrimitive,
+ isObject: isObject,
+ isError: isError,
+ canEvaluate: canEvaluate,
+ errorObj: errorObj,
+ tryCatch: tryCatch,
+ inherits: inherits,
+ withAppended: withAppended,
+ maybeWrapAsError: maybeWrapAsError,
+ toFastProperties: toFastProperties,
+ filledRange: filledRange,
+ toString: safeToString,
+ canAttachTrace: canAttachTrace,
+ ensureErrorObject: ensureErrorObject,
+ originatesFromRejection: originatesFromRejection,
+ markAsOriginatingFromRejection: markAsOriginatingFromRejection,
+ classString: classString,
+ copyDescriptors: copyDescriptors,
+ hasDevTools: typeof chrome !== "undefined" && chrome &&
+ typeof chrome.loadTimes === "function",
+ isNode: isNode,
+ env: env,
+ global: globalObject,
+ getNativePromise: getNativePromise,
+ domainBind: domainBind
+};
+ret.isRecentNode = ret.isNode && (function() {
+ var version = process.versions.node.split(".").map(Number);
+ return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
+})();
+
+if (ret.isNode) ret.toFastProperties(process);
+
+try {throw new Error(); } catch (e) {ret.lastLineError = e;}
+module.exports = ret;
+
+},{"./es5":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..d5f6e66
--- /dev/null
+++ b/node_modules/bluebird/js/browser/bluebird.core.min.js
@@ -0,0 +1,31 @@
+/* @preserve
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013-2015 Petka Antonov
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+/**
+ * bluebird build version 3.4.6
+ * Features enabled: core
+ * 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 S(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=k(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=k(o);o.stack=a.message+"\n"+a.stack.join("\n")}tt("warning",o)||E(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&&(e=e.slice(n)),e}function k(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:C(e)}}function E(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 L?L(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||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():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=P(t);return e&&e.fileName===n&&a<=e.line&&e.line<=s?!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 x,A,L,N=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(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),B.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){j("rejectionHandled",x,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=N();A="function"==typeof t?null===e?t:I.domainBind(e,t):void 0},e.onUnhandledRejectionHandled=function(t){var e=N();x="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&&O()){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&&O()};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}"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.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(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 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}}}},S.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=k(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&&(L=function(t){console.warn(t)},I.isNode&&process.stderr.isTTY?L=function(t,e){var n=e?"[33m":"[31m";console.warn(n+t+"[0m\n")}:I.isNode||"string"!=typeof(new Error).stack||(L=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:R,warn:y,deprecated:v,CapturedTrace:S,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 a(){return c.call(this,this.promise._target()._settledValue())}function s(t){return o(this,t)?void 0:(p.e=t,p)}function c(t){var r=this.promise,c=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?c.call(r._boundValue()):c.call(r._boundValue(),t);if(void 0!==l){r._setReturnedNonUndefined();var f=n(l,r);if(f instanceof e){if(null!=this.cancelPromise){if(f._isCancelled()){var h=new u("late cancellation observer");return r._attachExtraTrace(h),p.e=h,p}f.isPending()&&f._attachCancellationCallback(new i(this))}return f._then(a,s,void 0,this,void 0)}}}return r.isRejected()?(o(this),p.e=t,p):(o(this),t)}var l=t("./util"),u=e.CancellationError,p=l.errorObj;return r.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){o(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,i){return"function"!=typeof t?this.then():this._then(n,i,void 0,new r(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,c,c)},e.prototype.tap=function(t){return this._passThrough(t,1,c)},r}},{"./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("expecting an object but got A catch statement predicate "+h.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,O(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 E(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=S(t)(P(e,n));return r===R&&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=k(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=k(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){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=S(t).apply(this._boundValue(),n):(o=R,o.e=new g("cannot .spread() a non-array: "+h.classString(n))):o=S(t).call(e,n);var a=r._popContext();i=r._bitField,0===(65536&i)&&(o===w?r._reject(n):o===R?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,S(e).call(r,o)===R&&t._reject(R.e)):e===u?t._fulfill(u.call(r)):r instanceof n?r._promiseCancelled(t):a||t instanceof E?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,k,p,F),t("./bind")(i,b,k,F),t("./cancel")(i,E,p,F),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,E,k,b,v,c),i.Promise=i,i.version="3.4.6",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{}}}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 L.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 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}(),H.isNode&&H.toFastProperties(process);try{throw new Error}catch(D){H.lastLineError=D}e.exports=H},{"./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..4bae478
--- /dev/null
+++ b/node_modules/bluebird/js/browser/bluebird.js
@@ -0,0 +1,5598 @@
+/* @preserve
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013-2015 Petka Antonov
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+/**
+ * bluebird build version 3.4.6
+ * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
+*/
+!function(e){if("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();
+ async.invokeLater(this._notifyUnhandledRejection, this, undefined);
+};
+
+Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
+ fireRejectionEvent("rejectionHandled",
+ unhandledRejectionHandled, undefined, this);
+};
+
+Promise.prototype._setReturnedNonUndefined = function() {
+ this._bitField = this._bitField | 268435456;
+};
+
+Promise.prototype._returnedNonUndefined = function() {
+ return (this._bitField & 268435456) !== 0;
+};
+
+Promise.prototype._notifyUnhandledRejection = function () {
+ if (this._isRejectionUnhandled()) {
+ var reason = this._settledValue();
+ this._setUnhandledRejectionIsNotified();
+ fireRejectionEvent("unhandledRejection",
+ possiblyUnhandledRejection, reason, this);
+ }
+};
+
+Promise.prototype._setUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField | 262144;
+};
+
+Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField & (~262144);
+};
+
+Promise.prototype._isUnhandledRejectionNotified = function () {
+ return (this._bitField & 262144) > 0;
+};
+
+Promise.prototype._setRejectionIsUnhandled = function () {
+ this._bitField = this._bitField | 1048576;
+};
+
+Promise.prototype._unsetRejectionIsUnhandled = function () {
+ this._bitField = this._bitField & (~1048576);
+ if (this._isUnhandledRejectionNotified()) {
+ this._unsetUnhandledRejectionIsNotified();
+ this._notifyUnhandledRejectionIsHandled();
+ }
+};
+
+Promise.prototype._isRejectionUnhandled = function () {
+ return (this._bitField & 1048576) > 0;
+};
+
+Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
+ return warn(message, shouldUseOwnTrace, promise || this);
+};
+
+Promise.onPossiblyUnhandledRejection = function (fn) {
+ var domain = getDomain();
+ possiblyUnhandledRejection =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+Promise.onUnhandledRejectionHandled = function (fn) {
+ var domain = getDomain();
+ unhandledRejectionHandled =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+var disableLongStackTraces = function() {};
+Promise.longStackTraces = function () {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ if (!config.longStackTraces && longStackTracesIsSupported()) {
+ var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
+ var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
+ config.longStackTraces = true;
+ disableLongStackTraces = function() {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ Promise.prototype._captureStackTrace = Promise_captureStackTrace;
+ Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
+ Context.deactivateLongStackTraces();
+ async.enableTrampoline();
+ config.longStackTraces = false;
+ };
+ Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
+ Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
+ Context.activateLongStackTraces();
+ async.disableTrampolineIfNecessary();
+ }
+};
+
+Promise.hasLongStackTraces = function () {
+ return config.longStackTraces && longStackTracesIsSupported();
+};
+
+var fireDomEvent = (function() {
+ try {
+ if (typeof CustomEvent === "function") {
+ var event = new CustomEvent("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new CustomEvent(name.toLowerCase(), {
+ detail: event,
+ cancelable: true
+ });
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else if (typeof Event === "function") {
+ var event = new Event("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new Event(name.toLowerCase(), {
+ cancelable: true
+ });
+ domEvent.detail = event;
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else {
+ var event = document.createEvent("CustomEvent");
+ event.initCustomEvent("testingtheevent", false, true, {});
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = document.createEvent("CustomEvent");
+ domEvent.initCustomEvent(name.toLowerCase(), false, true,
+ event);
+ return !util.global.dispatchEvent(domEvent);
+ };
+ }
+ } catch (e) {}
+ return function() {
+ return false;
+ };
+})();
+
+var fireGlobalEvent = (function() {
+ if (util.isNode) {
+ return function() {
+ return process.emit.apply(process, arguments);
+ };
+ } else {
+ if (!util.global) {
+ return function() {
+ return false;
+ };
+ }
+ return function(name) {
+ var methodName = "on" + name.toLowerCase();
+ var method = util.global[methodName];
+ if (!method) return false;
+ method.apply(util.global, [].slice.call(arguments, 1));
+ return true;
+ };
+ }
+})();
+
+function generatePromiseLifecycleEventObject(name, promise) {
+ return {promise: promise};
+}
+
+var eventToObjectGenerator = {
+ promiseCreated: generatePromiseLifecycleEventObject,
+ promiseFulfilled: generatePromiseLifecycleEventObject,
+ promiseRejected: generatePromiseLifecycleEventObject,
+ promiseResolved: generatePromiseLifecycleEventObject,
+ promiseCancelled: generatePromiseLifecycleEventObject,
+ promiseChained: function(name, promise, child) {
+ return {promise: promise, child: child};
+ },
+ warning: function(name, warning) {
+ return {warning: warning};
+ },
+ unhandledRejection: function (name, reason, promise) {
+ return {reason: reason, promise: promise};
+ },
+ rejectionHandled: generatePromiseLifecycleEventObject
+};
+
+var activeFireEvent = function (name) {
+ var globalEventFired = false;
+ try {
+ globalEventFired = fireGlobalEvent.apply(null, arguments);
+ } catch (e) {
+ async.throwLater(e);
+ globalEventFired = true;
+ }
+
+ var domEventFired = false;
+ try {
+ domEventFired = fireDomEvent(name,
+ eventToObjectGenerator[name].apply(null, arguments));
+ } catch (e) {
+ async.throwLater(e);
+ domEventFired = true;
+ }
+
+ return domEventFired || globalEventFired;
+};
+
+Promise.config = function(opts) {
+ opts = Object(opts);
+ if ("longStackTraces" in opts) {
+ if (opts.longStackTraces) {
+ Promise.longStackTraces();
+ } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
+ disableLongStackTraces();
+ }
+ }
+ if ("warnings" in opts) {
+ var warningsOption = opts.warnings;
+ config.warnings = !!warningsOption;
+ wForgottenReturn = config.warnings;
+
+ if (util.isObject(warningsOption)) {
+ if ("wForgottenReturn" in warningsOption) {
+ wForgottenReturn = !!warningsOption.wForgottenReturn;
+ }
+ }
+ }
+ if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
+ if (async.haveItemsQueued()) {
+ throw new Error(
+ "cannot enable cancellation after promises are in use");
+ }
+ Promise.prototype._clearCancellationData =
+ cancellationClearCancellationData;
+ Promise.prototype._propagateFrom = cancellationPropagateFrom;
+ Promise.prototype._onCancel = cancellationOnCancel;
+ Promise.prototype._setOnCancel = cancellationSetOnCancel;
+ Promise.prototype._attachCancellationCallback =
+ cancellationAttachCancellationCallback;
+ Promise.prototype._execute = cancellationExecute;
+ propagateFromFunction = cancellationPropagateFrom;
+ config.cancellation = true;
+ }
+ if ("monitoring" in opts) {
+ if (opts.monitoring && !config.monitoring) {
+ config.monitoring = true;
+ Promise.prototype._fireEvent = activeFireEvent;
+ } else if (!opts.monitoring && config.monitoring) {
+ config.monitoring = false;
+ Promise.prototype._fireEvent = defaultFireEvent;
+ }
+ }
+};
+
+function defaultFireEvent() { return false; }
+
+Promise.prototype._fireEvent = defaultFireEvent;
+Promise.prototype._execute = function(executor, resolve, reject) {
+ try {
+ executor(resolve, reject);
+ } catch (e) {
+ return e;
+ }
+};
+Promise.prototype._onCancel = function () {};
+Promise.prototype._setOnCancel = function (handler) { ; };
+Promise.prototype._attachCancellationCallback = function(onCancel) {
+ ;
+};
+Promise.prototype._captureStackTrace = function () {};
+Promise.prototype._attachExtraTrace = function () {};
+Promise.prototype._clearCancellationData = function() {};
+Promise.prototype._propagateFrom = function (parent, flags) {
+ ;
+ ;
+};
+
+function cancellationExecute(executor, resolve, reject) {
+ var promise = this;
+ try {
+ executor(resolve, reject, function(onCancel) {
+ if (typeof onCancel !== "function") {
+ throw new TypeError("onCancel must be a function, got: " +
+ util.toString(onCancel));
+ }
+ promise._attachCancellationCallback(onCancel);
+ });
+ } catch (e) {
+ return e;
+ }
+}
+
+function cancellationAttachCancellationCallback(onCancel) {
+ if (!this._isCancellable()) return this;
+
+ var previousOnCancel = this._onCancel();
+ if (previousOnCancel !== undefined) {
+ if (util.isArray(previousOnCancel)) {
+ previousOnCancel.push(onCancel);
+ } else {
+ this._setOnCancel([previousOnCancel, onCancel]);
+ }
+ } else {
+ this._setOnCancel(onCancel);
+ }
+}
+
+function cancellationOnCancel() {
+ return this._onCancelField;
+}
+
+function cancellationSetOnCancel(onCancel) {
+ this._onCancelField = onCancel;
+}
+
+function cancellationClearCancellationData() {
+ this._cancellationParent = undefined;
+ this._onCancelField = undefined;
+}
+
+function cancellationPropagateFrom(parent, flags) {
+ if ((flags & 1) !== 0) {
+ this._cancellationParent = parent;
+ var branchesRemainingToCancel = parent._branchesRemainingToCancel;
+ if (branchesRemainingToCancel === undefined) {
+ branchesRemainingToCancel = 0;
+ }
+ parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
+ }
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+
+function bindingPropagateFrom(parent, flags) {
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+var propagateFromFunction = bindingPropagateFrom;
+
+function boundValueFunction() {
+ var ret = this._boundTo;
+ if (ret !== undefined) {
+ if (ret instanceof Promise) {
+ if (ret.isFulfilled()) {
+ return ret.value();
+ } else {
+ return undefined;
+ }
+ }
+ }
+ return ret;
+}
+
+function longStackTracesCaptureStackTrace() {
+ this._trace = new CapturedTrace(this._peekContext());
+}
+
+function longStackTracesAttachExtraTrace(error, ignoreSelf) {
+ if (canAttachTrace(error)) {
+ var trace = this._trace;
+ if (trace !== undefined) {
+ if (ignoreSelf) trace = trace._parent;
+ }
+ if (trace !== undefined) {
+ trace.attachExtraTrace(error);
+ } else if (!error.__stackCleaned__) {
+ var parsed = parseStackAndMessage(error);
+ util.notEnumerableProp(error, "stack",
+ parsed.message + "\n" + parsed.stack.join("\n"));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+ }
+ }
+}
+
+function checkForgottenReturns(returnValue, promiseCreated, name, promise,
+ parent) {
+ if (returnValue === undefined && promiseCreated !== null &&
+ wForgottenReturn) {
+ if (parent !== undefined && parent._returnedNonUndefined()) return;
+ if ((promise._bitField & 65535) === 0) return;
+
+ if (name) name = name + " ";
+ var handlerLine = "";
+ var creatorLine = "";
+ if (promiseCreated._trace) {
+ var traceLines = promiseCreated._trace.stack.split("\n");
+ var stack = cleanStack(traceLines);
+ for (var i = stack.length - 1; i >= 0; --i) {
+ var line = stack[i];
+ if (!nodeFramePattern.test(line)) {
+ var lineMatches = line.match(parseLinePattern);
+ if (lineMatches) {
+ handlerLine = "at " + lineMatches[1] +
+ ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
+ }
+ break;
+ }
+ }
+
+ if (stack.length > 0) {
+ var firstUserLine = stack[0];
+ for (var i = 0; i < traceLines.length; ++i) {
+
+ if (traceLines[i] === firstUserLine) {
+ if (i > 0) {
+ creatorLine = "\n" + traceLines[i - 1];
+ }
+ break;
+ }
+ }
+
+ }
+ }
+ var msg = "a promise was created in a " + name +
+ "handler " + handlerLine + "but was not returned from it, " +
+ "see http://goo.gl/rRqMUw" +
+ creatorLine;
+ promise._warn(msg, true, promiseCreated);
+ }
+}
+
+function deprecated(name, replacement) {
+ var message = name +
+ " is deprecated and will be removed in a future version.";
+ if (replacement) message += " Use " + replacement + " instead.";
+ return warn(message);
+}
+
+function warn(message, shouldUseOwnTrace, promise) {
+ if (!config.warnings) return;
+ var warning = new Warning(message);
+ var ctx;
+ if (shouldUseOwnTrace) {
+ promise._attachExtraTrace(warning);
+ } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
+ ctx.attachExtraTrace(warning);
+ } else {
+ var parsed = parseStackAndMessage(warning);
+ warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
+ }
+
+ if (!activeFireEvent("warning", warning)) {
+ formatAndLogError(warning, "", true);
+ }
+}
+
+function reconstructStack(message, stacks) {
+ for (var i = 0; i < stacks.length - 1; ++i) {
+ stacks[i].push("From previous event:");
+ stacks[i] = stacks[i].join("\n");
+ }
+ if (i < stacks.length) {
+ stacks[i] = stacks[i].join("\n");
+ }
+ return message + "\n" + stacks.join("\n");
+}
+
+function removeDuplicateOrEmptyJumps(stacks) {
+ for (var i = 0; i < stacks.length; ++i) {
+ if (stacks[i].length === 0 ||
+ ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
+ stacks.splice(i, 1);
+ i--;
+ }
+ }
+}
+
+function removeCommonRoots(stacks) {
+ var current = stacks[0];
+ for (var i = 1; i < stacks.length; ++i) {
+ var prev = stacks[i];
+ var currentLastIndex = current.length - 1;
+ var currentLastLine = current[currentLastIndex];
+ var commonRootMeetPoint = -1;
+
+ for (var j = prev.length - 1; j >= 0; --j) {
+ if (prev[j] === currentLastLine) {
+ commonRootMeetPoint = j;
+ break;
+ }
+ }
+
+ for (var j = commonRootMeetPoint; j >= 0; --j) {
+ var line = prev[j];
+ if (current[currentLastIndex] === line) {
+ current.pop();
+ currentLastIndex--;
+ } else {
+ break;
+ }
+ }
+ current = prev;
+ }
+}
+
+function cleanStack(stack) {
+ var ret = [];
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ var isTraceLine = " (No stack trace)" === line ||
+ stackFramePattern.test(line);
+ var isInternalFrame = isTraceLine && shouldIgnore(line);
+ if (isTraceLine && !isInternalFrame) {
+ if (indentStackFrames && line.charAt(0) !== " ") {
+ line = " " + line;
+ }
+ ret.push(line);
+ }
+ }
+ return ret;
+}
+
+function stackFramesAsArray(error) {
+ var stack = error.stack.replace(/\s+$/g, "").split("\n");
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ if (" (No stack trace)" === line || stackFramePattern.test(line)) {
+ break;
+ }
+ }
+ if (i > 0) {
+ stack = stack.slice(i);
+ }
+ return stack;
+}
+
+function parseStackAndMessage(error) {
+ var stack = error.stack;
+ var message = error.toString();
+ stack = typeof stack === "string" && stack.length > 0
+ ? stackFramesAsArray(error) : [" (No stack trace)"];
+ return {
+ message: message,
+ stack: cleanStack(stack)
+ };
+}
+
+function formatAndLogError(error, title, isSoft) {
+ if (typeof console !== "undefined") {
+ var message;
+ if (util.isObject(error)) {
+ var stack = error.stack;
+ message = title + formatStack(stack, error);
+ } else {
+ message = title + String(error);
+ }
+ if (typeof printWarning === "function") {
+ printWarning(message, isSoft);
+ } else if (typeof console.log === "function" ||
+ typeof console.log === "object") {
+ console.log(message);
+ }
+ }
+}
+
+function fireRejectionEvent(name, localHandler, reason, promise) {
+ var localEventFired = false;
+ try {
+ if (typeof localHandler === "function") {
+ localEventFired = true;
+ if (name === "rejectionHandled") {
+ localHandler(promise);
+ } else {
+ localHandler(reason, promise);
+ }
+ }
+ } catch (e) {
+ async.throwLater(e);
+ }
+
+ if (name === "unhandledRejection") {
+ if (!activeFireEvent(name, reason, promise) && !localEventFired) {
+ formatAndLogError(reason, "Unhandled rejection ");
+ }
+ } else {
+ activeFireEvent(name, promise);
+ }
+}
+
+function formatNonError(obj) {
+ var str;
+ if (typeof obj === "function") {
+ str = "[function " +
+ (obj.name || "anonymous") +
+ "]";
+ } else {
+ str = obj && typeof obj.toString === "function"
+ ? obj.toString() : util.toString(obj);
+ var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
+ if (ruselessToString.test(str)) {
+ try {
+ var newStr = JSON.stringify(obj);
+ str = newStr;
+ }
+ catch(e) {
+
+ }
+ }
+ if (str.length === 0) {
+ str = "(empty array)";
+ }
+ }
+ return ("(<" + snip(str) + ">, no stack trace)");
+}
+
+function snip(str) {
+ var maxChars = 41;
+ if (str.length < maxChars) {
+ return str;
+ }
+ return str.substr(0, maxChars - 3) + "...";
+}
+
+function longStackTracesIsSupported() {
+ return typeof captureStackTrace === "function";
+}
+
+var shouldIgnore = function() { return false; };
+var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
+function parseLineInfo(line) {
+ var matches = line.match(parseLineInfoRegex);
+ if (matches) {
+ return {
+ fileName: matches[1],
+ line: parseInt(matches[2], 10)
+ };
+ }
+}
+
+function setBounds(firstLineError, lastLineError) {
+ if (!longStackTracesIsSupported()) return;
+ var firstStackLines = firstLineError.stack.split("\n");
+ var lastStackLines = lastLineError.stack.split("\n");
+ var firstIndex = -1;
+ var lastIndex = -1;
+ var firstFileName;
+ var lastFileName;
+ for (var i = 0; i < firstStackLines.length; ++i) {
+ var result = parseLineInfo(firstStackLines[i]);
+ if (result) {
+ firstFileName = result.fileName;
+ firstIndex = result.line;
+ break;
+ }
+ }
+ for (var i = 0; i < lastStackLines.length; ++i) {
+ var result = parseLineInfo(lastStackLines[i]);
+ if (result) {
+ lastFileName = result.fileName;
+ lastIndex = result.line;
+ break;
+ }
+ }
+ if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
+ firstFileName !== lastFileName || firstIndex >= lastIndex) {
+ return;
+ }
+
+ shouldIgnore = function(line) {
+ if (bluebirdFramePattern.test(line)) return true;
+ var info = parseLineInfo(line);
+ if (info) {
+ if (info.fileName === firstFileName &&
+ (firstIndex <= info.line && info.line <= lastIndex)) {
+ return true;
+ }
+ }
+ return false;
+ };
+}
+
+function CapturedTrace(parent) {
+ this._parent = parent;
+ this._promisesCreated = 0;
+ var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
+ captureStackTrace(this, CapturedTrace);
+ if (length > 32) this.uncycle();
+}
+util.inherits(CapturedTrace, Error);
+Context.CapturedTrace = CapturedTrace;
+
+CapturedTrace.prototype.uncycle = function() {
+ var length = this._length;
+ if (length < 2) return;
+ var nodes = [];
+ var stackToIndex = {};
+
+ for (var i = 0, node = this; node !== undefined; ++i) {
+ nodes.push(node);
+ node = node._parent;
+ }
+ length = this._length = i;
+ for (var i = length - 1; i >= 0; --i) {
+ var stack = nodes[i].stack;
+ if (stackToIndex[stack] === undefined) {
+ stackToIndex[stack] = i;
+ }
+ }
+ for (var i = 0; i < length; ++i) {
+ var currentStack = nodes[i].stack;
+ var index = stackToIndex[currentStack];
+ if (index !== undefined && index !== i) {
+ if (index > 0) {
+ nodes[index - 1]._parent = undefined;
+ nodes[index - 1]._length = 1;
+ }
+ nodes[i]._parent = undefined;
+ nodes[i]._length = 1;
+ var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
+
+ if (index < length - 1) {
+ cycleEdgeNode._parent = nodes[index + 1];
+ cycleEdgeNode._parent.uncycle();
+ cycleEdgeNode._length =
+ cycleEdgeNode._parent._length + 1;
+ } else {
+ cycleEdgeNode._parent = undefined;
+ cycleEdgeNode._length = 1;
+ }
+ var currentChildLength = cycleEdgeNode._length + 1;
+ for (var j = i - 2; j >= 0; --j) {
+ nodes[j]._length = currentChildLength;
+ currentChildLength++;
+ }
+ return;
+ }
+ }
+};
+
+CapturedTrace.prototype.attachExtraTrace = function(error) {
+ if (error.__stackCleaned__) return;
+ this.uncycle();
+ var parsed = parseStackAndMessage(error);
+ var message = parsed.message;
+ var stacks = [parsed.stack];
+
+ var trace = this;
+ while (trace !== undefined) {
+ stacks.push(cleanStack(trace.stack.split("\n")));
+ trace = trace._parent;
+ }
+ removeCommonRoots(stacks);
+ removeDuplicateOrEmptyJumps(stacks);
+ util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+};
+
+var captureStackTrace = (function stackDetection() {
+ var v8stackFramePattern = /^\s*at\s*/;
+ var v8stackFormatter = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if (error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ if (typeof Error.stackTraceLimit === "number" &&
+ typeof Error.captureStackTrace === "function") {
+ Error.stackTraceLimit += 6;
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ var captureStackTrace = Error.captureStackTrace;
+
+ shouldIgnore = function(line) {
+ return bluebirdFramePattern.test(line);
+ };
+ return function(receiver, ignoreUntil) {
+ Error.stackTraceLimit += 6;
+ captureStackTrace(receiver, ignoreUntil);
+ Error.stackTraceLimit -= 6;
+ };
+ }
+ var err = new Error();
+
+ if (typeof err.stack === "string" &&
+ err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
+ stackFramePattern = /@/;
+ formatStack = v8stackFormatter;
+ indentStackFrames = true;
+ return function captureStackTrace(o) {
+ o.stack = new Error().stack;
+ };
+ }
+
+ var hasStackAfterThrow;
+ try { throw new Error(); }
+ catch(e) {
+ hasStackAfterThrow = ("stack" in e);
+ }
+ if (!("stack" in err) && hasStackAfterThrow &&
+ typeof Error.stackTraceLimit === "number") {
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ return function captureStackTrace(o) {
+ Error.stackTraceLimit += 6;
+ try { throw new Error(); }
+ catch(e) { o.stack = e.stack; }
+ Error.stackTraceLimit -= 6;
+ };
+ }
+
+ formatStack = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if ((typeof error === "object" ||
+ typeof error === "function") &&
+ error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ return null;
+
+})([]);
+
+if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
+ printWarning = function (message) {
+ console.warn(message);
+ };
+ if (util.isNode && process.stderr.isTTY) {
+ printWarning = function(message, isSoft) {
+ var color = isSoft ? "\u001b[33m" : "\u001b[31m";
+ console.warn(color + message + "\u001b[0m\n");
+ };
+ } else if (!util.isNode && typeof (new Error().stack) === "string") {
+ printWarning = function(message, isSoft) {
+ console.warn("%c" + message,
+ isSoft ? "color: darkorange" : "color: red");
+ };
+ }
+}
+
+var config = {
+ warnings: warnings,
+ longStackTraces: false,
+ cancellation: false,
+ monitoring: false
+};
+
+if (longStackTraces) Promise.longStackTraces();
+
+return {
+ longStackTraces: function() {
+ return config.longStackTraces;
+ },
+ warnings: function() {
+ return config.warnings;
+ },
+ cancellation: function() {
+ return config.cancellation;
+ },
+ monitoring: function() {
+ return config.monitoring;
+ },
+ propagateFromFunction: function() {
+ return propagateFromFunction;
+ },
+ boundValueFunction: function() {
+ return boundValueFunction;
+ },
+ checkForgottenReturns: checkForgottenReturns,
+ setBounds: setBounds,
+ warn: warn,
+ deprecated: deprecated,
+ CapturedTrace: CapturedTrace,
+ fireDomEvent: fireDomEvent,
+ fireGlobalEvent: fireGlobalEvent
+};
+};
+
+},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise) {
+function returner() {
+ return this.value;
+}
+function thrower() {
+ throw this.reason;
+}
+
+Promise.prototype["return"] =
+Promise.prototype.thenReturn = function (value) {
+ if (value instanceof Promise) value.suppressUnhandledRejections();
+ return this._then(
+ returner, undefined, undefined, {value: value}, undefined);
+};
+
+Promise.prototype["throw"] =
+Promise.prototype.thenThrow = function (reason) {
+ return this._then(
+ thrower, undefined, undefined, {reason: reason}, undefined);
+};
+
+Promise.prototype.catchThrow = function (reason) {
+ if (arguments.length <= 1) {
+ return this._then(
+ undefined, thrower, undefined, {reason: reason}, undefined);
+ } else {
+ var _reason = arguments[1];
+ var handler = function() {throw _reason;};
+ return this.caught(reason, handler);
+ }
+};
+
+Promise.prototype.catchReturn = function (value) {
+ if (arguments.length <= 1) {
+ if (value instanceof Promise) value.suppressUnhandledRejections();
+ return this._then(
+ undefined, returner, undefined, {value: value}, undefined);
+ } else {
+ var _value = arguments[1];
+ if (_value instanceof Promise) _value.suppressUnhandledRejections();
+ var handler = function() {return _value;};
+ return this.caught(value, handler);
+ }
+};
+};
+
+},{}],11:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var PromiseReduce = Promise.reduce;
+var PromiseAll = Promise.all;
+
+function promiseAllThis() {
+ return PromiseAll(this);
+}
+
+function PromiseMapSeries(promises, fn) {
+ return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
+}
+
+Promise.prototype.each = function (fn) {
+ return PromiseReduce(this, fn, INTERNAL, 0)
+ ._then(promiseAllThis, undefined, undefined, this, undefined);
+};
+
+Promise.prototype.mapSeries = function (fn) {
+ return PromiseReduce(this, fn, INTERNAL, INTERNAL);
+};
+
+Promise.each = function (promises, fn) {
+ return PromiseReduce(promises, fn, INTERNAL, 0)
+ ._then(promiseAllThis, undefined, undefined, promises, undefined);
+};
+
+Promise.mapSeries = PromiseMapSeries;
+};
+
+
+},{}],12:[function(_dereq_,module,exports){
+"use strict";
+var es5 = _dereq_("./es5");
+var Objectfreeze = es5.freeze;
+var util = _dereq_("./util");
+var inherits = util.inherits;
+var notEnumerableProp = util.notEnumerableProp;
+
+function subError(nameProperty, defaultMessage) {
+ function SubError(message) {
+ if (!(this instanceof SubError)) return new SubError(message);
+ notEnumerableProp(this, "message",
+ typeof message === "string" ? message : defaultMessage);
+ notEnumerableProp(this, "name", nameProperty);
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ } else {
+ Error.call(this);
+ }
+ }
+ inherits(SubError, Error);
+ return SubError;
+}
+
+var _TypeError, _RangeError;
+var Warning = subError("Warning", "warning");
+var CancellationError = subError("CancellationError", "cancellation error");
+var TimeoutError = subError("TimeoutError", "timeout error");
+var AggregateError = subError("AggregateError", "aggregate error");
+try {
+ _TypeError = TypeError;
+ _RangeError = RangeError;
+} catch(e) {
+ _TypeError = subError("TypeError", "type error");
+ _RangeError = subError("RangeError", "range error");
+}
+
+var methods = ("join pop push shift unshift slice filter forEach some " +
+ "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
+
+for (var i = 0; i < methods.length; ++i) {
+ if (typeof Array.prototype[methods[i]] === "function") {
+ AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
+ }
+}
+
+es5.defineProperty(AggregateError.prototype, "length", {
+ value: 0,
+ configurable: false,
+ writable: true,
+ enumerable: true
+});
+AggregateError.prototype["isOperational"] = true;
+var level = 0;
+AggregateError.prototype.toString = function() {
+ var indent = Array(level * 4 + 1).join(" ");
+ var ret = "\n" + indent + "AggregateError of:" + "\n";
+ level++;
+ indent = Array(level * 4 + 1).join(" ");
+ for (var i = 0; i < this.length; ++i) {
+ var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
+ var lines = str.split("\n");
+ for (var j = 0; j < lines.length; ++j) {
+ lines[j] = indent + lines[j];
+ }
+ str = lines.join("\n");
+ ret += str + "\n";
+ }
+ level--;
+ return ret;
+};
+
+function OperationalError(message) {
+ if (!(this instanceof OperationalError))
+ return new OperationalError(message);
+ notEnumerableProp(this, "name", "OperationalError");
+ notEnumerableProp(this, "message", message);
+ this.cause = message;
+ this["isOperational"] = true;
+
+ if (message instanceof Error) {
+ notEnumerableProp(this, "message", message.message);
+ notEnumerableProp(this, "stack", message.stack);
+ } else if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, this.constructor);
+ }
+
+}
+inherits(OperationalError, Error);
+
+var errorTypes = Error["__BluebirdErrorTypes__"];
+if (!errorTypes) {
+ errorTypes = Objectfreeze({
+ CancellationError: CancellationError,
+ TimeoutError: TimeoutError,
+ OperationalError: OperationalError,
+ RejectionError: OperationalError,
+ AggregateError: AggregateError
+ });
+ es5.defineProperty(Error, "__BluebirdErrorTypes__", {
+ value: errorTypes,
+ writable: false,
+ enumerable: false,
+ configurable: false
+ });
+}
+
+module.exports = {
+ Error: Error,
+ TypeError: _TypeError,
+ RangeError: _RangeError,
+ CancellationError: errorTypes.CancellationError,
+ OperationalError: errorTypes.OperationalError,
+ TimeoutError: errorTypes.TimeoutError,
+ AggregateError: errorTypes.AggregateError,
+ Warning: Warning
+};
+
+},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
+var isES5 = (function(){
+ "use strict";
+ return this === undefined;
+})();
+
+if (isES5) {
+ module.exports = {
+ freeze: Object.freeze,
+ defineProperty: Object.defineProperty,
+ getDescriptor: Object.getOwnPropertyDescriptor,
+ keys: Object.keys,
+ names: Object.getOwnPropertyNames,
+ getPrototypeOf: Object.getPrototypeOf,
+ isArray: Array.isArray,
+ isES5: isES5,
+ propertyIsWritable: function(obj, prop) {
+ var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
+ return !!(!descriptor || descriptor.writable || descriptor.set);
+ }
+ };
+} else {
+ var has = {}.hasOwnProperty;
+ var str = {}.toString;
+ var proto = {}.constructor.prototype;
+
+ var ObjectKeys = function (o) {
+ var ret = [];
+ for (var key in o) {
+ if (has.call(o, key)) {
+ ret.push(key);
+ }
+ }
+ return ret;
+ };
+
+ var ObjectGetDescriptor = function(o, key) {
+ return {value: o[key]};
+ };
+
+ var ObjectDefineProperty = function (o, key, desc) {
+ o[key] = desc.value;
+ return o;
+ };
+
+ var ObjectFreeze = function (obj) {
+ return obj;
+ };
+
+ var ObjectGetPrototypeOf = function (obj) {
+ try {
+ return Object(obj).constructor.prototype;
+ }
+ catch (e) {
+ return proto;
+ }
+ };
+
+ var ArrayIsArray = function (obj) {
+ try {
+ return str.call(obj) === "[object Array]";
+ }
+ catch(e) {
+ return false;
+ }
+ };
+
+ module.exports = {
+ isArray: ArrayIsArray,
+ keys: ObjectKeys,
+ names: ObjectKeys,
+ defineProperty: ObjectDefineProperty,
+ getDescriptor: ObjectGetDescriptor,
+ freeze: ObjectFreeze,
+ getPrototypeOf: ObjectGetPrototypeOf,
+ isES5: isES5,
+ propertyIsWritable: function() {
+ return true;
+ }
+ };
+}
+
+},{}],14:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var PromiseMap = Promise.map;
+
+Promise.prototype.filter = function (fn, options) {
+ return PromiseMap(this, fn, options, INTERNAL);
+};
+
+Promise.filter = function (promises, fn, options) {
+ return PromiseMap(promises, fn, options, INTERNAL);
+};
+};
+
+},{}],15:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, tryConvertToPromise) {
+var util = _dereq_("./util");
+var CancellationError = Promise.CancellationError;
+var errorObj = util.errorObj;
+
+function PassThroughHandlerContext(promise, type, handler) {
+ this.promise = promise;
+ this.type = type;
+ this.handler = handler;
+ this.called = false;
+ this.cancelPromise = null;
+}
+
+PassThroughHandlerContext.prototype.isFinallyHandler = function() {
+ return this.type === 0;
+};
+
+function FinallyHandlerCancelReaction(finallyHandler) {
+ this.finallyHandler = finallyHandler;
+}
+
+FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
+ checkCancel(this.finallyHandler);
+};
+
+function checkCancel(ctx, reason) {
+ if (ctx.cancelPromise != null) {
+ if (arguments.length > 1) {
+ ctx.cancelPromise._reject(reason);
+ } else {
+ ctx.cancelPromise._cancel();
+ }
+ ctx.cancelPromise = null;
+ return true;
+ }
+ return false;
+}
+
+function succeed() {
+ return finallyHandler.call(this, this.promise._target()._settledValue());
+}
+function fail(reason) {
+ if (checkCancel(this, reason)) return;
+ errorObj.e = reason;
+ return errorObj;
+}
+function finallyHandler(reasonOrValue) {
+ var promise = this.promise;
+ var handler = this.handler;
+
+ if (!this.called) {
+ this.called = true;
+ var ret = this.isFinallyHandler()
+ ? handler.call(promise._boundValue())
+ : handler.call(promise._boundValue(), reasonOrValue);
+ if (ret !== undefined) {
+ promise._setReturnedNonUndefined();
+ var maybePromise = tryConvertToPromise(ret, promise);
+ if (maybePromise instanceof Promise) {
+ if (this.cancelPromise != null) {
+ if (maybePromise._isCancelled()) {
+ var reason =
+ new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ errorObj.e = reason;
+ return errorObj;
+ } else if (maybePromise.isPending()) {
+ maybePromise._attachCancellationCallback(
+ new FinallyHandlerCancelReaction(this));
+ }
+ }
+ return maybePromise._then(
+ succeed, fail, undefined, this, undefined);
+ }
+ }
+ }
+
+ if (promise.isRejected()) {
+ checkCancel(this);
+ errorObj.e = reasonOrValue;
+ return errorObj;
+ } else {
+ checkCancel(this);
+ return reasonOrValue;
+ }
+}
+
+Promise.prototype._passThrough = function(handler, type, success, fail) {
+ if (typeof handler !== "function") return this.then();
+ return this._then(success,
+ fail,
+ undefined,
+ new PassThroughHandlerContext(this, type, handler),
+ undefined);
+};
+
+Promise.prototype.lastly =
+Promise.prototype["finally"] = function (handler) {
+ return this._passThrough(handler,
+ 0,
+ finallyHandler,
+ finallyHandler);
+};
+
+Promise.prototype.tap = function (handler) {
+ return this._passThrough(handler, 1, finallyHandler);
+};
+
+return PassThroughHandlerContext;
+};
+
+},{"./util":36}],16:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise,
+ apiRejection,
+ INTERNAL,
+ tryConvertToPromise,
+ Proxyable,
+ debug) {
+var errors = _dereq_("./errors");
+var TypeError = errors.TypeError;
+var util = _dereq_("./util");
+var errorObj = util.errorObj;
+var tryCatch = util.tryCatch;
+var yieldHandlers = [];
+
+function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
+ for (var i = 0; i < yieldHandlers.length; ++i) {
+ traceParent._pushContext();
+ var result = tryCatch(yieldHandlers[i])(value);
+ traceParent._popContext();
+ if (result === errorObj) {
+ traceParent._pushContext();
+ var ret = Promise.reject(errorObj.e);
+ traceParent._popContext();
+ return ret;
+ }
+ var maybePromise = tryConvertToPromise(result, traceParent);
+ if (maybePromise instanceof Promise) return maybePromise;
+ }
+ return null;
+}
+
+function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
+ if (debug.cancellation()) {
+ var internal = new Promise(INTERNAL);
+ var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
+ this._promise = internal.lastly(function() {
+ return _finallyPromise;
+ });
+ internal._captureStackTrace();
+ internal._setOnCancel(this);
+ } else {
+ var promise = this._promise = new Promise(INTERNAL);
+ promise._captureStackTrace();
+ }
+ this._stack = stack;
+ this._generatorFunction = generatorFunction;
+ this._receiver = receiver;
+ this._generator = undefined;
+ this._yieldHandlers = typeof yieldHandler === "function"
+ ? [yieldHandler].concat(yieldHandlers)
+ : yieldHandlers;
+ this._yieldedPromise = null;
+ this._cancellationPhase = false;
+}
+util.inherits(PromiseSpawn, Proxyable);
+
+PromiseSpawn.prototype._isResolved = function() {
+ return this._promise === null;
+};
+
+PromiseSpawn.prototype._cleanup = function() {
+ this._promise = this._generator = null;
+ if (debug.cancellation() && this._finallyPromise !== null) {
+ this._finallyPromise._fulfill();
+ this._finallyPromise = null;
+ }
+};
+
+PromiseSpawn.prototype._promiseCancelled = function() {
+ if (this._isResolved()) return;
+ var implementsReturn = typeof this._generator["return"] !== "undefined";
+
+ var result;
+ if (!implementsReturn) {
+ var reason = new Promise.CancellationError(
+ "generator .return() sentinel");
+ Promise.coroutine.returnSentinel = reason;
+ this._promise._attachExtraTrace(reason);
+ this._promise._pushContext();
+ result = tryCatch(this._generator["throw"]).call(this._generator,
+ reason);
+ this._promise._popContext();
+ } else {
+ this._promise._pushContext();
+ result = tryCatch(this._generator["return"]).call(this._generator,
+ undefined);
+ this._promise._popContext();
+ }
+ this._cancellationPhase = true;
+ this._yieldedPromise = null;
+ this._continue(result);
+};
+
+PromiseSpawn.prototype._promiseFulfilled = function(value) {
+ this._yieldedPromise = null;
+ this._promise._pushContext();
+ var result = tryCatch(this._generator.next).call(this._generator, value);
+ this._promise._popContext();
+ this._continue(result);
+};
+
+PromiseSpawn.prototype._promiseRejected = function(reason) {
+ this._yieldedPromise = null;
+ this._promise._attachExtraTrace(reason);
+ this._promise._pushContext();
+ var result = tryCatch(this._generator["throw"])
+ .call(this._generator, reason);
+ this._promise._popContext();
+ this._continue(result);
+};
+
+PromiseSpawn.prototype._resultCancelled = function() {
+ if (this._yieldedPromise instanceof Promise) {
+ var promise = this._yieldedPromise;
+ this._yieldedPromise = null;
+ promise.cancel();
+ }
+};
+
+PromiseSpawn.prototype.promise = function () {
+ return this._promise;
+};
+
+PromiseSpawn.prototype._run = function () {
+ this._generator = this._generatorFunction.call(this._receiver);
+ this._receiver =
+ this._generatorFunction = undefined;
+ this._promiseFulfilled(undefined);
+};
+
+PromiseSpawn.prototype._continue = function (result) {
+ var promise = this._promise;
+ if (result === errorObj) {
+ this._cleanup();
+ if (this._cancellationPhase) {
+ return promise.cancel();
+ } else {
+ return promise._rejectCallback(result.e, false);
+ }
+ }
+
+ var value = result.value;
+ if (result.done === true) {
+ this._cleanup();
+ if (this._cancellationPhase) {
+ return promise.cancel();
+ } else {
+ return promise._resolveCallback(value);
+ }
+ } else {
+ var maybePromise = tryConvertToPromise(value, this._promise);
+ if (!(maybePromise instanceof Promise)) {
+ maybePromise =
+ promiseFromYieldHandler(maybePromise,
+ this._yieldHandlers,
+ this._promise);
+ if (maybePromise === null) {
+ this._promiseRejected(
+ new TypeError(
+ "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
+ "From coroutine:\u000a" +
+ this._stack.split("\n").slice(1, -7).join("\n")
+ )
+ );
+ return;
+ }
+ }
+ maybePromise = maybePromise._target();
+ var bitField = maybePromise._bitField;
+ ;
+ if (((bitField & 50397184) === 0)) {
+ this._yieldedPromise = maybePromise;
+ maybePromise._proxy(this, null);
+ } else if (((bitField & 33554432) !== 0)) {
+ Promise._async.invoke(
+ this._promiseFulfilled, this, maybePromise._value()
+ );
+ } else if (((bitField & 16777216) !== 0)) {
+ Promise._async.invoke(
+ this._promiseRejected, this, maybePromise._reason()
+ );
+ } else {
+ this._promiseCancelled();
+ }
+ }
+};
+
+Promise.coroutine = function (generatorFunction, options) {
+ if (typeof generatorFunction !== "function") {
+ throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ var yieldHandler = Object(options).yieldHandler;
+ var PromiseSpawn$ = PromiseSpawn;
+ var stack = new Error().stack;
+ return function () {
+ var generator = generatorFunction.apply(this, arguments);
+ var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
+ stack);
+ var ret = spawn.promise();
+ spawn._generator = generator;
+ spawn._promiseFulfilled(undefined);
+ return ret;
+ };
+};
+
+Promise.coroutine.addYieldHandler = function(fn) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ yieldHandlers.push(fn);
+};
+
+Promise.spawn = function (generatorFunction) {
+ debug.deprecated("Promise.spawn()", "Promise.coroutine()");
+ if (typeof generatorFunction !== "function") {
+ return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ var spawn = new PromiseSpawn(generatorFunction, this);
+ var ret = spawn.promise();
+ spawn._run(Promise.spawn);
+ return ret;
+};
+};
+
+},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
+"use strict";
+module.exports =
+function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
+ getDomain) {
+var util = _dereq_("./util");
+var canEvaluate = util.canEvaluate;
+var tryCatch = util.tryCatch;
+var errorObj = util.errorObj;
+var reject;
+
+if (!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);
+var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
+var nodebackForPromise = _dereq_("./nodeback");
+var errorObj = util.errorObj;
+var tryCatch = util.tryCatch;
+function check(self, executor) {
+ if (typeof executor !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(executor));
+ }
+ if (self.constructor !== Promise) {
+ throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+}
+
+function Promise(executor) {
+ this._bitField = 0;
+ this._fulfillmentHandler0 = undefined;
+ this._rejectionHandler0 = undefined;
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ if (executor !== INTERNAL) {
+ check(this, executor);
+ this._resolveFromExecutor(executor);
+ }
+ this._promiseCreated();
+ this._fireEvent("promiseCreated", this);
+}
+
+Promise.prototype.toString = function () {
+ return "[object Promise]";
+};
+
+Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
+ var len = arguments.length;
+ if (len > 1) {
+ var catchInstances = new Array(len - 1),
+ j = 0, i;
+ for (i = 0; i < len - 1; ++i) {
+ var item = arguments[i];
+ if (util.isObject(item)) {
+ catchInstances[j++] = item;
+ } else {
+ return apiRejection("expecting an object but got " +
+ "A catch statement predicate " + util.classString(item));
+ }
+ }
+ catchInstances.length = j;
+ fn = arguments[i];
+ return this.then(undefined, catchFilter(catchInstances, fn, this));
+ }
+ return this.then(undefined, fn);
+};
+
+Promise.prototype.reflect = function () {
+ return this._then(reflectHandler,
+ reflectHandler, undefined, this, undefined);
+};
+
+Promise.prototype.then = function (didFulfill, didReject) {
+ if (debug.warnings() && arguments.length > 0 &&
+ typeof didFulfill !== "function" &&
+ typeof didReject !== "function") {
+ var msg = ".then() only accepts functions but was passed: " +
+ util.classString(didFulfill);
+ if (arguments.length > 1) {
+ msg += ", " + util.classString(didReject);
+ }
+ this._warn(msg);
+ }
+ return this._then(didFulfill, didReject, undefined, undefined, undefined);
+};
+
+Promise.prototype.done = function (didFulfill, didReject) {
+ var promise =
+ this._then(didFulfill, didReject, undefined, undefined, undefined);
+ promise._setIsFinal();
+};
+
+Promise.prototype.spread = function (fn) {
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ return this.all()._then(fn, undefined, undefined, APPLY, undefined);
+};
+
+Promise.prototype.toJSON = function () {
+ var ret = {
+ isFulfilled: false,
+ isRejected: false,
+ fulfillmentValue: undefined,
+ rejectionReason: undefined
+ };
+ if (this.isFulfilled()) {
+ ret.fulfillmentValue = this.value();
+ ret.isFulfilled = true;
+ } else if (this.isRejected()) {
+ ret.rejectionReason = this.reason();
+ ret.isRejected = true;
+ }
+ return ret;
+};
+
+Promise.prototype.all = function () {
+ if (arguments.length > 0) {
+ this._warn(".all() was passed arguments but it does not take any");
+ }
+ return new PromiseArray(this).promise();
+};
+
+Promise.prototype.error = function (fn) {
+ return this.caught(util.originatesFromRejection, fn);
+};
+
+Promise.getNewLibraryCopy = module.exports;
+
+Promise.is = function (val) {
+ return val instanceof Promise;
+};
+
+Promise.fromNode = Promise.fromCallback = function(fn) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
+ : false;
+ var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
+ if (result === errorObj) {
+ ret._rejectCallback(result.e, true);
+ }
+ if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
+ return ret;
+};
+
+Promise.all = function (promises) {
+ return new PromiseArray(promises).promise();
+};
+
+Promise.cast = function (obj) {
+ var ret = tryConvertToPromise(obj);
+ if (!(ret instanceof Promise)) {
+ ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._setFulfilled();
+ ret._rejectionHandler0 = obj;
+ }
+ return ret;
+};
+
+Promise.resolve = Promise.fulfilled = Promise.cast;
+
+Promise.reject = Promise.rejected = function (reason) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._rejectCallback(reason, true);
+ return ret;
+};
+
+Promise.setScheduler = function(fn) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ return async.setScheduler(fn);
+};
+
+Promise.prototype._then = function (
+ didFulfill,
+ didReject,
+ _, receiver,
+ internalData
+) {
+ var haveInternalData = internalData !== undefined;
+ var promise = haveInternalData ? internalData : new Promise(INTERNAL);
+ var target = this._target();
+ var bitField = target._bitField;
+
+ if (!haveInternalData) {
+ promise._propagateFrom(this, 3);
+ promise._captureStackTrace();
+ if (receiver === undefined &&
+ ((this._bitField & 2097152) !== 0)) {
+ if (!((bitField & 50397184) === 0)) {
+ receiver = this._boundValue();
+ } else {
+ receiver = target === this ? undefined : this._boundTo;
+ }
+ }
+ this._fireEvent("promiseChained", this, promise);
+ }
+
+ var domain = getDomain();
+ if (!((bitField & 50397184) === 0)) {
+ var handler, value, settler = target._settlePromiseCtx;
+ if (((bitField & 33554432) !== 0)) {
+ value = target._rejectionHandler0;
+ handler = didFulfill;
+ } else if (((bitField & 16777216) !== 0)) {
+ value = target._fulfillmentHandler0;
+ handler = didReject;
+ target._unsetRejectionIsUnhandled();
+ } else {
+ settler = target._settlePromiseLateCancellationObserver;
+ value = new CancellationError("late cancellation observer");
+ target._attachExtraTrace(value);
+ handler = didReject;
+ }
+
+ async.invoke(settler, target, {
+ handler: domain === null ? handler
+ : (typeof handler === "function" &&
+ util.domainBind(domain, handler)),
+ promise: promise,
+ receiver: receiver,
+ value: value
+ });
+ } else {
+ target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
+ }
+
+ return promise;
+};
+
+Promise.prototype._length = function () {
+ return this._bitField & 65535;
+};
+
+Promise.prototype._isFateSealed = function () {
+ return (this._bitField & 117506048) !== 0;
+};
+
+Promise.prototype._isFollowing = function () {
+ return (this._bitField & 67108864) === 67108864;
+};
+
+Promise.prototype._setLength = function (len) {
+ this._bitField = (this._bitField & -65536) |
+ (len & 65535);
+};
+
+Promise.prototype._setFulfilled = function () {
+ this._bitField = this._bitField | 33554432;
+ this._fireEvent("promiseFulfilled", this);
+};
+
+Promise.prototype._setRejected = function () {
+ this._bitField = this._bitField | 16777216;
+ this._fireEvent("promiseRejected", this);
+};
+
+Promise.prototype._setFollowing = function () {
+ this._bitField = this._bitField | 67108864;
+ this._fireEvent("promiseResolved", this);
+};
+
+Promise.prototype._setIsFinal = function () {
+ this._bitField = this._bitField | 4194304;
+};
+
+Promise.prototype._isFinal = function () {
+ return (this._bitField & 4194304) > 0;
+};
+
+Promise.prototype._unsetCancelled = function() {
+ this._bitField = this._bitField & (~65536);
+};
+
+Promise.prototype._setCancelled = function() {
+ this._bitField = this._bitField | 65536;
+ this._fireEvent("promiseCancelled", this);
+};
+
+Promise.prototype._setWillBeCancelled = function() {
+ this._bitField = this._bitField | 8388608;
+};
+
+Promise.prototype._setAsyncGuaranteed = function() {
+ if (async.hasCustomScheduler()) return;
+ this._bitField = this._bitField | 134217728;
+};
+
+Promise.prototype._receiverAt = function (index) {
+ var ret = index === 0 ? this._receiver0 : this[
+ index * 4 - 4 + 3];
+ if (ret === UNDEFINED_BINDING) {
+ return undefined;
+ } else if (ret === undefined && this._isBound()) {
+ return this._boundValue();
+ }
+ return ret;
+};
+
+Promise.prototype._promiseAt = function (index) {
+ return this[
+ index * 4 - 4 + 2];
+};
+
+Promise.prototype._fulfillmentHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 0];
+};
+
+Promise.prototype._rejectionHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 1];
+};
+
+Promise.prototype._boundValue = function() {};
+
+Promise.prototype._migrateCallback0 = function (follower) {
+ var bitField = follower._bitField;
+ var fulfill = follower._fulfillmentHandler0;
+ var reject = follower._rejectionHandler0;
+ var promise = follower._promise0;
+ var receiver = follower._receiverAt(0);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._migrateCallbackAt = function (follower, index) {
+ var fulfill = follower._fulfillmentHandlerAt(index);
+ var reject = follower._rejectionHandlerAt(index);
+ var promise = follower._promiseAt(index);
+ var receiver = follower._receiverAt(index);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._addCallbacks = function (
+ fulfill,
+ reject,
+ promise,
+ receiver,
+ domain
+) {
+ var index = this._length();
+
+ if (index >= 65535 - 4) {
+ index = 0;
+ this._setLength(0);
+ }
+
+ if (index === 0) {
+ this._promise0 = promise;
+ this._receiver0 = receiver;
+ if (typeof fulfill === "function") {
+ this._fulfillmentHandler0 =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this._rejectionHandler0 =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ } else {
+ var base = index * 4 - 4;
+ this[base + 2] = promise;
+ this[base + 3] = receiver;
+ if (typeof fulfill === "function") {
+ this[base + 0] =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this[base + 1] =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ }
+ this._setLength(index + 1);
+ return index;
+};
+
+Promise.prototype._proxy = function (proxyable, arg) {
+ this._addCallbacks(undefined, undefined, arg, proxyable, null);
+};
+
+Promise.prototype._resolveCallback = function(value, shouldBind) {
+ if (((this._bitField & 117506048) !== 0)) return;
+ if (value === this)
+ return this._rejectCallback(makeSelfResolutionError(), false);
+ var maybePromise = tryConvertToPromise(value, this);
+ if (!(maybePromise instanceof Promise)) return this._fulfill(value);
+
+ if (shouldBind) this._propagateFrom(maybePromise, 2);
+
+ var promise = maybePromise._target();
+
+ if (promise === this) {
+ this._reject(makeSelfResolutionError());
+ return;
+ }
+
+ var bitField = promise._bitField;
+ if (((bitField & 50397184) === 0)) {
+ var len = this._length();
+ if (len > 0) promise._migrateCallback0(this);
+ for (var i = 1; i < len; ++i) {
+ promise._migrateCallbackAt(this, i);
+ }
+ this._setFollowing();
+ this._setLength(0);
+ this._setFollowee(promise);
+ } else if (((bitField & 33554432) !== 0)) {
+ this._fulfill(promise._value());
+ } else if (((bitField & 16777216) !== 0)) {
+ this._reject(promise._reason());
+ } else {
+ var reason = new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ this._reject(reason);
+ }
+};
+
+Promise.prototype._rejectCallback =
+function(reason, synchronous, ignoreNonErrorWarnings) {
+ var trace = util.ensureErrorObject(reason);
+ var hasStack = trace === reason;
+ if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
+ var message = "a promise was rejected with a non-error: " +
+ util.classString(reason);
+ this._warn(message, true);
+ }
+ this._attachExtraTrace(trace, synchronous ? hasStack : false);
+ this._reject(reason);
+};
+
+Promise.prototype._resolveFromExecutor = function (executor) {
+ var promise = this;
+ this._captureStackTrace();
+ this._pushContext();
+ var synchronous = true;
+ var r = this._execute(executor, function(value) {
+ promise._resolveCallback(value);
+ }, function (reason) {
+ promise._rejectCallback(reason, synchronous);
+ });
+ synchronous = false;
+ this._popContext();
+
+ if (r !== undefined) {
+ promise._rejectCallback(r, true);
+ }
+};
+
+Promise.prototype._settlePromiseFromHandler = function (
+ handler, receiver, value, promise
+) {
+ var bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+ promise._pushContext();
+ var x;
+ if (receiver === APPLY) {
+ if (!value || typeof value.length !== "number") {
+ x = errorObj;
+ x.e = new TypeError("cannot .spread() a non-array: " +
+ util.classString(value));
+ } else {
+ x = tryCatch(handler).apply(this._boundValue(), value);
+ }
+ } else {
+ x = tryCatch(handler).call(receiver, value);
+ }
+ var promiseCreated = promise._popContext();
+ bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+
+ if (x === NEXT_FILTER) {
+ promise._reject(value);
+ } else if (x === errorObj) {
+ promise._rejectCallback(x.e, false);
+ } else {
+ debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
+ promise._resolveCallback(x);
+ }
+};
+
+Promise.prototype._target = function() {
+ var ret = this;
+ while (ret._isFollowing()) ret = ret._followee();
+ return ret;
+};
+
+Promise.prototype._followee = function() {
+ return this._rejectionHandler0;
+};
+
+Promise.prototype._setFollowee = function(promise) {
+ this._rejectionHandler0 = promise;
+};
+
+Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
+ var isPromise = promise instanceof Promise;
+ var bitField = this._bitField;
+ var asyncGuaranteed = ((bitField & 134217728) !== 0);
+ if (((bitField & 65536) !== 0)) {
+ if (isPromise) promise._invokeInternalOnCancel();
+
+ if (receiver instanceof PassThroughHandlerContext &&
+ receiver.isFinallyHandler()) {
+ receiver.cancelPromise = promise;
+ if (tryCatch(handler).call(receiver, value) === errorObj) {
+ promise._reject(errorObj.e);
+ }
+ } else if (handler === reflectHandler) {
+ promise._fulfill(reflectHandler.call(receiver));
+ } else if (receiver instanceof Proxyable) {
+ receiver._promiseCancelled(promise);
+ } else if (isPromise || promise instanceof PromiseArray) {
+ promise._cancel();
+ } else {
+ receiver.cancel();
+ }
+ } else if (typeof handler === "function") {
+ if (!isPromise) {
+ handler.call(receiver, value, promise);
+ } else {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (receiver instanceof Proxyable) {
+ if (!receiver._isResolved()) {
+ if (((bitField & 33554432) !== 0)) {
+ receiver._promiseFulfilled(value, promise);
+ } else {
+ receiver._promiseRejected(value, promise);
+ }
+ }
+ } else if (isPromise) {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ if (((bitField & 33554432) !== 0)) {
+ promise._fulfill(value);
+ } else {
+ promise._reject(value);
+ }
+ }
+};
+
+Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
+ var handler = ctx.handler;
+ var promise = ctx.promise;
+ var receiver = ctx.receiver;
+ var value = ctx.value;
+ if (typeof handler === "function") {
+ if (!(promise instanceof Promise)) {
+ handler.call(receiver, value, promise);
+ } else {
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (promise instanceof Promise) {
+ promise._reject(value);
+ }
+};
+
+Promise.prototype._settlePromiseCtx = function(ctx) {
+ this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
+};
+
+Promise.prototype._settlePromise0 = function(handler, value, bitField) {
+ var promise = this._promise0;
+ var receiver = this._receiverAt(0);
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ this._settlePromise(promise, handler, receiver, value);
+};
+
+Promise.prototype._clearCallbackDataAtIndex = function(index) {
+ var base = index * 4 - 4;
+ this[base + 2] =
+ this[base + 3] =
+ this[base + 0] =
+ this[base + 1] = undefined;
+};
+
+Promise.prototype._fulfill = function (value) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ if (value === this) {
+ var err = makeSelfResolutionError();
+ this._attachExtraTrace(err);
+ return this._reject(err);
+ }
+ this._setFulfilled();
+ this._rejectionHandler0 = value;
+
+ if ((bitField & 65535) > 0) {
+ if (((bitField & 134217728) !== 0)) {
+ this._settlePromises();
+ } else {
+ async.settlePromises(this);
+ }
+ }
+};
+
+Promise.prototype._reject = function (reason) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ this._setRejected();
+ this._fulfillmentHandler0 = reason;
+
+ if (this._isFinal()) {
+ return async.fatalError(reason, util.isNode);
+ }
+
+ if ((bitField & 65535) > 0) {
+ async.settlePromises(this);
+ } else {
+ this._ensurePossibleRejectionHandled();
+ }
+};
+
+Promise.prototype._fulfillPromises = function (len, value) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._fulfillmentHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, value);
+ }
+};
+
+Promise.prototype._rejectPromises = function (len, reason) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._rejectionHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, reason);
+ }
+};
+
+Promise.prototype._settlePromises = function () {
+ var bitField = this._bitField;
+ var len = (bitField & 65535);
+
+ if (len > 0) {
+ if (((bitField & 16842752) !== 0)) {
+ var reason = this._fulfillmentHandler0;
+ this._settlePromise0(this._rejectionHandler0, reason, bitField);
+ this._rejectPromises(len, reason);
+ } else {
+ var value = this._rejectionHandler0;
+ this._settlePromise0(this._fulfillmentHandler0, value, bitField);
+ this._fulfillPromises(len, value);
+ }
+ this._setLength(0);
+ }
+ this._clearCancellationData();
+};
+
+Promise.prototype._settledValue = function() {
+ var bitField = this._bitField;
+ if (((bitField & 33554432) !== 0)) {
+ return this._rejectionHandler0;
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._fulfillmentHandler0;
+ }
+};
+
+function deferResolve(v) {this.promise._resolveCallback(v);}
+function deferReject(v) {this.promise._rejectCallback(v, false);}
+
+Promise.defer = Promise.pending = function() {
+ debug.deprecated("Promise.defer", "new Promise");
+ var promise = new Promise(INTERNAL);
+ return {
+ promise: promise,
+ resolve: deferResolve,
+ reject: deferReject
+ };
+};
+
+util.notEnumerableProp(Promise,
+ "_makeSelfResolutionError",
+ makeSelfResolutionError);
+
+_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
+ debug);
+_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
+_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
+_dereq_("./direct_resolve")(Promise);
+_dereq_("./synchronous_inspection")(Promise);
+_dereq_("./join")(
+ Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
+Promise.Promise = Promise;
+Promise.version = "3.4.6";
+_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
+_dereq_('./call_get.js')(Promise);
+_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
+_dereq_('./timers.js')(Promise, INTERNAL, debug);
+_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
+_dereq_('./nodeify.js')(Promise);
+_dereq_('./promisify.js')(Promise, INTERNAL);
+_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
+_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
+_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
+_dereq_('./settle.js')(Promise, PromiseArray, debug);
+_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
+_dereq_('./filter.js')(Promise, INTERNAL);
+_dereq_('./each.js')(Promise, INTERNAL);
+_dereq_('./any.js')(Promise);
+
+ util.toFastProperties(Promise);
+ util.toFastProperties(Promise.prototype);
+ function fillTypes(value) {
+ var p = new Promise(INTERNAL);
+ p._fulfillmentHandler0 = value;
+ p._rejectionHandler0 = value;
+ p._promise0 = value;
+ p._receiver0 = value;
+ }
+ // Complete slack tracking, opt out of field-type tracking and
+ // stabilize map
+ fillTypes({a: 1});
+ fillTypes({b: 2});
+ fillTypes({c: 3});
+ fillTypes(1);
+ fillTypes(function(){});
+ fillTypes(undefined);
+ fillTypes(false);
+ fillTypes(new Promise(INTERNAL));
+ debug.setBounds(Async.firstLineError, util.lastLineError);
+ return Promise;
+
+};
+
+},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL, tryConvertToPromise,
+ apiRejection, Proxyable) {
+var util = _dereq_("./util");
+var isArray = util.isArray;
+
+function toResolutionValue(val) {
+ switch(val) {
+ case -2: return [];
+ case -3: return {};
+ }
+}
+
+function PromiseArray(values) {
+ var promise = this._promise = new Promise(INTERNAL);
+ if (values instanceof Promise) {
+ promise._propagateFrom(values, 3);
+ }
+ promise._setOnCancel(this);
+ this._values = values;
+ this._length = 0;
+ this._totalResolved = 0;
+ this._init(undefined, -2);
+}
+util.inherits(PromiseArray, Proxyable);
+
+PromiseArray.prototype.length = function () {
+ return this._length;
+};
+
+PromiseArray.prototype.promise = function () {
+ return this._promise;
+};
+
+PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
+ var values = tryConvertToPromise(this._values, this._promise);
+ if (values instanceof Promise) {
+ values = values._target();
+ var bitField = values._bitField;
+ ;
+ this._values = values;
+
+ if (((bitField & 50397184) === 0)) {
+ this._promise._setAsyncGuaranteed();
+ return values._then(
+ init,
+ this._reject,
+ undefined,
+ this,
+ resolveValueIfEmpty
+ );
+ } else if (((bitField & 33554432) !== 0)) {
+ values = values._value();
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._reject(values._reason());
+ } else {
+ return this._cancel();
+ }
+ }
+ values = util.asArray(values);
+ if (values === null) {
+ var err = apiRejection(
+ "expecting an array or an iterable object but got " + util.classString(values)).reason();
+ this._promise._rejectCallback(err, false);
+ return;
+ }
+
+ if (values.length === 0) {
+ if (resolveValueIfEmpty === -5) {
+ this._resolveEmptyArray();
+ }
+ else {
+ this._resolve(toResolutionValue(resolveValueIfEmpty));
+ }
+ return;
+ }
+ this._iterate(values);
+};
+
+PromiseArray.prototype._iterate = function(values) {
+ var len = this.getActualLength(values.length);
+ this._length = len;
+ this._values = this.shouldCopyValues() ? new Array(len) : this._values;
+ var result = this._promise;
+ var isResolved = false;
+ var bitField = null;
+ for (var i = 0; i < len; ++i) {
+ var maybePromise = tryConvertToPromise(values[i], result);
+
+ if (maybePromise instanceof Promise) {
+ maybePromise = maybePromise._target();
+ bitField = maybePromise._bitField;
+ } else {
+ bitField = null;
+ }
+
+ if (isResolved) {
+ if (bitField !== null) {
+ maybePromise.suppressUnhandledRejections();
+ }
+ } else if (bitField !== null) {
+ if (((bitField & 50397184) === 0)) {
+ maybePromise._proxy(this, i);
+ this._values[i] = maybePromise;
+ } else if (((bitField & 33554432) !== 0)) {
+ isResolved = this._promiseFulfilled(maybePromise._value(), i);
+ } else if (((bitField & 16777216) !== 0)) {
+ isResolved = this._promiseRejected(maybePromise._reason(), i);
+ } else {
+ isResolved = this._promiseCancelled(i);
+ }
+ } else {
+ isResolved = this._promiseFulfilled(maybePromise, i);
+ }
+ }
+ if (!isResolved) result._setAsyncGuaranteed();
+};
+
+PromiseArray.prototype._isResolved = function () {
+ return this._values === null;
+};
+
+PromiseArray.prototype._resolve = function (value) {
+ this._values = null;
+ this._promise._fulfill(value);
+};
+
+PromiseArray.prototype._cancel = function() {
+ if (this._isResolved() || !this._promise._isCancellable()) return;
+ this._values = null;
+ this._promise._cancel();
+};
+
+PromiseArray.prototype._reject = function (reason) {
+ this._values = null;
+ this._promise._rejectCallback(reason, false);
+};
+
+PromiseArray.prototype._promiseFulfilled = function (value, index) {
+ this._values[index] = value;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ this._resolve(this._values);
+ return true;
+ }
+ return false;
+};
+
+PromiseArray.prototype._promiseCancelled = function() {
+ this._cancel();
+ return true;
+};
+
+PromiseArray.prototype._promiseRejected = function (reason) {
+ this._totalResolved++;
+ this._reject(reason);
+ return true;
+};
+
+PromiseArray.prototype._resultCancelled = function() {
+ if (this._isResolved()) return;
+ var values = this._values;
+ this._cancel();
+ if (values instanceof Promise) {
+ values.cancel();
+ } else {
+ for (var i = 0; i < values.length; ++i) {
+ if (values[i] instanceof Promise) {
+ values[i].cancel();
+ }
+ }
+ }
+};
+
+PromiseArray.prototype.shouldCopyValues = function () {
+ return true;
+};
+
+PromiseArray.prototype.getActualLength = function (len) {
+ return len;
+};
+
+return PromiseArray;
+};
+
+},{"./util":36}],24:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var THIS = {};
+var util = _dereq_("./util");
+var nodebackForPromise = _dereq_("./nodeback");
+var withAppended = util.withAppended;
+var maybeWrapAsError = util.maybeWrapAsError;
+var canEvaluate = util.canEvaluate;
+var TypeError = _dereq_("./errors").TypeError;
+var defaultSuffix = "Async";
+var defaultPromisified = {__isPromisified__: true};
+var noCopyProps = [
+ "arity", "length",
+ "name",
+ "arguments",
+ "caller",
+ "callee",
+ "prototype",
+ "__isPromisified__"
+];
+var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
+
+var defaultFilter = function(name) {
+ return util.isIdentifier(name) &&
+ name.charAt(0) !== "_" &&
+ name !== "constructor";
+};
+
+function propsFilter(key) {
+ return !noCopyPropsPattern.test(key);
+}
+
+function isPromisified(fn) {
+ try {
+ return fn.__isPromisified__ === true;
+ }
+ catch (e) {
+ return false;
+ }
+}
+
+function hasPromisified(obj, key, suffix) {
+ var val = util.getDataPropertyOrDefault(obj, key + suffix,
+ defaultPromisified);
+ return val ? isPromisified(val) : false;
+}
+function checkValid(ret, suffix, suffixRegexp) {
+ for (var i = 0; i < ret.length; i += 2) {
+ var key = ret[i];
+ if (suffixRegexp.test(key)) {
+ var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
+ for (var j = 0; j < ret.length; j += 2) {
+ if (ret[j] === keyWithoutAsyncSuffix) {
+ throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
+ .replace("%s", suffix));
+ }
+ }
+ }
+ }
+}
+
+function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
+ var keys = util.inheritedDataKeys(obj);
+ var ret = [];
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ var value = obj[key];
+ var passesDefaultFilter = filter === defaultFilter
+ ? true : defaultFilter(key, value, obj);
+ if (typeof value === "function" &&
+ !isPromisified(value) &&
+ !hasPromisified(obj, key, suffix) &&
+ filter(key, value, obj, passesDefaultFilter)) {
+ ret.push(key, value);
+ }
+ }
+ checkValid(ret, suffix, suffixRegexp);
+ return ret;
+}
+
+var escapeIdentRegex = function(str) {
+ return str.replace(/([$])/, "\\$");
+};
+
+var makeNodePromisifiedEval;
+if (!true) {
+var switchCaseArgumentOrder = function(likelyArgumentCount) {
+ var ret = [likelyArgumentCount];
+ var min = Math.max(0, likelyArgumentCount - 1 - 3);
+ for(var i = likelyArgumentCount - 1; i >= min; --i) {
+ ret.push(i);
+ }
+ for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
+ ret.push(i);
+ }
+ return ret;
+};
+
+var argumentSequence = function(argumentCount) {
+ return util.filledRange(argumentCount, "_arg", "");
+};
+
+var parameterDeclaration = function(parameterCount) {
+ return util.filledRange(
+ Math.max(parameterCount, 3), "_arg", "");
+};
+
+var parameterCount = function(fn) {
+ if (typeof fn.length === "number") {
+ return Math.max(Math.min(fn.length, 1023 + 1), 0);
+ }
+ return 0;
+};
+
+makeNodePromisifiedEval =
+function(callback, receiver, originalName, fn, _, multiArgs) {
+ var newParameterCount = Math.max(0, parameterCount(fn) - 1);
+ var argumentOrder = switchCaseArgumentOrder(newParameterCount);
+ var shouldProxyThis = typeof callback === "string" || receiver === THIS;
+
+ function generateCallForArgumentCount(count) {
+ var args = argumentSequence(count).join(", ");
+ var comma = count > 0 ? ", " : "";
+ var ret;
+ if (shouldProxyThis) {
+ ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
+ } else {
+ ret = receiver === undefined
+ ? "ret = callback({{args}}, nodeback); break;\n"
+ : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
+ }
+ return ret.replace("{{args}}", args).replace(", ", comma);
+ }
+
+ function generateArgumentSwitchCase() {
+ var ret = "";
+ for (var i = 0; i < argumentOrder.length; ++i) {
+ ret += "case " + argumentOrder[i] +":" +
+ generateCallForArgumentCount(argumentOrder[i]);
+ }
+
+ ret += " \n\
+ default: \n\
+ var args = new Array(len + 1); \n\
+ var i = 0; \n\
+ for (var i = 0; i < len; ++i) { \n\
+ args[i] = arguments[i]; \n\
+ } \n\
+ args[i] = nodeback; \n\
+ [CodeForCall] \n\
+ break; \n\
+ ".replace("[CodeForCall]", (shouldProxyThis
+ ? "ret = callback.apply(this, args);\n"
+ : "ret = callback.apply(receiver, args);\n"));
+ return ret;
+ }
+
+ var getFunctionCode = typeof callback === "string"
+ ? ("this != null ? this['"+callback+"'] : fn")
+ : "fn";
+ var body = "'use strict'; \n\
+ var ret = function (Parameters) { \n\
+ 'use strict'; \n\
+ var len = arguments.length; \n\
+ var promise = new Promise(INTERNAL); \n\
+ promise._captureStackTrace(); \n\
+ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
+ var ret; \n\
+ var callback = tryCatch([GetFunctionCode]); \n\
+ switch(len) { \n\
+ [CodeForSwitchCase] \n\
+ } \n\
+ if (ret === errorObj) { \n\
+ promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
+ } \n\
+ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
+ return promise; \n\
+ }; \n\
+ notEnumerableProp(ret, '__isPromisified__', true); \n\
+ return ret; \n\
+ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
+ .replace("[GetFunctionCode]", getFunctionCode);
+ body = body.replace("Parameters", parameterDeclaration(newParameterCount));
+ return new Function("Promise",
+ "fn",
+ "receiver",
+ "withAppended",
+ "maybeWrapAsError",
+ "nodebackForPromise",
+ "tryCatch",
+ "errorObj",
+ "notEnumerableProp",
+ "INTERNAL",
+ body)(
+ Promise,
+ fn,
+ receiver,
+ withAppended,
+ maybeWrapAsError,
+ nodebackForPromise,
+ util.tryCatch,
+ util.errorObj,
+ util.notEnumerableProp,
+ INTERNAL);
+};
+}
+
+function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
+ var defaultThis = (function() {return this;})();
+ var method = callback;
+ if (typeof method === "string") {
+ callback = fn;
+ }
+ function promisified() {
+ var _receiver = receiver;
+ if (receiver === THIS) _receiver = this;
+ var promise = new Promise(INTERNAL);
+ promise._captureStackTrace();
+ var cb = typeof method === "string" && this !== defaultThis
+ ? this[method] : callback;
+ var fn = nodebackForPromise(promise, multiArgs);
+ try {
+ cb.apply(_receiver, withAppended(arguments, fn));
+ } catch(e) {
+ promise._rejectCallback(maybeWrapAsError(e), true, true);
+ }
+ if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
+ return promise;
+ }
+ util.notEnumerableProp(promisified, "__isPromisified__", true);
+ return promisified;
+}
+
+var makeNodePromisified = canEvaluate
+ ? makeNodePromisifiedEval
+ : makeNodePromisifiedClosure;
+
+function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
+ var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
+ var methods =
+ promisifiableMethods(obj, suffix, suffixRegexp, filter);
+
+ for (var i = 0, len = methods.length; i < len; i+= 2) {
+ var key = methods[i];
+ var fn = methods[i+1];
+ var promisifiedKey = key + suffix;
+ if (promisifier === makeNodePromisified) {
+ obj[promisifiedKey] =
+ makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
+ } else {
+ var promisified = promisifier(fn, function() {
+ return makeNodePromisified(key, THIS, key,
+ fn, suffix, multiArgs);
+ });
+ util.notEnumerableProp(promisified, "__isPromisified__", true);
+ obj[promisifiedKey] = promisified;
+ }
+ }
+ util.toFastProperties(obj);
+ return obj;
+}
+
+function promisify(callback, receiver, multiArgs) {
+ return makeNodePromisified(callback, receiver, undefined,
+ callback, null, multiArgs);
+}
+
+Promise.promisify = function (fn, options) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ if (isPromisified(fn)) {
+ return fn;
+ }
+ options = Object(options);
+ var receiver = options.context === undefined ? THIS : options.context;
+ var multiArgs = !!options.multiArgs;
+ var ret = promisify(fn, receiver, multiArgs);
+ util.copyDescriptors(fn, ret, propsFilter);
+ return ret;
+};
+
+Promise.promisifyAll = function (target, options) {
+ if (typeof target !== "function" && typeof target !== "object") {
+ throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ options = Object(options);
+ var multiArgs = !!options.multiArgs;
+ var suffix = options.suffix;
+ if (typeof suffix !== "string") suffix = defaultSuffix;
+ var filter = options.filter;
+ if (typeof filter !== "function") filter = defaultFilter;
+ var promisifier = options.promisifier;
+ if (typeof promisifier !== "function") promisifier = makeNodePromisified;
+
+ if (!util.isIdentifier(suffix)) {
+ throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+
+ var keys = util.inheritedDataKeys(target);
+ for (var i = 0; i < keys.length; ++i) {
+ var value = target[keys[i]];
+ if (keys[i] !== "constructor" &&
+ util.isClass(value)) {
+ promisifyAll(value.prototype, suffix, filter, promisifier,
+ multiArgs);
+ promisifyAll(value, suffix, filter, promisifier, multiArgs);
+ }
+ }
+
+ return promisifyAll(target, suffix, filter, promisifier, multiArgs);
+};
+};
+
+
+},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(
+ Promise, PromiseArray, tryConvertToPromise, apiRejection) {
+var util = _dereq_("./util");
+var isObject = util.isObject;
+var es5 = _dereq_("./es5");
+var Es6Map;
+if (typeof Map === "function") Es6Map = Map;
+
+var mapToEntries = (function() {
+ var index = 0;
+ var size = 0;
+
+ function extractEntry(value, key) {
+ this[index] = value;
+ this[index + size] = key;
+ index++;
+ }
+
+ return function mapToEntries(map) {
+ size = map.size;
+ index = 0;
+ var ret = new Array(map.size * 2);
+ map.forEach(extractEntry, ret);
+ return ret;
+ };
+})();
+
+var entriesToMap = function(entries) {
+ var ret = new Es6Map();
+ var length = entries.length / 2 | 0;
+ for (var i = 0; i < length; ++i) {
+ var key = entries[length + i];
+ var value = entries[i];
+ ret.set(key, value);
+ }
+ return ret;
+};
+
+function PropertiesPromiseArray(obj) {
+ var isMap = false;
+ var entries;
+ if (Es6Map !== undefined && obj instanceof Es6Map) {
+ entries = mapToEntries(obj);
+ isMap = true;
+ } else {
+ var keys = es5.keys(obj);
+ var len = keys.length;
+ entries = new Array(len * 2);
+ for (var i = 0; i < len; ++i) {
+ var key = keys[i];
+ entries[i] = obj[key];
+ entries[i + len] = key;
+ }
+ }
+ this.constructor$(entries);
+ this._isMap = isMap;
+ this._init$(undefined, -3);
+}
+util.inherits(PropertiesPromiseArray, PromiseArray);
+
+PropertiesPromiseArray.prototype._init = function () {};
+
+PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
+ this._values[index] = value;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ var val;
+ if (this._isMap) {
+ val = entriesToMap(this._values);
+ } else {
+ val = {};
+ var keyOffset = this.length();
+ for (var i = 0, len = this.length(); i < len; ++i) {
+ val[this._values[i + keyOffset]] = this._values[i];
+ }
+ }
+ this._resolve(val);
+ return true;
+ }
+ return false;
+};
+
+PropertiesPromiseArray.prototype.shouldCopyValues = function () {
+ return false;
+};
+
+PropertiesPromiseArray.prototype.getActualLength = function (len) {
+ return len >> 1;
+};
+
+function props(promises) {
+ var ret;
+ var castValue = tryConvertToPromise(promises);
+
+ if (!isObject(castValue)) {
+ return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ } else if (castValue instanceof Promise) {
+ ret = castValue._then(
+ Promise.props, undefined, undefined, undefined, undefined);
+ } else {
+ ret = new PropertiesPromiseArray(castValue).promise();
+ }
+
+ if (castValue instanceof Promise) {
+ ret._propagateFrom(castValue, 2);
+ }
+ return ret;
+}
+
+Promise.prototype.props = function () {
+ return props(this);
+};
+
+Promise.props = function (promises) {
+ return props(promises);
+};
+};
+
+},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
+"use strict";
+function arrayMove(src, srcIndex, dst, dstIndex, len) {
+ for (var j = 0; j < len; ++j) {
+ dst[j + dstIndex] = src[j + srcIndex];
+ src[j + srcIndex] = void 0;
+ }
+}
+
+function Queue(capacity) {
+ this._capacity = capacity;
+ this._length = 0;
+ this._front = 0;
+}
+
+Queue.prototype._willBeOverCapacity = function (size) {
+ return this._capacity < size;
+};
+
+Queue.prototype._pushOne = function (arg) {
+ var length = this.length();
+ this._checkCapacity(length + 1);
+ var i = (this._front + length) & (this._capacity - 1);
+ this[i] = arg;
+ this._length = length + 1;
+};
+
+Queue.prototype._unshiftOne = function(value) {
+ var capacity = this._capacity;
+ this._checkCapacity(this.length() + 1);
+ var front = this._front;
+ var i = (((( front - 1 ) &
+ ( capacity - 1) ) ^ capacity ) - capacity );
+ this[i] = value;
+ this._front = i;
+ this._length = this.length() + 1;
+};
+
+Queue.prototype.unshift = function(fn, receiver, arg) {
+ this._unshiftOne(arg);
+ this._unshiftOne(receiver);
+ this._unshiftOne(fn);
+};
+
+Queue.prototype.push = function (fn, receiver, arg) {
+ var length = this.length() + 3;
+ if (this._willBeOverCapacity(length)) {
+ this._pushOne(fn);
+ this._pushOne(receiver);
+ this._pushOne(arg);
+ return;
+ }
+ var j = this._front + length - 3;
+ this._checkCapacity(length);
+ var wrapMask = this._capacity - 1;
+ this[(j + 0) & wrapMask] = fn;
+ this[(j + 1) & wrapMask] = receiver;
+ this[(j + 2) & wrapMask] = arg;
+ this._length = length;
+};
+
+Queue.prototype.shift = function () {
+ var front = this._front,
+ ret = this[front];
+
+ this[front] = undefined;
+ this._front = (front + 1) & (this._capacity - 1);
+ this._length--;
+ return ret;
+};
+
+Queue.prototype.length = function () {
+ return this._length;
+};
+
+Queue.prototype._checkCapacity = function (size) {
+ if (this._capacity < size) {
+ this._resizeTo(this._capacity << 1);
+ }
+};
+
+Queue.prototype._resizeTo = function (capacity) {
+ var oldCapacity = this._capacity;
+ this._capacity = capacity;
+ var front = this._front;
+ var length = this._length;
+ var moveItemsCount = (front + length) & (oldCapacity - 1);
+ arrayMove(this, 0, this, oldCapacity, moveItemsCount);
+};
+
+module.exports = Queue;
+
+},{}],27:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(
+ Promise, INTERNAL, tryConvertToPromise, apiRejection) {
+var util = _dereq_("./util");
+
+var raceLater = function (promise) {
+ return promise.then(function(array) {
+ return race(array, promise);
+ });
+};
+
+function race(promises, parent) {
+ var maybePromise = tryConvertToPromise(promises);
+
+ if (maybePromise instanceof Promise) {
+ return raceLater(maybePromise);
+ } else {
+ promises = util.asArray(promises);
+ if (promises === null)
+ return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
+ }
+
+ var ret = new Promise(INTERNAL);
+ if (parent !== undefined) {
+ ret._propagateFrom(parent, 3);
+ }
+ var fulfill = ret._fulfill;
+ var reject = ret._reject;
+ for (var i = 0, len = promises.length; i < len; ++i) {
+ var val = promises[i];
+
+ if (val === undefined && !(i in promises)) {
+ continue;
+ }
+
+ Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
+ }
+ return ret;
+}
+
+Promise.race = function (promises) {
+ return race(promises, undefined);
+};
+
+Promise.prototype.race = function () {
+ return race(this, undefined);
+};
+
+};
+
+},{"./util":36}],28:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise,
+ PromiseArray,
+ apiRejection,
+ tryConvertToPromise,
+ INTERNAL,
+ debug) {
+var getDomain = Promise._getDomain;
+var util = _dereq_("./util");
+var tryCatch = util.tryCatch;
+
+function ReductionPromiseArray(promises, fn, initialValue, _each) {
+ this.constructor$(promises);
+ var domain = getDomain();
+ this._fn = domain === null ? fn : util.domainBind(domain, fn);
+ if (initialValue !== undefined) {
+ initialValue = Promise.resolve(initialValue);
+ initialValue._attachCancellationCallback(this);
+ }
+ this._initialValue = initialValue;
+ this._currentCancellable = null;
+ if(_each === INTERNAL) {
+ this._eachValues = Array(this._length);
+ } else if (_each === 0) {
+ this._eachValues = null;
+ } else {
+ this._eachValues = undefined;
+ }
+ this._promise._captureStackTrace();
+ this._init$(undefined, -5);
+}
+util.inherits(ReductionPromiseArray, PromiseArray);
+
+ReductionPromiseArray.prototype._gotAccum = function(accum) {
+ if (this._eachValues !== undefined &&
+ this._eachValues !== null &&
+ accum !== INTERNAL) {
+ this._eachValues.push(accum);
+ }
+};
+
+ReductionPromiseArray.prototype._eachComplete = function(value) {
+ if (this._eachValues !== null) {
+ this._eachValues.push(value);
+ }
+ return this._eachValues;
+};
+
+ReductionPromiseArray.prototype._init = function() {};
+
+ReductionPromiseArray.prototype._resolveEmptyArray = function() {
+ this._resolve(this._eachValues !== undefined ? this._eachValues
+ : this._initialValue);
+};
+
+ReductionPromiseArray.prototype.shouldCopyValues = function () {
+ return false;
+};
+
+ReductionPromiseArray.prototype._resolve = function(value) {
+ this._promise._resolveCallback(value);
+ this._values = null;
+};
+
+ReductionPromiseArray.prototype._resultCancelled = function(sender) {
+ if (sender === this._initialValue) return this._cancel();
+ if (this._isResolved()) return;
+ this._resultCancelled$();
+ if (this._currentCancellable instanceof Promise) {
+ this._currentCancellable.cancel();
+ }
+ if (this._initialValue instanceof Promise) {
+ this._initialValue.cancel();
+ }
+};
+
+ReductionPromiseArray.prototype._iterate = function (values) {
+ this._values = values;
+ var value;
+ var i;
+ var length = values.length;
+ if (this._initialValue !== undefined) {
+ value = this._initialValue;
+ i = 0;
+ } else {
+ value = Promise.resolve(values[0]);
+ i = 1;
+ }
+
+ this._currentCancellable = value;
+
+ if (!value.isRejected()) {
+ for (; i < length; ++i) {
+ var ctx = {
+ accum: null,
+ value: values[i],
+ index: i,
+ length: length,
+ array: this
+ };
+ value = value._then(gotAccum, undefined, undefined, ctx, undefined);
+ }
+ }
+
+ if (this._eachValues !== undefined) {
+ value = value
+ ._then(this._eachComplete, undefined, undefined, this, undefined);
+ }
+ value._then(completed, completed, undefined, value, this);
+};
+
+Promise.prototype.reduce = function (fn, initialValue) {
+ return reduce(this, fn, initialValue, null);
+};
+
+Promise.reduce = function (promises, fn, initialValue, _each) {
+ return reduce(promises, fn, initialValue, _each);
+};
+
+function completed(valueOrReason, array) {
+ if (this.isFulfilled()) {
+ array._resolve(valueOrReason);
+ } else {
+ array._reject(valueOrReason);
+ }
+}
+
+function reduce(promises, fn, initialValue, _each) {
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
+ return array.promise();
+}
+
+function gotAccum(accum) {
+ this.accum = accum;
+ this.array._gotAccum(accum);
+ var value = tryConvertToPromise(this.value, this.array._promise);
+ if (value instanceof Promise) {
+ this.array._currentCancellable = value;
+ return value._then(gotValue, undefined, undefined, this, undefined);
+ } else {
+ return gotValue.call(this, value);
+ }
+}
+
+function gotValue(value) {
+ var array = this.array;
+ var promise = array._promise;
+ var fn = tryCatch(array._fn);
+ promise._pushContext();
+ var ret;
+ if (array._eachValues !== undefined) {
+ ret = fn.call(promise._boundValue(), value, this.index, this.length);
+ } else {
+ ret = fn.call(promise._boundValue(),
+ this.accum, value, this.index, this.length);
+ }
+ if (ret instanceof Promise) {
+ array._currentCancellable = ret;
+ }
+ var promiseCreated = promise._popContext();
+ debug.checkForgottenReturns(
+ ret,
+ promiseCreated,
+ array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
+ promise
+ );
+ return ret;
+}
+};
+
+},{"./util":36}],29:[function(_dereq_,module,exports){
+"use strict";
+var util = _dereq_("./util");
+var schedule;
+var noAsyncScheduler = function() {
+ throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+};
+var NativePromise = util.getNativePromise();
+if (util.isNode && typeof MutationObserver === "undefined") {
+ var GlobalSetImmediate = global.setImmediate;
+ var ProcessNextTick = process.nextTick;
+ schedule = util.isRecentNode
+ ? function(fn) { GlobalSetImmediate.call(global, fn); }
+ : function(fn) { ProcessNextTick.call(process, fn); };
+} else if (typeof NativePromise === "function" &&
+ typeof NativePromise.resolve === "function") {
+ var nativePromise = NativePromise.resolve();
+ schedule = function(fn) {
+ nativePromise.then(fn);
+ };
+} else if ((typeof MutationObserver !== "undefined") &&
+ !(typeof window !== "undefined" &&
+ window.navigator &&
+ (window.navigator.standalone || window.cordova))) {
+ schedule = (function() {
+ var div = document.createElement("div");
+ var opts = {attributes: true};
+ var toggleScheduled = false;
+ var div2 = document.createElement("div");
+ var o2 = new MutationObserver(function() {
+ div.classList.toggle("foo");
+ toggleScheduled = false;
+ });
+ o2.observe(div2, opts);
+
+ var scheduleToggle = function() {
+ if (toggleScheduled) return;
+ toggleScheduled = true;
+ div2.classList.toggle("foo");
+ };
+
+ return function schedule(fn) {
+ var o = new MutationObserver(function() {
+ o.disconnect();
+ fn();
+ });
+ o.observe(div, opts);
+ scheduleToggle();
+ };
+ })();
+} else if (typeof setImmediate !== "undefined") {
+ schedule = function (fn) {
+ setImmediate(fn);
+ };
+} else if (typeof setTimeout !== "undefined") {
+ schedule = function (fn) {
+ setTimeout(fn, 0);
+ };
+} else {
+ schedule = noAsyncScheduler;
+}
+module.exports = schedule;
+
+},{"./util":36}],30:[function(_dereq_,module,exports){
+"use strict";
+module.exports =
+ function(Promise, PromiseArray, debug) {
+var PromiseInspection = Promise.PromiseInspection;
+var util = _dereq_("./util");
+
+function SettledPromiseArray(values) {
+ this.constructor$(values);
+}
+util.inherits(SettledPromiseArray, PromiseArray);
+
+SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
+ this._values[index] = inspection;
+ var totalResolved = ++this._totalResolved;
+ if (totalResolved >= this._length) {
+ this._resolve(this._values);
+ return true;
+ }
+ return false;
+};
+
+SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
+ var ret = new PromiseInspection();
+ ret._bitField = 33554432;
+ ret._settledValueField = value;
+ return this._promiseResolved(index, ret);
+};
+SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
+ var ret = new PromiseInspection();
+ ret._bitField = 16777216;
+ ret._settledValueField = reason;
+ return this._promiseResolved(index, ret);
+};
+
+Promise.settle = function (promises) {
+ debug.deprecated(".settle()", ".reflect()");
+ return new SettledPromiseArray(promises).promise();
+};
+
+Promise.prototype.settle = function () {
+ return Promise.settle(this);
+};
+};
+
+},{"./util":36}],31:[function(_dereq_,module,exports){
+"use strict";
+module.exports =
+function(Promise, PromiseArray, apiRejection) {
+var util = _dereq_("./util");
+var RangeError = _dereq_("./errors").RangeError;
+var AggregateError = _dereq_("./errors").AggregateError;
+var isArray = util.isArray;
+var CANCELLATION = {};
+
+
+function SomePromiseArray(values) {
+ this.constructor$(values);
+ this._howMany = 0;
+ this._unwrap = false;
+ this._initialized = false;
+}
+util.inherits(SomePromiseArray, PromiseArray);
+
+SomePromiseArray.prototype._init = function () {
+ if (!this._initialized) {
+ return;
+ }
+ if (this._howMany === 0) {
+ this._resolve([]);
+ return;
+ }
+ this._init$(undefined, -5);
+ var isArrayResolved = isArray(this._values);
+ if (!this._isResolved() &&
+ isArrayResolved &&
+ this._howMany > this._canPossiblyFulfill()) {
+ this._reject(this._getRangeError(this.length()));
+ }
+};
+
+SomePromiseArray.prototype.init = function () {
+ this._initialized = true;
+ this._init();
+};
+
+SomePromiseArray.prototype.setUnwrap = function () {
+ this._unwrap = true;
+};
+
+SomePromiseArray.prototype.howMany = function () {
+ return this._howMany;
+};
+
+SomePromiseArray.prototype.setHowMany = function (count) {
+ this._howMany = count;
+};
+
+SomePromiseArray.prototype._promiseFulfilled = function (value) {
+ this._addFulfilled(value);
+ if (this._fulfilled() === this.howMany()) {
+ this._values.length = this.howMany();
+ if (this.howMany() === 1 && this._unwrap) {
+ this._resolve(this._values[0]);
+ } else {
+ this._resolve(this._values);
+ }
+ return true;
+ }
+ return false;
+
+};
+SomePromiseArray.prototype._promiseRejected = function (reason) {
+ this._addRejected(reason);
+ return this._checkOutcome();
+};
+
+SomePromiseArray.prototype._promiseCancelled = function () {
+ if (this._values instanceof Promise || this._values == null) {
+ return this._cancel();
+ }
+ this._addRejected(CANCELLATION);
+ return this._checkOutcome();
+};
+
+SomePromiseArray.prototype._checkOutcome = function() {
+ if (this.howMany() > this._canPossiblyFulfill()) {
+ var e = new AggregateError();
+ for (var i = this.length(); i < this._values.length; ++i) {
+ if (this._values[i] !== CANCELLATION) {
+ e.push(this._values[i]);
+ }
+ }
+ if (e.length > 0) {
+ this._reject(e);
+ } else {
+ this._cancel();
+ }
+ return true;
+ }
+ return false;
+};
+
+SomePromiseArray.prototype._fulfilled = function () {
+ return this._totalResolved;
+};
+
+SomePromiseArray.prototype._rejected = function () {
+ return this._values.length - this.length();
+};
+
+SomePromiseArray.prototype._addRejected = function (reason) {
+ this._values.push(reason);
+};
+
+SomePromiseArray.prototype._addFulfilled = function (value) {
+ this._values[this._totalResolved++] = value;
+};
+
+SomePromiseArray.prototype._canPossiblyFulfill = function () {
+ return this.length() - this._rejected();
+};
+
+SomePromiseArray.prototype._getRangeError = function (count) {
+ var message = "Input array must contain at least " +
+ this._howMany + " items but contains only " + count + " items";
+ return new RangeError(message);
+};
+
+SomePromiseArray.prototype._resolveEmptyArray = function () {
+ this._reject(this._getRangeError(0));
+};
+
+function some(promises, howMany) {
+ if ((howMany | 0) !== howMany || howMany < 0) {
+ return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ var ret = new SomePromiseArray(promises);
+ var promise = ret.promise();
+ ret.setHowMany(howMany);
+ ret.init();
+ return promise;
+}
+
+Promise.some = function (promises, howMany) {
+ return some(promises, howMany);
+};
+
+Promise.prototype.some = function (howMany) {
+ return some(this, howMany);
+};
+
+Promise._SomePromiseArray = SomePromiseArray;
+};
+
+},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise) {
+function PromiseInspection(promise) {
+ if (promise !== undefined) {
+ promise = promise._target();
+ this._bitField = promise._bitField;
+ this._settledValueField = promise._isFateSealed()
+ ? promise._settledValue() : undefined;
+ }
+ else {
+ this._bitField = 0;
+ this._settledValueField = undefined;
+ }
+}
+
+PromiseInspection.prototype._settledValue = function() {
+ return this._settledValueField;
+};
+
+var value = PromiseInspection.prototype.value = function () {
+ if (!this.isFulfilled()) {
+ throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ return this._settledValue();
+};
+
+var reason = PromiseInspection.prototype.error =
+PromiseInspection.prototype.reason = function () {
+ if (!this.isRejected()) {
+ throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ return this._settledValue();
+};
+
+var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
+ return (this._bitField & 33554432) !== 0;
+};
+
+var isRejected = PromiseInspection.prototype.isRejected = function () {
+ return (this._bitField & 16777216) !== 0;
+};
+
+var isPending = PromiseInspection.prototype.isPending = function () {
+ return (this._bitField & 50397184) === 0;
+};
+
+var isResolved = PromiseInspection.prototype.isResolved = function () {
+ return (this._bitField & 50331648) !== 0;
+};
+
+PromiseInspection.prototype.isCancelled = function() {
+ return (this._bitField & 8454144) !== 0;
+};
+
+Promise.prototype.__isCancelled = function() {
+ return (this._bitField & 65536) === 65536;
+};
+
+Promise.prototype._isCancelled = function() {
+ return this._target().__isCancelled();
+};
+
+Promise.prototype.isCancelled = function() {
+ return (this._target()._bitField & 8454144) !== 0;
+};
+
+Promise.prototype.isPending = function() {
+ return isPending.call(this._target());
+};
+
+Promise.prototype.isRejected = function() {
+ return isRejected.call(this._target());
+};
+
+Promise.prototype.isFulfilled = function() {
+ return isFulfilled.call(this._target());
+};
+
+Promise.prototype.isResolved = function() {
+ return isResolved.call(this._target());
+};
+
+Promise.prototype.value = function() {
+ return value.call(this._target());
+};
+
+Promise.prototype.reason = function() {
+ var target = this._target();
+ target._unsetRejectionIsUnhandled();
+ return reason.call(target);
+};
+
+Promise.prototype._value = function() {
+ return this._settledValue();
+};
+
+Promise.prototype._reason = function() {
+ this._unsetRejectionIsUnhandled();
+ return this._settledValue();
+};
+
+Promise.PromiseInspection = PromiseInspection;
+};
+
+},{}],33:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL) {
+var util = _dereq_("./util");
+var errorObj = util.errorObj;
+var isObject = util.isObject;
+
+function tryConvertToPromise(obj, context) {
+ if (isObject(obj)) {
+ if (obj instanceof Promise) return obj;
+ var then = getThen(obj);
+ if (then === errorObj) {
+ if (context) context._pushContext();
+ var ret = Promise.reject(then.e);
+ if (context) context._popContext();
+ return ret;
+ } else if (typeof then === "function") {
+ if (isAnyBluebirdPromise(obj)) {
+ var ret = new Promise(INTERNAL);
+ obj._then(
+ ret._fulfill,
+ ret._reject,
+ undefined,
+ ret,
+ null
+ );
+ return ret;
+ }
+ return doThenable(obj, then, context);
+ }
+ }
+ return obj;
+}
+
+function doGetThen(obj) {
+ return obj.then;
+}
+
+function getThen(obj) {
+ try {
+ return doGetThen(obj);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+}
+
+var hasProp = {}.hasOwnProperty;
+function isAnyBluebirdPromise(obj) {
+ try {
+ return hasProp.call(obj, "_promise0");
+ } catch (e) {
+ return false;
+ }
+}
+
+function doThenable(x, then, context) {
+ var promise = new Promise(INTERNAL);
+ var ret = promise;
+ if (context) context._pushContext();
+ promise._captureStackTrace();
+ if (context) context._popContext();
+ var synchronous = true;
+ var result = util.tryCatch(then).call(x, resolve, reject);
+ synchronous = false;
+
+ if (promise && result === errorObj) {
+ promise._rejectCallback(result.e, true, true);
+ promise = null;
+ }
+
+ function resolve(value) {
+ if (!promise) return;
+ promise._resolveCallback(value);
+ promise = null;
+ }
+
+ function reject(reason) {
+ if (!promise) return;
+ promise._rejectCallback(reason, synchronous, true);
+ promise = null;
+ }
+ return ret;
+}
+
+return tryConvertToPromise;
+};
+
+},{"./util":36}],34:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function(Promise, INTERNAL, debug) {
+var util = _dereq_("./util");
+var TimeoutError = Promise.TimeoutError;
+
+function HandleWrapper(handle) {
+ this.handle = handle;
+}
+
+HandleWrapper.prototype._resultCancelled = function() {
+ clearTimeout(this.handle);
+};
+
+var afterValue = function(value) { return delay(+this).thenReturn(value); };
+var delay = Promise.delay = function (ms, value) {
+ var ret;
+ var handle;
+ if (value !== undefined) {
+ ret = Promise.resolve(value)
+ ._then(afterValue, null, null, ms, undefined);
+ if (debug.cancellation() && value instanceof Promise) {
+ ret._setOnCancel(value);
+ }
+ } else {
+ ret = new Promise(INTERNAL);
+ handle = setTimeout(function() { ret._fulfill(); }, +ms);
+ if (debug.cancellation()) {
+ ret._setOnCancel(new HandleWrapper(handle));
+ }
+ ret._captureStackTrace();
+ }
+ ret._setAsyncGuaranteed();
+ return ret;
+};
+
+Promise.prototype.delay = function (ms) {
+ return delay(ms, this);
+};
+
+var afterTimeout = function (promise, message, parent) {
+ var err;
+ if (typeof message !== "string") {
+ if (message instanceof Error) {
+ err = message;
+ } else {
+ err = new TimeoutError("operation timed out");
+ }
+ } else {
+ err = new TimeoutError(message);
+ }
+ util.markAsOriginatingFromRejection(err);
+ promise._attachExtraTrace(err);
+ promise._reject(err);
+
+ if (parent != null) {
+ parent.cancel();
+ }
+};
+
+function successClear(value) {
+ clearTimeout(this.handle);
+ return value;
+}
+
+function failureClear(reason) {
+ clearTimeout(this.handle);
+ throw reason;
+}
+
+Promise.prototype.timeout = function (ms, message) {
+ ms = +ms;
+ var ret, parent;
+
+ var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
+ if (ret.isPending()) {
+ afterTimeout(ret, message, parent);
+ }
+ }, ms));
+
+ if (debug.cancellation()) {
+ parent = this.then();
+ ret = parent._then(successClear, failureClear,
+ undefined, handleWrapper, undefined);
+ ret._setOnCancel(handleWrapper);
+ } else {
+ ret = this._then(successClear, failureClear,
+ undefined, handleWrapper, undefined);
+ }
+
+ return ret;
+};
+
+};
+
+},{"./util":36}],35:[function(_dereq_,module,exports){
+"use strict";
+module.exports = function (Promise, apiRejection, tryConvertToPromise,
+ createContext, INTERNAL, debug) {
+ var util = _dereq_("./util");
+ var TypeError = _dereq_("./errors").TypeError;
+ var inherits = _dereq_("./util").inherits;
+ var errorObj = util.errorObj;
+ var tryCatch = util.tryCatch;
+ var NULL = {};
+
+ function thrower(e) {
+ setTimeout(function(){throw e;}, 0);
+ }
+
+ function castPreservingDisposable(thenable) {
+ var maybePromise = tryConvertToPromise(thenable);
+ if (maybePromise !== thenable &&
+ typeof thenable._isDisposable === "function" &&
+ typeof thenable._getDisposer === "function" &&
+ thenable._isDisposable()) {
+ maybePromise._setDisposable(thenable._getDisposer());
+ }
+ return maybePromise;
+ }
+ function dispose(resources, inspection) {
+ var i = 0;
+ var len = resources.length;
+ var ret = new Promise(INTERNAL);
+ function iterator() {
+ if (i >= len) return ret._fulfill();
+ var maybePromise = castPreservingDisposable(resources[i++]);
+ if (maybePromise instanceof Promise &&
+ maybePromise._isDisposable()) {
+ try {
+ maybePromise = tryConvertToPromise(
+ maybePromise._getDisposer().tryDispose(inspection),
+ resources.promise);
+ } catch (e) {
+ return thrower(e);
+ }
+ if (maybePromise instanceof Promise) {
+ return maybePromise._then(iterator, thrower,
+ null, null, null);
+ }
+ }
+ iterator();
+ }
+ iterator();
+ return ret;
+ }
+
+ function Disposer(data, promise, context) {
+ this._data = data;
+ this._promise = promise;
+ this._context = context;
+ }
+
+ Disposer.prototype.data = function () {
+ return this._data;
+ };
+
+ Disposer.prototype.promise = function () {
+ return this._promise;
+ };
+
+ Disposer.prototype.resource = function () {
+ if (this.promise().isFulfilled()) {
+ return this.promise().value();
+ }
+ return NULL;
+ };
+
+ Disposer.prototype.tryDispose = function(inspection) {
+ var resource = this.resource();
+ var context = this._context;
+ if (context !== undefined) context._pushContext();
+ var ret = resource !== NULL
+ ? this.doDispose(resource, inspection) : null;
+ if (context !== undefined) context._popContext();
+ this._promise._unsetDisposable();
+ this._data = null;
+ return ret;
+ };
+
+ Disposer.isDisposer = function (d) {
+ return (d != null &&
+ typeof d.resource === "function" &&
+ typeof d.tryDispose === "function");
+ };
+
+ function FunctionDisposer(fn, promise, context) {
+ this.constructor$(fn, promise, context);
+ }
+ inherits(FunctionDisposer, Disposer);
+
+ FunctionDisposer.prototype.doDispose = function (resource, inspection) {
+ var fn = this.data();
+ return fn.call(resource, resource, inspection);
+ };
+
+ function maybeUnwrapDisposer(value) {
+ if (Disposer.isDisposer(value)) {
+ this.resources[this.index]._setDisposable(value);
+ return value.promise();
+ }
+ return value;
+ }
+
+ function ResourceList(length) {
+ this.length = length;
+ this.promise = null;
+ this[length-1] = null;
+ }
+
+ ResourceList.prototype._resultCancelled = function() {
+ var len = this.length;
+ for (var i = 0; i < len; ++i) {
+ var item = this[i];
+ if (item instanceof Promise) {
+ item.cancel();
+ }
+ }
+ };
+
+ Promise.using = function () {
+ var len = arguments.length;
+ if (len < 2) return apiRejection(
+ "you must pass at least 2 arguments to Promise.using");
+ var fn = arguments[len - 1];
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ var input;
+ var spreadArgs = true;
+ if (len === 2 && Array.isArray(arguments[0])) {
+ input = arguments[0];
+ len = input.length;
+ spreadArgs = false;
+ } else {
+ input = arguments;
+ len--;
+ }
+ var resources = new ResourceList(len);
+ for (var i = 0; i < len; ++i) {
+ var resource = input[i];
+ if (Disposer.isDisposer(resource)) {
+ var disposer = resource;
+ resource = resource.promise();
+ resource._setDisposable(disposer);
+ } else {
+ var maybePromise = tryConvertToPromise(resource);
+ if (maybePromise instanceof Promise) {
+ resource =
+ maybePromise._then(maybeUnwrapDisposer, null, null, {
+ resources: resources,
+ index: i
+ }, undefined);
+ }
+ }
+ resources[i] = resource;
+ }
+
+ var reflectedResources = new Array(resources.length);
+ for (var i = 0; i < reflectedResources.length; ++i) {
+ reflectedResources[i] = Promise.resolve(resources[i]).reflect();
+ }
+
+ var resultPromise = Promise.all(reflectedResources)
+ .then(function(inspections) {
+ for (var i = 0; i < inspections.length; ++i) {
+ var inspection = inspections[i];
+ if (inspection.isRejected()) {
+ errorObj.e = inspection.error();
+ return errorObj;
+ } else if (!inspection.isFulfilled()) {
+ resultPromise.cancel();
+ return;
+ }
+ inspections[i] = inspection.value();
+ }
+ promise._pushContext();
+
+ fn = tryCatch(fn);
+ var ret = spreadArgs
+ ? fn.apply(undefined, inspections) : fn(inspections);
+ var promiseCreated = promise._popContext();
+ debug.checkForgottenReturns(
+ ret, promiseCreated, "Promise.using", promise);
+ return ret;
+ });
+
+ var promise = resultPromise.lastly(function() {
+ var inspection = new Promise.PromiseInspection(resultPromise);
+ return dispose(resources, inspection);
+ });
+ resources.promise = promise;
+ promise._setOnCancel(resources);
+ return promise;
+ };
+
+ Promise.prototype._setDisposable = function (disposer) {
+ this._bitField = this._bitField | 131072;
+ this._disposer = disposer;
+ };
+
+ Promise.prototype._isDisposable = function () {
+ return (this._bitField & 131072) > 0;
+ };
+
+ Promise.prototype._getDisposer = function () {
+ return this._disposer;
+ };
+
+ Promise.prototype._unsetDisposable = function () {
+ this._bitField = this._bitField & (~131072);
+ this._disposer = undefined;
+ };
+
+ Promise.prototype.disposer = function (fn) {
+ if (typeof fn === "function") {
+ return new FunctionDisposer(fn, this, createContext());
+ }
+ throw new TypeError();
+ };
+
+};
+
+},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
+"use strict";
+var es5 = _dereq_("./es5");
+var canEvaluate = typeof navigator == "undefined";
+
+var errorObj = {e: {}};
+var tryCatchTarget;
+var globalObject = typeof self !== "undefined" ? self :
+ typeof window !== "undefined" ? window :
+ typeof global !== "undefined" ? global :
+ this !== undefined ? this : null;
+
+function tryCatcher() {
+ try {
+ var target = tryCatchTarget;
+ tryCatchTarget = null;
+ return target.apply(this, arguments);
+ } catch (e) {
+ errorObj.e = e;
+ return errorObj;
+ }
+}
+function tryCatch(fn) {
+ tryCatchTarget = fn;
+ return tryCatcher;
+}
+
+var inherits = function(Child, Parent) {
+ var hasProp = {}.hasOwnProperty;
+
+ function T() {
+ this.constructor = Child;
+ this.constructor$ = Parent;
+ for (var propertyName in Parent.prototype) {
+ if (hasProp.call(Parent.prototype, propertyName) &&
+ propertyName.charAt(propertyName.length-1) !== "$"
+ ) {
+ this[propertyName + "$"] = Parent.prototype[propertyName];
+ }
+ }
+ }
+ T.prototype = Parent.prototype;
+ Child.prototype = new T();
+ return Child.prototype;
+};
+
+
+function isPrimitive(val) {
+ return val == null || val === true || val === false ||
+ typeof val === "string" || typeof val === "number";
+
+}
+
+function isObject(value) {
+ return typeof value === "function" ||
+ typeof value === "object" && value !== null;
+}
+
+function maybeWrapAsError(maybeError) {
+ if (!isPrimitive(maybeError)) return maybeError;
+
+ return new Error(safeToString(maybeError));
+}
+
+function withAppended(target, appendee) {
+ var len = target.length;
+ var ret = new Array(len + 1);
+ var i;
+ for (i = 0; i < len; ++i) {
+ ret[i] = target[i];
+ }
+ ret[i] = appendee;
+ return ret;
+}
+
+function getDataPropertyOrDefault(obj, key, defaultValue) {
+ if (es5.isES5) {
+ var desc = Object.getOwnPropertyDescriptor(obj, key);
+
+ if (desc != null) {
+ return desc.get == null && desc.set == null
+ ? desc.value
+ : defaultValue;
+ }
+ } else {
+ return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
+ }
+}
+
+function notEnumerableProp(obj, name, value) {
+ if (isPrimitive(obj)) return obj;
+ var descriptor = {
+ value: value,
+ configurable: true,
+ enumerable: false,
+ writable: true
+ };
+ es5.defineProperty(obj, name, descriptor);
+ return obj;
+}
+
+function thrower(r) {
+ throw r;
+}
+
+var inheritedDataKeys = (function() {
+ var excludedPrototypes = [
+ Array.prototype,
+ Object.prototype,
+ Function.prototype
+ ];
+
+ var isExcludedProto = function(val) {
+ for (var i = 0; i < excludedPrototypes.length; ++i) {
+ if (excludedPrototypes[i] === val) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ if (es5.isES5) {
+ var getKeys = Object.getOwnPropertyNames;
+ return function(obj) {
+ var ret = [];
+ var visitedKeys = Object.create(null);
+ while (obj != null && !isExcludedProto(obj)) {
+ var keys;
+ try {
+ keys = getKeys(obj);
+ } catch (e) {
+ return ret;
+ }
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (visitedKeys[key]) continue;
+ visitedKeys[key] = true;
+ var desc = Object.getOwnPropertyDescriptor(obj, key);
+ if (desc != null && desc.get == null && desc.set == null) {
+ ret.push(key);
+ }
+ }
+ obj = es5.getPrototypeOf(obj);
+ }
+ return ret;
+ };
+ } else {
+ var hasProp = {}.hasOwnProperty;
+ return function(obj) {
+ if (isExcludedProto(obj)) return [];
+ var ret = [];
+
+ /*jshint forin:false */
+ enumeration: for (var key in obj) {
+ if (hasProp.call(obj, key)) {
+ ret.push(key);
+ } else {
+ for (var i = 0; i < excludedPrototypes.length; ++i) {
+ if (hasProp.call(excludedPrototypes[i], key)) {
+ continue enumeration;
+ }
+ }
+ ret.push(key);
+ }
+ }
+ return ret;
+ };
+ }
+
+})();
+
+var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
+function isClass(fn) {
+ try {
+ if (typeof fn === "function") {
+ var keys = es5.names(fn.prototype);
+
+ var hasMethods = es5.isES5 && keys.length > 1;
+ var hasMethodsOtherThanConstructor = keys.length > 0 &&
+ !(keys.length === 1 && keys[0] === "constructor");
+ var hasThisAssignmentAndStaticMethods =
+ thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
+
+ if (hasMethods || hasMethodsOtherThanConstructor ||
+ hasThisAssignmentAndStaticMethods) {
+ return true;
+ }
+ }
+ return false;
+ } catch (e) {
+ return false;
+ }
+}
+
+function toFastProperties(obj) {
+ /*jshint -W027,-W055,-W031*/
+ function FakeConstructor() {}
+ FakeConstructor.prototype = obj;
+ var l = 8;
+ while (l--) new FakeConstructor();
+ return obj;
+ eval(obj);
+}
+
+var rident = /^[a-z$_][a-z$_0-9]*$/i;
+function isIdentifier(str) {
+ return rident.test(str);
+}
+
+function filledRange(count, prefix, suffix) {
+ var ret = new Array(count);
+ for(var i = 0; i < count; ++i) {
+ ret[i] = prefix + i + suffix;
+ }
+ return ret;
+}
+
+function safeToString(obj) {
+ try {
+ return obj + "";
+ } catch (e) {
+ return "[no string representation]";
+ }
+}
+
+function isError(obj) {
+ return obj !== null &&
+ typeof obj === "object" &&
+ typeof obj.message === "string" &&
+ typeof obj.name === "string";
+}
+
+function markAsOriginatingFromRejection(e) {
+ try {
+ notEnumerableProp(e, "isOperational", true);
+ }
+ catch(ignore) {}
+}
+
+function originatesFromRejection(e) {
+ if (e == null) return false;
+ return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
+ e["isOperational"] === true);
+}
+
+function canAttachTrace(obj) {
+ return isError(obj) && es5.propertyIsWritable(obj, "stack");
+}
+
+var ensureErrorObject = (function() {
+ if (!("stack" in new Error())) {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ try {throw new Error(safeToString(value));}
+ catch(err) {return err;}
+ };
+ } else {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ return new Error(safeToString(value));
+ };
+ }
+})();
+
+function classString(obj) {
+ return {}.toString.call(obj);
+}
+
+function copyDescriptors(from, to, filter) {
+ var keys = es5.names(from);
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (filter(key)) {
+ try {
+ es5.defineProperty(to, key, es5.getDescriptor(from, key));
+ } catch (ignore) {}
+ }
+ }
+}
+
+var asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ }
+ return null;
+};
+
+if (typeof Symbol !== "undefined" && Symbol.iterator) {
+ var ArrayFrom = typeof Array.from === "function" ? function(v) {
+ return Array.from(v);
+ } : function(v) {
+ var ret = [];
+ var it = v[Symbol.iterator]();
+ var itResult;
+ while (!((itResult = it.next()).done)) {
+ ret.push(itResult.value);
+ }
+ return ret;
+ };
+
+ asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ } else if (v != null && typeof v[Symbol.iterator] === "function") {
+ return ArrayFrom(v);
+ }
+ return null;
+ };
+}
+
+var isNode = typeof process !== "undefined" &&
+ classString(process).toLowerCase() === "[object process]";
+
+function env(key, def) {
+ return isNode ? process.env[key] : def;
+}
+
+function getNativePromise() {
+ if (typeof Promise === "function") {
+ try {
+ var promise = new Promise(function(){});
+ if ({}.toString.call(promise) === "[object Promise]") {
+ return Promise;
+ }
+ } catch (e) {}
+ }
+}
+
+function domainBind(self, cb) {
+ return self.bind(cb);
+}
+
+var ret = {
+ isClass: isClass,
+ isIdentifier: isIdentifier,
+ inheritedDataKeys: inheritedDataKeys,
+ getDataPropertyOrDefault: getDataPropertyOrDefault,
+ thrower: thrower,
+ isArray: es5.isArray,
+ asArray: asArray,
+ notEnumerableProp: notEnumerableProp,
+ isPrimitive: isPrimitive,
+ isObject: isObject,
+ isError: isError,
+ canEvaluate: canEvaluate,
+ errorObj: errorObj,
+ tryCatch: tryCatch,
+ inherits: inherits,
+ withAppended: withAppended,
+ maybeWrapAsError: maybeWrapAsError,
+ toFastProperties: toFastProperties,
+ filledRange: filledRange,
+ toString: safeToString,
+ canAttachTrace: canAttachTrace,
+ ensureErrorObject: ensureErrorObject,
+ originatesFromRejection: originatesFromRejection,
+ markAsOriginatingFromRejection: markAsOriginatingFromRejection,
+ classString: classString,
+ copyDescriptors: copyDescriptors,
+ hasDevTools: typeof chrome !== "undefined" && chrome &&
+ typeof chrome.loadTimes === "function",
+ isNode: isNode,
+ env: env,
+ global: globalObject,
+ getNativePromise: getNativePromise,
+ domainBind: domainBind
+};
+ret.isRecentNode = ret.isNode && (function() {
+ var version = process.versions.node.split(".").map(Number);
+ return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
+})();
+
+if (ret.isNode) ret.toFastProperties(process);
+
+try {throw new Error(); } catch (e) {ret.lastLineError = e;}
+module.exports = ret;
+
+},{"./es5":13}]},{},[4])(4)
+}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
\ 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..485c12a
--- /dev/null
+++ b/node_modules/bluebird/js/browser/bluebird.min.js
@@ -0,0 +1,31 @@
+/* @preserve
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2013-2015 Petka Antonov
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ */
+/**
+ * bluebird build version 3.4.6
+ * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
+*/
+!function(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)||k(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&&(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:w(e)}}function k(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 E(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||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():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(){0===(524288&this._bitField)&&(this._setRejectionIsUnhandled(),I.invokeLater(this._notifyUnhandledRejection,this,void 0))},e.prototype._notifyUnhandledRejectionIsHandled=function(){E("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(),E("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}"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.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?"[33m":"[31m";console.warn(n+t+"[0m\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 s(){return c.call(this,this.promise._target()._settledValue())}function a(t){return o(this,t)?void 0:(p.e=t,p)}function c(t){var r=this.promise,c=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?c.call(r._boundValue()):c.call(r._boundValue(),t);if(void 0!==l){r._setReturnedNonUndefined();var h=n(l,r);if(h instanceof e){if(null!=this.cancelPromise){if(h._isCancelled()){var f=new u("late cancellation observer");return r._attachExtraTrace(f),p.e=f,p}h.isPending()&&h._attachCancellationCallback(new i(this))}return h._then(s,a,void 0,this,void 0)}}}return r.isRejected()?(o(this),p.e=t,p):(o(this),t)}var l=t("./util"),u=e.CancellationError,p=l.errorObj;return r.prototype.isFinallyHandler=function(){return 0===this.type},i.prototype._resultCancelled=function(){o(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,i){return"function"!=typeof t?this.then():this._then(n,i,void 0,new r(this,e,t),void 0)},e.prototype.lastly=e.prototype["finally"]=function(t){return this._passThrough(t,0,c,c)},e.prototype.tap=function(t){return this._passThrough(t,1,c)},r}},{"./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("expecting an object but got A catch statement predicate "+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 k(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 k(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){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 k?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,k,p,x),t("./direct_resolve")(i),t("./synchronous_inspection")(i),t("./join")(i,k,j,b,v,c),i.Promise=i,i.version="3.4.6",t("./map.js")(i,k,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,k,j,p),t("./race.js")(i,b,j,p),t("./reduce.js")(i,k,p,j,b,x),t("./settle.js")(i,k,x),t("./some.js")(i,k,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{}}}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===E)t[_]=E(u,h,u,p,e,i);else{var d=r(p,function(){return E(u,h,u,p,e,i)});f.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return f.toFastProperties(t),t}function u(t,e,n){return E(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},k=function(t){return t.replace(/([$])/,"\\$")},E=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=E),!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,-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 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}(),N.isNode&&N.toFastProperties(process);try{throw new Error}catch(B){N.lastLineError=B}e.exports=N},{"./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..28ead44
--- /dev/null
+++ b/node_modules/bluebird/js/release/async.js
@@ -0,0 +1,166 @@
+"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.invokeFirst = function (fn, receiver, arg) {
+ this._normalQueue.unshift(fn, receiver, arg);
+ this._queueTick();
+};
+
+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..a534ae7
--- /dev/null
+++ b/node_modules/bluebird/js/release/debuggability.js
@@ -0,0 +1,915 @@
+"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();
+ async.invokeLater(this._notifyUnhandledRejection, this, undefined);
+};
+
+Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
+ fireRejectionEvent("rejectionHandled",
+ unhandledRejectionHandled, undefined, this);
+};
+
+Promise.prototype._setReturnedNonUndefined = function() {
+ this._bitField = this._bitField | 268435456;
+};
+
+Promise.prototype._returnedNonUndefined = function() {
+ return (this._bitField & 268435456) !== 0;
+};
+
+Promise.prototype._notifyUnhandledRejection = function () {
+ if (this._isRejectionUnhandled()) {
+ var reason = this._settledValue();
+ this._setUnhandledRejectionIsNotified();
+ fireRejectionEvent("unhandledRejection",
+ possiblyUnhandledRejection, reason, this);
+ }
+};
+
+Promise.prototype._setUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField | 262144;
+};
+
+Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
+ this._bitField = this._bitField & (~262144);
+};
+
+Promise.prototype._isUnhandledRejectionNotified = function () {
+ return (this._bitField & 262144) > 0;
+};
+
+Promise.prototype._setRejectionIsUnhandled = function () {
+ this._bitField = this._bitField | 1048576;
+};
+
+Promise.prototype._unsetRejectionIsUnhandled = function () {
+ this._bitField = this._bitField & (~1048576);
+ if (this._isUnhandledRejectionNotified()) {
+ this._unsetUnhandledRejectionIsNotified();
+ this._notifyUnhandledRejectionIsHandled();
+ }
+};
+
+Promise.prototype._isRejectionUnhandled = function () {
+ return (this._bitField & 1048576) > 0;
+};
+
+Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
+ return warn(message, shouldUseOwnTrace, promise || this);
+};
+
+Promise.onPossiblyUnhandledRejection = function (fn) {
+ var domain = getDomain();
+ possiblyUnhandledRejection =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+Promise.onUnhandledRejectionHandled = function (fn) {
+ var domain = getDomain();
+ unhandledRejectionHandled =
+ typeof fn === "function" ? (domain === null ?
+ fn : util.domainBind(domain, fn))
+ : undefined;
+};
+
+var disableLongStackTraces = function() {};
+Promise.longStackTraces = function () {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ if (!config.longStackTraces && longStackTracesIsSupported()) {
+ var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
+ var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
+ config.longStackTraces = true;
+ disableLongStackTraces = function() {
+ if (async.haveItemsQueued() && !config.longStackTraces) {
+ throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+ Promise.prototype._captureStackTrace = Promise_captureStackTrace;
+ Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
+ Context.deactivateLongStackTraces();
+ async.enableTrampoline();
+ config.longStackTraces = false;
+ };
+ Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
+ Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
+ Context.activateLongStackTraces();
+ async.disableTrampolineIfNecessary();
+ }
+};
+
+Promise.hasLongStackTraces = function () {
+ return config.longStackTraces && longStackTracesIsSupported();
+};
+
+var fireDomEvent = (function() {
+ try {
+ if (typeof CustomEvent === "function") {
+ var event = new CustomEvent("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new CustomEvent(name.toLowerCase(), {
+ detail: event,
+ cancelable: true
+ });
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else if (typeof Event === "function") {
+ var event = new Event("CustomEvent");
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = new Event(name.toLowerCase(), {
+ cancelable: true
+ });
+ domEvent.detail = event;
+ return !util.global.dispatchEvent(domEvent);
+ };
+ } else {
+ var event = document.createEvent("CustomEvent");
+ event.initCustomEvent("testingtheevent", false, true, {});
+ util.global.dispatchEvent(event);
+ return function(name, event) {
+ var domEvent = document.createEvent("CustomEvent");
+ domEvent.initCustomEvent(name.toLowerCase(), false, true,
+ event);
+ return !util.global.dispatchEvent(domEvent);
+ };
+ }
+ } catch (e) {}
+ return function() {
+ return false;
+ };
+})();
+
+var fireGlobalEvent = (function() {
+ if (util.isNode) {
+ return function() {
+ return process.emit.apply(process, arguments);
+ };
+ } else {
+ if (!util.global) {
+ return function() {
+ return false;
+ };
+ }
+ return function(name) {
+ var methodName = "on" + name.toLowerCase();
+ var method = util.global[methodName];
+ if (!method) return false;
+ method.apply(util.global, [].slice.call(arguments, 1));
+ return true;
+ };
+ }
+})();
+
+function generatePromiseLifecycleEventObject(name, promise) {
+ return {promise: promise};
+}
+
+var eventToObjectGenerator = {
+ promiseCreated: generatePromiseLifecycleEventObject,
+ promiseFulfilled: generatePromiseLifecycleEventObject,
+ promiseRejected: generatePromiseLifecycleEventObject,
+ promiseResolved: generatePromiseLifecycleEventObject,
+ promiseCancelled: generatePromiseLifecycleEventObject,
+ promiseChained: function(name, promise, child) {
+ return {promise: promise, child: child};
+ },
+ warning: function(name, warning) {
+ return {warning: warning};
+ },
+ unhandledRejection: function (name, reason, promise) {
+ return {reason: reason, promise: promise};
+ },
+ rejectionHandled: generatePromiseLifecycleEventObject
+};
+
+var activeFireEvent = function (name) {
+ var globalEventFired = false;
+ try {
+ globalEventFired = fireGlobalEvent.apply(null, arguments);
+ } catch (e) {
+ async.throwLater(e);
+ globalEventFired = true;
+ }
+
+ var domEventFired = false;
+ try {
+ domEventFired = fireDomEvent(name,
+ eventToObjectGenerator[name].apply(null, arguments));
+ } catch (e) {
+ async.throwLater(e);
+ domEventFired = true;
+ }
+
+ return domEventFired || globalEventFired;
+};
+
+Promise.config = function(opts) {
+ opts = Object(opts);
+ if ("longStackTraces" in opts) {
+ if (opts.longStackTraces) {
+ Promise.longStackTraces();
+ } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
+ disableLongStackTraces();
+ }
+ }
+ if ("warnings" in opts) {
+ var warningsOption = opts.warnings;
+ config.warnings = !!warningsOption;
+ wForgottenReturn = config.warnings;
+
+ if (util.isObject(warningsOption)) {
+ if ("wForgottenReturn" in warningsOption) {
+ wForgottenReturn = !!warningsOption.wForgottenReturn;
+ }
+ }
+ }
+ if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
+ if (async.haveItemsQueued()) {
+ throw new Error(
+ "cannot enable cancellation after promises are in use");
+ }
+ Promise.prototype._clearCancellationData =
+ cancellationClearCancellationData;
+ Promise.prototype._propagateFrom = cancellationPropagateFrom;
+ Promise.prototype._onCancel = cancellationOnCancel;
+ Promise.prototype._setOnCancel = cancellationSetOnCancel;
+ Promise.prototype._attachCancellationCallback =
+ cancellationAttachCancellationCallback;
+ Promise.prototype._execute = cancellationExecute;
+ propagateFromFunction = cancellationPropagateFrom;
+ config.cancellation = true;
+ }
+ if ("monitoring" in opts) {
+ if (opts.monitoring && !config.monitoring) {
+ config.monitoring = true;
+ Promise.prototype._fireEvent = activeFireEvent;
+ } else if (!opts.monitoring && config.monitoring) {
+ config.monitoring = false;
+ Promise.prototype._fireEvent = defaultFireEvent;
+ }
+ }
+};
+
+function defaultFireEvent() { return false; }
+
+Promise.prototype._fireEvent = defaultFireEvent;
+Promise.prototype._execute = function(executor, resolve, reject) {
+ try {
+ executor(resolve, reject);
+ } catch (e) {
+ return e;
+ }
+};
+Promise.prototype._onCancel = function () {};
+Promise.prototype._setOnCancel = function (handler) { ; };
+Promise.prototype._attachCancellationCallback = function(onCancel) {
+ ;
+};
+Promise.prototype._captureStackTrace = function () {};
+Promise.prototype._attachExtraTrace = function () {};
+Promise.prototype._clearCancellationData = function() {};
+Promise.prototype._propagateFrom = function (parent, flags) {
+ ;
+ ;
+};
+
+function cancellationExecute(executor, resolve, reject) {
+ var promise = this;
+ try {
+ executor(resolve, reject, function(onCancel) {
+ if (typeof onCancel !== "function") {
+ throw new TypeError("onCancel must be a function, got: " +
+ util.toString(onCancel));
+ }
+ promise._attachCancellationCallback(onCancel);
+ });
+ } catch (e) {
+ return e;
+ }
+}
+
+function cancellationAttachCancellationCallback(onCancel) {
+ if (!this._isCancellable()) return this;
+
+ var previousOnCancel = this._onCancel();
+ if (previousOnCancel !== undefined) {
+ if (util.isArray(previousOnCancel)) {
+ previousOnCancel.push(onCancel);
+ } else {
+ this._setOnCancel([previousOnCancel, onCancel]);
+ }
+ } else {
+ this._setOnCancel(onCancel);
+ }
+}
+
+function cancellationOnCancel() {
+ return this._onCancelField;
+}
+
+function cancellationSetOnCancel(onCancel) {
+ this._onCancelField = onCancel;
+}
+
+function cancellationClearCancellationData() {
+ this._cancellationParent = undefined;
+ this._onCancelField = undefined;
+}
+
+function cancellationPropagateFrom(parent, flags) {
+ if ((flags & 1) !== 0) {
+ this._cancellationParent = parent;
+ var branchesRemainingToCancel = parent._branchesRemainingToCancel;
+ if (branchesRemainingToCancel === undefined) {
+ branchesRemainingToCancel = 0;
+ }
+ parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
+ }
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+
+function bindingPropagateFrom(parent, flags) {
+ if ((flags & 2) !== 0 && parent._isBound()) {
+ this._setBoundTo(parent._boundTo);
+ }
+}
+var propagateFromFunction = bindingPropagateFrom;
+
+function boundValueFunction() {
+ var ret = this._boundTo;
+ if (ret !== undefined) {
+ if (ret instanceof Promise) {
+ if (ret.isFulfilled()) {
+ return ret.value();
+ } else {
+ return undefined;
+ }
+ }
+ }
+ return ret;
+}
+
+function longStackTracesCaptureStackTrace() {
+ this._trace = new CapturedTrace(this._peekContext());
+}
+
+function longStackTracesAttachExtraTrace(error, ignoreSelf) {
+ if (canAttachTrace(error)) {
+ var trace = this._trace;
+ if (trace !== undefined) {
+ if (ignoreSelf) trace = trace._parent;
+ }
+ if (trace !== undefined) {
+ trace.attachExtraTrace(error);
+ } else if (!error.__stackCleaned__) {
+ var parsed = parseStackAndMessage(error);
+ util.notEnumerableProp(error, "stack",
+ parsed.message + "\n" + parsed.stack.join("\n"));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+ }
+ }
+}
+
+function checkForgottenReturns(returnValue, promiseCreated, name, promise,
+ parent) {
+ if (returnValue === undefined && promiseCreated !== null &&
+ wForgottenReturn) {
+ if (parent !== undefined && parent._returnedNonUndefined()) return;
+ if ((promise._bitField & 65535) === 0) return;
+
+ if (name) name = name + " ";
+ var handlerLine = "";
+ var creatorLine = "";
+ if (promiseCreated._trace) {
+ var traceLines = promiseCreated._trace.stack.split("\n");
+ var stack = cleanStack(traceLines);
+ for (var i = stack.length - 1; i >= 0; --i) {
+ var line = stack[i];
+ if (!nodeFramePattern.test(line)) {
+ var lineMatches = line.match(parseLinePattern);
+ if (lineMatches) {
+ handlerLine = "at " + lineMatches[1] +
+ ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
+ }
+ break;
+ }
+ }
+
+ if (stack.length > 0) {
+ var firstUserLine = stack[0];
+ for (var i = 0; i < traceLines.length; ++i) {
+
+ if (traceLines[i] === firstUserLine) {
+ if (i > 0) {
+ creatorLine = "\n" + traceLines[i - 1];
+ }
+ break;
+ }
+ }
+
+ }
+ }
+ var msg = "a promise was created in a " + name +
+ "handler " + handlerLine + "but was not returned from it, " +
+ "see http://goo.gl/rRqMUw" +
+ creatorLine;
+ promise._warn(msg, true, promiseCreated);
+ }
+}
+
+function deprecated(name, replacement) {
+ var message = name +
+ " is deprecated and will be removed in a future version.";
+ if (replacement) message += " Use " + replacement + " instead.";
+ return warn(message);
+}
+
+function warn(message, shouldUseOwnTrace, promise) {
+ if (!config.warnings) return;
+ var warning = new Warning(message);
+ var ctx;
+ if (shouldUseOwnTrace) {
+ promise._attachExtraTrace(warning);
+ } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
+ ctx.attachExtraTrace(warning);
+ } else {
+ var parsed = parseStackAndMessage(warning);
+ warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
+ }
+
+ if (!activeFireEvent("warning", warning)) {
+ formatAndLogError(warning, "", true);
+ }
+}
+
+function reconstructStack(message, stacks) {
+ for (var i = 0; i < stacks.length - 1; ++i) {
+ stacks[i].push("From previous event:");
+ stacks[i] = stacks[i].join("\n");
+ }
+ if (i < stacks.length) {
+ stacks[i] = stacks[i].join("\n");
+ }
+ return message + "\n" + stacks.join("\n");
+}
+
+function removeDuplicateOrEmptyJumps(stacks) {
+ for (var i = 0; i < stacks.length; ++i) {
+ if (stacks[i].length === 0 ||
+ ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
+ stacks.splice(i, 1);
+ i--;
+ }
+ }
+}
+
+function removeCommonRoots(stacks) {
+ var current = stacks[0];
+ for (var i = 1; i < stacks.length; ++i) {
+ var prev = stacks[i];
+ var currentLastIndex = current.length - 1;
+ var currentLastLine = current[currentLastIndex];
+ var commonRootMeetPoint = -1;
+
+ for (var j = prev.length - 1; j >= 0; --j) {
+ if (prev[j] === currentLastLine) {
+ commonRootMeetPoint = j;
+ break;
+ }
+ }
+
+ for (var j = commonRootMeetPoint; j >= 0; --j) {
+ var line = prev[j];
+ if (current[currentLastIndex] === line) {
+ current.pop();
+ currentLastIndex--;
+ } else {
+ break;
+ }
+ }
+ current = prev;
+ }
+}
+
+function cleanStack(stack) {
+ var ret = [];
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ var isTraceLine = " (No stack trace)" === line ||
+ stackFramePattern.test(line);
+ var isInternalFrame = isTraceLine && shouldIgnore(line);
+ if (isTraceLine && !isInternalFrame) {
+ if (indentStackFrames && line.charAt(0) !== " ") {
+ line = " " + line;
+ }
+ ret.push(line);
+ }
+ }
+ return ret;
+}
+
+function stackFramesAsArray(error) {
+ var stack = error.stack.replace(/\s+$/g, "").split("\n");
+ for (var i = 0; i < stack.length; ++i) {
+ var line = stack[i];
+ if (" (No stack trace)" === line || stackFramePattern.test(line)) {
+ break;
+ }
+ }
+ if (i > 0) {
+ stack = stack.slice(i);
+ }
+ return stack;
+}
+
+function parseStackAndMessage(error) {
+ var stack = error.stack;
+ var message = error.toString();
+ stack = typeof stack === "string" && stack.length > 0
+ ? stackFramesAsArray(error) : [" (No stack trace)"];
+ return {
+ message: message,
+ stack: cleanStack(stack)
+ };
+}
+
+function formatAndLogError(error, title, isSoft) {
+ if (typeof console !== "undefined") {
+ var message;
+ if (util.isObject(error)) {
+ var stack = error.stack;
+ message = title + formatStack(stack, error);
+ } else {
+ message = title + String(error);
+ }
+ if (typeof printWarning === "function") {
+ printWarning(message, isSoft);
+ } else if (typeof console.log === "function" ||
+ typeof console.log === "object") {
+ console.log(message);
+ }
+ }
+}
+
+function fireRejectionEvent(name, localHandler, reason, promise) {
+ var localEventFired = false;
+ try {
+ if (typeof localHandler === "function") {
+ localEventFired = true;
+ if (name === "rejectionHandled") {
+ localHandler(promise);
+ } else {
+ localHandler(reason, promise);
+ }
+ }
+ } catch (e) {
+ async.throwLater(e);
+ }
+
+ if (name === "unhandledRejection") {
+ if (!activeFireEvent(name, reason, promise) && !localEventFired) {
+ formatAndLogError(reason, "Unhandled rejection ");
+ }
+ } else {
+ activeFireEvent(name, promise);
+ }
+}
+
+function formatNonError(obj) {
+ var str;
+ if (typeof obj === "function") {
+ str = "[function " +
+ (obj.name || "anonymous") +
+ "]";
+ } else {
+ str = obj && typeof obj.toString === "function"
+ ? obj.toString() : util.toString(obj);
+ var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
+ if (ruselessToString.test(str)) {
+ try {
+ var newStr = JSON.stringify(obj);
+ str = newStr;
+ }
+ catch(e) {
+
+ }
+ }
+ if (str.length === 0) {
+ str = "(empty array)";
+ }
+ }
+ return ("(<" + snip(str) + ">, no stack trace)");
+}
+
+function snip(str) {
+ var maxChars = 41;
+ if (str.length < maxChars) {
+ return str;
+ }
+ return str.substr(0, maxChars - 3) + "...";
+}
+
+function longStackTracesIsSupported() {
+ return typeof captureStackTrace === "function";
+}
+
+var shouldIgnore = function() { return false; };
+var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
+function parseLineInfo(line) {
+ var matches = line.match(parseLineInfoRegex);
+ if (matches) {
+ return {
+ fileName: matches[1],
+ line: parseInt(matches[2], 10)
+ };
+ }
+}
+
+function setBounds(firstLineError, lastLineError) {
+ if (!longStackTracesIsSupported()) return;
+ var firstStackLines = firstLineError.stack.split("\n");
+ var lastStackLines = lastLineError.stack.split("\n");
+ var firstIndex = -1;
+ var lastIndex = -1;
+ var firstFileName;
+ var lastFileName;
+ for (var i = 0; i < firstStackLines.length; ++i) {
+ var result = parseLineInfo(firstStackLines[i]);
+ if (result) {
+ firstFileName = result.fileName;
+ firstIndex = result.line;
+ break;
+ }
+ }
+ for (var i = 0; i < lastStackLines.length; ++i) {
+ var result = parseLineInfo(lastStackLines[i]);
+ if (result) {
+ lastFileName = result.fileName;
+ lastIndex = result.line;
+ break;
+ }
+ }
+ if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
+ firstFileName !== lastFileName || firstIndex >= lastIndex) {
+ return;
+ }
+
+ shouldIgnore = function(line) {
+ if (bluebirdFramePattern.test(line)) return true;
+ var info = parseLineInfo(line);
+ if (info) {
+ if (info.fileName === firstFileName &&
+ (firstIndex <= info.line && info.line <= lastIndex)) {
+ return true;
+ }
+ }
+ return false;
+ };
+}
+
+function CapturedTrace(parent) {
+ this._parent = parent;
+ this._promisesCreated = 0;
+ var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
+ captureStackTrace(this, CapturedTrace);
+ if (length > 32) this.uncycle();
+}
+util.inherits(CapturedTrace, Error);
+Context.CapturedTrace = CapturedTrace;
+
+CapturedTrace.prototype.uncycle = function() {
+ var length = this._length;
+ if (length < 2) return;
+ var nodes = [];
+ var stackToIndex = {};
+
+ for (var i = 0, node = this; node !== undefined; ++i) {
+ nodes.push(node);
+ node = node._parent;
+ }
+ length = this._length = i;
+ for (var i = length - 1; i >= 0; --i) {
+ var stack = nodes[i].stack;
+ if (stackToIndex[stack] === undefined) {
+ stackToIndex[stack] = i;
+ }
+ }
+ for (var i = 0; i < length; ++i) {
+ var currentStack = nodes[i].stack;
+ var index = stackToIndex[currentStack];
+ if (index !== undefined && index !== i) {
+ if (index > 0) {
+ nodes[index - 1]._parent = undefined;
+ nodes[index - 1]._length = 1;
+ }
+ nodes[i]._parent = undefined;
+ nodes[i]._length = 1;
+ var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
+
+ if (index < length - 1) {
+ cycleEdgeNode._parent = nodes[index + 1];
+ cycleEdgeNode._parent.uncycle();
+ cycleEdgeNode._length =
+ cycleEdgeNode._parent._length + 1;
+ } else {
+ cycleEdgeNode._parent = undefined;
+ cycleEdgeNode._length = 1;
+ }
+ var currentChildLength = cycleEdgeNode._length + 1;
+ for (var j = i - 2; j >= 0; --j) {
+ nodes[j]._length = currentChildLength;
+ currentChildLength++;
+ }
+ return;
+ }
+ }
+};
+
+CapturedTrace.prototype.attachExtraTrace = function(error) {
+ if (error.__stackCleaned__) return;
+ this.uncycle();
+ var parsed = parseStackAndMessage(error);
+ var message = parsed.message;
+ var stacks = [parsed.stack];
+
+ var trace = this;
+ while (trace !== undefined) {
+ stacks.push(cleanStack(trace.stack.split("\n")));
+ trace = trace._parent;
+ }
+ removeCommonRoots(stacks);
+ removeDuplicateOrEmptyJumps(stacks);
+ util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
+ util.notEnumerableProp(error, "__stackCleaned__", true);
+};
+
+var captureStackTrace = (function stackDetection() {
+ var v8stackFramePattern = /^\s*at\s*/;
+ var v8stackFormatter = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if (error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ if (typeof Error.stackTraceLimit === "number" &&
+ typeof Error.captureStackTrace === "function") {
+ Error.stackTraceLimit += 6;
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ var captureStackTrace = Error.captureStackTrace;
+
+ shouldIgnore = function(line) {
+ return bluebirdFramePattern.test(line);
+ };
+ return function(receiver, ignoreUntil) {
+ Error.stackTraceLimit += 6;
+ captureStackTrace(receiver, ignoreUntil);
+ Error.stackTraceLimit -= 6;
+ };
+ }
+ var err = new Error();
+
+ if (typeof err.stack === "string" &&
+ err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
+ stackFramePattern = /@/;
+ formatStack = v8stackFormatter;
+ indentStackFrames = true;
+ return function captureStackTrace(o) {
+ o.stack = new Error().stack;
+ };
+ }
+
+ var hasStackAfterThrow;
+ try { throw new Error(); }
+ catch(e) {
+ hasStackAfterThrow = ("stack" in e);
+ }
+ if (!("stack" in err) && hasStackAfterThrow &&
+ typeof Error.stackTraceLimit === "number") {
+ stackFramePattern = v8stackFramePattern;
+ formatStack = v8stackFormatter;
+ return function captureStackTrace(o) {
+ Error.stackTraceLimit += 6;
+ try { throw new Error(); }
+ catch(e) { o.stack = e.stack; }
+ Error.stackTraceLimit -= 6;
+ };
+ }
+
+ formatStack = function(stack, error) {
+ if (typeof stack === "string") return stack;
+
+ if ((typeof error === "object" ||
+ typeof error === "function") &&
+ error.name !== undefined &&
+ error.message !== undefined) {
+ return error.toString();
+ }
+ return formatNonError(error);
+ };
+
+ return null;
+
+})([]);
+
+if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
+ printWarning = function (message) {
+ console.warn(message);
+ };
+ if (util.isNode && process.stderr.isTTY) {
+ printWarning = function(message, isSoft) {
+ var color = isSoft ? "\u001b[33m" : "\u001b[31m";
+ console.warn(color + message + "\u001b[0m\n");
+ };
+ } else if (!util.isNode && typeof (new Error().stack) === "string") {
+ printWarning = function(message, isSoft) {
+ console.warn("%c" + message,
+ isSoft ? "color: darkorange" : "color: red");
+ };
+ }
+}
+
+var config = {
+ warnings: warnings,
+ longStackTraces: false,
+ cancellation: false,
+ monitoring: false
+};
+
+if (longStackTraces) Promise.longStackTraces();
+
+return {
+ longStackTraces: function() {
+ return config.longStackTraces;
+ },
+ warnings: function() {
+ return config.warnings;
+ },
+ cancellation: function() {
+ return config.cancellation;
+ },
+ monitoring: function() {
+ return config.monitoring;
+ },
+ propagateFromFunction: function() {
+ return propagateFromFunction;
+ },
+ boundValueFunction: function() {
+ return boundValueFunction;
+ },
+ checkForgottenReturns: checkForgottenReturns,
+ setBounds: setBounds,
+ warn: warn,
+ deprecated: deprecated,
+ CapturedTrace: CapturedTrace,
+ fireDomEvent: fireDomEvent,
+ fireGlobalEvent: fireGlobalEvent
+};
+};
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..3717911
--- /dev/null
+++ b/node_modules/bluebird/js/release/finally.js
@@ -0,0 +1,111 @@
+"use strict";
+module.exports = function(Promise, tryConvertToPromise) {
+var util = require("./util");
+var CancellationError = Promise.CancellationError;
+var errorObj = util.errorObj;
+
+function PassThroughHandlerContext(promise, type, handler) {
+ this.promise = promise;
+ this.type = type;
+ this.handler = handler;
+ this.called = false;
+ this.cancelPromise = null;
+}
+
+PassThroughHandlerContext.prototype.isFinallyHandler = function() {
+ return this.type === 0;
+};
+
+function FinallyHandlerCancelReaction(finallyHandler) {
+ this.finallyHandler = finallyHandler;
+}
+
+FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
+ checkCancel(this.finallyHandler);
+};
+
+function checkCancel(ctx, reason) {
+ if (ctx.cancelPromise != null) {
+ if (arguments.length > 1) {
+ ctx.cancelPromise._reject(reason);
+ } else {
+ ctx.cancelPromise._cancel();
+ }
+ ctx.cancelPromise = null;
+ return true;
+ }
+ return false;
+}
+
+function succeed() {
+ return finallyHandler.call(this, this.promise._target()._settledValue());
+}
+function fail(reason) {
+ if (checkCancel(this, reason)) return;
+ errorObj.e = reason;
+ return errorObj;
+}
+function finallyHandler(reasonOrValue) {
+ var promise = this.promise;
+ var handler = this.handler;
+
+ if (!this.called) {
+ this.called = true;
+ var ret = this.isFinallyHandler()
+ ? handler.call(promise._boundValue())
+ : handler.call(promise._boundValue(), reasonOrValue);
+ if (ret !== undefined) {
+ promise._setReturnedNonUndefined();
+ var maybePromise = tryConvertToPromise(ret, promise);
+ if (maybePromise instanceof Promise) {
+ if (this.cancelPromise != null) {
+ if (maybePromise._isCancelled()) {
+ var reason =
+ new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ errorObj.e = reason;
+ return errorObj;
+ } else if (maybePromise.isPending()) {
+ maybePromise._attachCancellationCallback(
+ new FinallyHandlerCancelReaction(this));
+ }
+ }
+ return maybePromise._then(
+ succeed, fail, undefined, this, undefined);
+ }
+ }
+ }
+
+ if (promise.isRejected()) {
+ checkCancel(this);
+ errorObj.e = reasonOrValue;
+ return errorObj;
+ } else {
+ checkCancel(this);
+ return reasonOrValue;
+ }
+}
+
+Promise.prototype._passThrough = function(handler, type, success, fail) {
+ if (typeof handler !== "function") return this.then();
+ return this._then(success,
+ fail,
+ undefined,
+ new PassThroughHandlerContext(this, type, handler),
+ undefined);
+};
+
+Promise.prototype.lastly =
+Promise.prototype["finally"] = function (handler) {
+ return this._passThrough(handler,
+ 0,
+ finallyHandler,
+ finallyHandler);
+};
+
+Promise.prototype.tap = function (handler) {
+ return this._passThrough(handler, 1, finallyHandler);
+};
+
+return PassThroughHandlerContext;
+};
diff --git a/node_modules/bluebird/js/release/generators.js b/node_modules/bluebird/js/release/generators.js
new file mode 100644
index 0000000..40e9b1f
--- /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", 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..335fbff
--- /dev/null
+++ b/node_modules/bluebird/js/release/promise.js
@@ -0,0 +1,773 @@
+"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);
+var catchFilter = require("./catch_filter")(NEXT_FILTER);
+var nodebackForPromise = require("./nodeback");
+var errorObj = util.errorObj;
+var tryCatch = util.tryCatch;
+function check(self, executor) {
+ if (typeof executor !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(executor));
+ }
+ if (self.constructor !== Promise) {
+ throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
+ }
+}
+
+function Promise(executor) {
+ this._bitField = 0;
+ this._fulfillmentHandler0 = undefined;
+ this._rejectionHandler0 = undefined;
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ if (executor !== INTERNAL) {
+ check(this, executor);
+ this._resolveFromExecutor(executor);
+ }
+ this._promiseCreated();
+ this._fireEvent("promiseCreated", this);
+}
+
+Promise.prototype.toString = function () {
+ return "[object Promise]";
+};
+
+Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
+ var len = arguments.length;
+ if (len > 1) {
+ var catchInstances = new Array(len - 1),
+ j = 0, i;
+ for (i = 0; i < len - 1; ++i) {
+ var item = arguments[i];
+ if (util.isObject(item)) {
+ catchInstances[j++] = item;
+ } else {
+ return apiRejection("expecting an object but got " +
+ "A catch statement predicate " + util.classString(item));
+ }
+ }
+ catchInstances.length = j;
+ fn = arguments[i];
+ return this.then(undefined, catchFilter(catchInstances, fn, this));
+ }
+ return this.then(undefined, fn);
+};
+
+Promise.prototype.reflect = function () {
+ return this._then(reflectHandler,
+ reflectHandler, undefined, this, undefined);
+};
+
+Promise.prototype.then = function (didFulfill, didReject) {
+ if (debug.warnings() && arguments.length > 0 &&
+ typeof didFulfill !== "function" &&
+ typeof didReject !== "function") {
+ var msg = ".then() only accepts functions but was passed: " +
+ util.classString(didFulfill);
+ if (arguments.length > 1) {
+ msg += ", " + util.classString(didReject);
+ }
+ this._warn(msg);
+ }
+ return this._then(didFulfill, didReject, undefined, undefined, undefined);
+};
+
+Promise.prototype.done = function (didFulfill, didReject) {
+ var promise =
+ this._then(didFulfill, didReject, undefined, undefined, undefined);
+ promise._setIsFinal();
+};
+
+Promise.prototype.spread = function (fn) {
+ if (typeof fn !== "function") {
+ return apiRejection("expecting a function but got " + util.classString(fn));
+ }
+ return this.all()._then(fn, undefined, undefined, APPLY, undefined);
+};
+
+Promise.prototype.toJSON = function () {
+ var ret = {
+ isFulfilled: false,
+ isRejected: false,
+ fulfillmentValue: undefined,
+ rejectionReason: undefined
+ };
+ if (this.isFulfilled()) {
+ ret.fulfillmentValue = this.value();
+ ret.isFulfilled = true;
+ } else if (this.isRejected()) {
+ ret.rejectionReason = this.reason();
+ ret.isRejected = true;
+ }
+ return ret;
+};
+
+Promise.prototype.all = function () {
+ if (arguments.length > 0) {
+ this._warn(".all() was passed arguments but it does not take any");
+ }
+ return new PromiseArray(this).promise();
+};
+
+Promise.prototype.error = function (fn) {
+ return this.caught(util.originatesFromRejection, fn);
+};
+
+Promise.getNewLibraryCopy = module.exports;
+
+Promise.is = function (val) {
+ return val instanceof Promise;
+};
+
+Promise.fromNode = Promise.fromCallback = function(fn) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
+ : false;
+ var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
+ if (result === errorObj) {
+ ret._rejectCallback(result.e, true);
+ }
+ if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
+ return ret;
+};
+
+Promise.all = function (promises) {
+ return new PromiseArray(promises).promise();
+};
+
+Promise.cast = function (obj) {
+ var ret = tryConvertToPromise(obj);
+ if (!(ret instanceof Promise)) {
+ ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._setFulfilled();
+ ret._rejectionHandler0 = obj;
+ }
+ return ret;
+};
+
+Promise.resolve = Promise.fulfilled = Promise.cast;
+
+Promise.reject = Promise.rejected = function (reason) {
+ var ret = new Promise(INTERNAL);
+ ret._captureStackTrace();
+ ret._rejectCallback(reason, true);
+ return ret;
+};
+
+Promise.setScheduler = function(fn) {
+ if (typeof fn !== "function") {
+ throw new TypeError("expecting a function but got " + util.classString(fn));
+ }
+ return async.setScheduler(fn);
+};
+
+Promise.prototype._then = function (
+ didFulfill,
+ didReject,
+ _, receiver,
+ internalData
+) {
+ var haveInternalData = internalData !== undefined;
+ var promise = haveInternalData ? internalData : new Promise(INTERNAL);
+ var target = this._target();
+ var bitField = target._bitField;
+
+ if (!haveInternalData) {
+ promise._propagateFrom(this, 3);
+ promise._captureStackTrace();
+ if (receiver === undefined &&
+ ((this._bitField & 2097152) !== 0)) {
+ if (!((bitField & 50397184) === 0)) {
+ receiver = this._boundValue();
+ } else {
+ receiver = target === this ? undefined : this._boundTo;
+ }
+ }
+ this._fireEvent("promiseChained", this, promise);
+ }
+
+ var domain = getDomain();
+ if (!((bitField & 50397184) === 0)) {
+ var handler, value, settler = target._settlePromiseCtx;
+ if (((bitField & 33554432) !== 0)) {
+ value = target._rejectionHandler0;
+ handler = didFulfill;
+ } else if (((bitField & 16777216) !== 0)) {
+ value = target._fulfillmentHandler0;
+ handler = didReject;
+ target._unsetRejectionIsUnhandled();
+ } else {
+ settler = target._settlePromiseLateCancellationObserver;
+ value = new CancellationError("late cancellation observer");
+ target._attachExtraTrace(value);
+ handler = didReject;
+ }
+
+ async.invoke(settler, target, {
+ handler: domain === null ? handler
+ : (typeof handler === "function" &&
+ util.domainBind(domain, handler)),
+ promise: promise,
+ receiver: receiver,
+ value: value
+ });
+ } else {
+ target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
+ }
+
+ return promise;
+};
+
+Promise.prototype._length = function () {
+ return this._bitField & 65535;
+};
+
+Promise.prototype._isFateSealed = function () {
+ return (this._bitField & 117506048) !== 0;
+};
+
+Promise.prototype._isFollowing = function () {
+ return (this._bitField & 67108864) === 67108864;
+};
+
+Promise.prototype._setLength = function (len) {
+ this._bitField = (this._bitField & -65536) |
+ (len & 65535);
+};
+
+Promise.prototype._setFulfilled = function () {
+ this._bitField = this._bitField | 33554432;
+ this._fireEvent("promiseFulfilled", this);
+};
+
+Promise.prototype._setRejected = function () {
+ this._bitField = this._bitField | 16777216;
+ this._fireEvent("promiseRejected", this);
+};
+
+Promise.prototype._setFollowing = function () {
+ this._bitField = this._bitField | 67108864;
+ this._fireEvent("promiseResolved", this);
+};
+
+Promise.prototype._setIsFinal = function () {
+ this._bitField = this._bitField | 4194304;
+};
+
+Promise.prototype._isFinal = function () {
+ return (this._bitField & 4194304) > 0;
+};
+
+Promise.prototype._unsetCancelled = function() {
+ this._bitField = this._bitField & (~65536);
+};
+
+Promise.prototype._setCancelled = function() {
+ this._bitField = this._bitField | 65536;
+ this._fireEvent("promiseCancelled", this);
+};
+
+Promise.prototype._setWillBeCancelled = function() {
+ this._bitField = this._bitField | 8388608;
+};
+
+Promise.prototype._setAsyncGuaranteed = function() {
+ if (async.hasCustomScheduler()) return;
+ this._bitField = this._bitField | 134217728;
+};
+
+Promise.prototype._receiverAt = function (index) {
+ var ret = index === 0 ? this._receiver0 : this[
+ index * 4 - 4 + 3];
+ if (ret === UNDEFINED_BINDING) {
+ return undefined;
+ } else if (ret === undefined && this._isBound()) {
+ return this._boundValue();
+ }
+ return ret;
+};
+
+Promise.prototype._promiseAt = function (index) {
+ return this[
+ index * 4 - 4 + 2];
+};
+
+Promise.prototype._fulfillmentHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 0];
+};
+
+Promise.prototype._rejectionHandlerAt = function (index) {
+ return this[
+ index * 4 - 4 + 1];
+};
+
+Promise.prototype._boundValue = function() {};
+
+Promise.prototype._migrateCallback0 = function (follower) {
+ var bitField = follower._bitField;
+ var fulfill = follower._fulfillmentHandler0;
+ var reject = follower._rejectionHandler0;
+ var promise = follower._promise0;
+ var receiver = follower._receiverAt(0);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._migrateCallbackAt = function (follower, index) {
+ var fulfill = follower._fulfillmentHandlerAt(index);
+ var reject = follower._rejectionHandlerAt(index);
+ var promise = follower._promiseAt(index);
+ var receiver = follower._receiverAt(index);
+ if (receiver === undefined) receiver = UNDEFINED_BINDING;
+ this._addCallbacks(fulfill, reject, promise, receiver, null);
+};
+
+Promise.prototype._addCallbacks = function (
+ fulfill,
+ reject,
+ promise,
+ receiver,
+ domain
+) {
+ var index = this._length();
+
+ if (index >= 65535 - 4) {
+ index = 0;
+ this._setLength(0);
+ }
+
+ if (index === 0) {
+ this._promise0 = promise;
+ this._receiver0 = receiver;
+ if (typeof fulfill === "function") {
+ this._fulfillmentHandler0 =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this._rejectionHandler0 =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ } else {
+ var base = index * 4 - 4;
+ this[base + 2] = promise;
+ this[base + 3] = receiver;
+ if (typeof fulfill === "function") {
+ this[base + 0] =
+ domain === null ? fulfill : util.domainBind(domain, fulfill);
+ }
+ if (typeof reject === "function") {
+ this[base + 1] =
+ domain === null ? reject : util.domainBind(domain, reject);
+ }
+ }
+ this._setLength(index + 1);
+ return index;
+};
+
+Promise.prototype._proxy = function (proxyable, arg) {
+ this._addCallbacks(undefined, undefined, arg, proxyable, null);
+};
+
+Promise.prototype._resolveCallback = function(value, shouldBind) {
+ if (((this._bitField & 117506048) !== 0)) return;
+ if (value === this)
+ return this._rejectCallback(makeSelfResolutionError(), false);
+ var maybePromise = tryConvertToPromise(value, this);
+ if (!(maybePromise instanceof Promise)) return this._fulfill(value);
+
+ if (shouldBind) this._propagateFrom(maybePromise, 2);
+
+ var promise = maybePromise._target();
+
+ if (promise === this) {
+ this._reject(makeSelfResolutionError());
+ return;
+ }
+
+ var bitField = promise._bitField;
+ if (((bitField & 50397184) === 0)) {
+ var len = this._length();
+ if (len > 0) promise._migrateCallback0(this);
+ for (var i = 1; i < len; ++i) {
+ promise._migrateCallbackAt(this, i);
+ }
+ this._setFollowing();
+ this._setLength(0);
+ this._setFollowee(promise);
+ } else if (((bitField & 33554432) !== 0)) {
+ this._fulfill(promise._value());
+ } else if (((bitField & 16777216) !== 0)) {
+ this._reject(promise._reason());
+ } else {
+ var reason = new CancellationError("late cancellation observer");
+ promise._attachExtraTrace(reason);
+ this._reject(reason);
+ }
+};
+
+Promise.prototype._rejectCallback =
+function(reason, synchronous, ignoreNonErrorWarnings) {
+ var trace = util.ensureErrorObject(reason);
+ var hasStack = trace === reason;
+ if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
+ var message = "a promise was rejected with a non-error: " +
+ util.classString(reason);
+ this._warn(message, true);
+ }
+ this._attachExtraTrace(trace, synchronous ? hasStack : false);
+ this._reject(reason);
+};
+
+Promise.prototype._resolveFromExecutor = function (executor) {
+ var promise = this;
+ this._captureStackTrace();
+ this._pushContext();
+ var synchronous = true;
+ var r = this._execute(executor, function(value) {
+ promise._resolveCallback(value);
+ }, function (reason) {
+ promise._rejectCallback(reason, synchronous);
+ });
+ synchronous = false;
+ this._popContext();
+
+ if (r !== undefined) {
+ promise._rejectCallback(r, true);
+ }
+};
+
+Promise.prototype._settlePromiseFromHandler = function (
+ handler, receiver, value, promise
+) {
+ var bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+ promise._pushContext();
+ var x;
+ if (receiver === APPLY) {
+ if (!value || typeof value.length !== "number") {
+ x = errorObj;
+ x.e = new TypeError("cannot .spread() a non-array: " +
+ util.classString(value));
+ } else {
+ x = tryCatch(handler).apply(this._boundValue(), value);
+ }
+ } else {
+ x = tryCatch(handler).call(receiver, value);
+ }
+ var promiseCreated = promise._popContext();
+ bitField = promise._bitField;
+ if (((bitField & 65536) !== 0)) return;
+
+ if (x === NEXT_FILTER) {
+ promise._reject(value);
+ } else if (x === errorObj) {
+ promise._rejectCallback(x.e, false);
+ } else {
+ debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
+ promise._resolveCallback(x);
+ }
+};
+
+Promise.prototype._target = function() {
+ var ret = this;
+ while (ret._isFollowing()) ret = ret._followee();
+ return ret;
+};
+
+Promise.prototype._followee = function() {
+ return this._rejectionHandler0;
+};
+
+Promise.prototype._setFollowee = function(promise) {
+ this._rejectionHandler0 = promise;
+};
+
+Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
+ var isPromise = promise instanceof Promise;
+ var bitField = this._bitField;
+ var asyncGuaranteed = ((bitField & 134217728) !== 0);
+ if (((bitField & 65536) !== 0)) {
+ if (isPromise) promise._invokeInternalOnCancel();
+
+ if (receiver instanceof PassThroughHandlerContext &&
+ receiver.isFinallyHandler()) {
+ receiver.cancelPromise = promise;
+ if (tryCatch(handler).call(receiver, value) === errorObj) {
+ promise._reject(errorObj.e);
+ }
+ } else if (handler === reflectHandler) {
+ promise._fulfill(reflectHandler.call(receiver));
+ } else if (receiver instanceof Proxyable) {
+ receiver._promiseCancelled(promise);
+ } else if (isPromise || promise instanceof PromiseArray) {
+ promise._cancel();
+ } else {
+ receiver.cancel();
+ }
+ } else if (typeof handler === "function") {
+ if (!isPromise) {
+ handler.call(receiver, value, promise);
+ } else {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (receiver instanceof Proxyable) {
+ if (!receiver._isResolved()) {
+ if (((bitField & 33554432) !== 0)) {
+ receiver._promiseFulfilled(value, promise);
+ } else {
+ receiver._promiseRejected(value, promise);
+ }
+ }
+ } else if (isPromise) {
+ if (asyncGuaranteed) promise._setAsyncGuaranteed();
+ if (((bitField & 33554432) !== 0)) {
+ promise._fulfill(value);
+ } else {
+ promise._reject(value);
+ }
+ }
+};
+
+Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
+ var handler = ctx.handler;
+ var promise = ctx.promise;
+ var receiver = ctx.receiver;
+ var value = ctx.value;
+ if (typeof handler === "function") {
+ if (!(promise instanceof Promise)) {
+ handler.call(receiver, value, promise);
+ } else {
+ this._settlePromiseFromHandler(handler, receiver, value, promise);
+ }
+ } else if (promise instanceof Promise) {
+ promise._reject(value);
+ }
+};
+
+Promise.prototype._settlePromiseCtx = function(ctx) {
+ this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
+};
+
+Promise.prototype._settlePromise0 = function(handler, value, bitField) {
+ var promise = this._promise0;
+ var receiver = this._receiverAt(0);
+ this._promise0 = undefined;
+ this._receiver0 = undefined;
+ this._settlePromise(promise, handler, receiver, value);
+};
+
+Promise.prototype._clearCallbackDataAtIndex = function(index) {
+ var base = index * 4 - 4;
+ this[base + 2] =
+ this[base + 3] =
+ this[base + 0] =
+ this[base + 1] = undefined;
+};
+
+Promise.prototype._fulfill = function (value) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ if (value === this) {
+ var err = makeSelfResolutionError();
+ this._attachExtraTrace(err);
+ return this._reject(err);
+ }
+ this._setFulfilled();
+ this._rejectionHandler0 = value;
+
+ if ((bitField & 65535) > 0) {
+ if (((bitField & 134217728) !== 0)) {
+ this._settlePromises();
+ } else {
+ async.settlePromises(this);
+ }
+ }
+};
+
+Promise.prototype._reject = function (reason) {
+ var bitField = this._bitField;
+ if (((bitField & 117506048) >>> 16)) return;
+ this._setRejected();
+ this._fulfillmentHandler0 = reason;
+
+ if (this._isFinal()) {
+ return async.fatalError(reason, util.isNode);
+ }
+
+ if ((bitField & 65535) > 0) {
+ async.settlePromises(this);
+ } else {
+ this._ensurePossibleRejectionHandled();
+ }
+};
+
+Promise.prototype._fulfillPromises = function (len, value) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._fulfillmentHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, value);
+ }
+};
+
+Promise.prototype._rejectPromises = function (len, reason) {
+ for (var i = 1; i < len; i++) {
+ var handler = this._rejectionHandlerAt(i);
+ var promise = this._promiseAt(i);
+ var receiver = this._receiverAt(i);
+ this._clearCallbackDataAtIndex(i);
+ this._settlePromise(promise, handler, receiver, reason);
+ }
+};
+
+Promise.prototype._settlePromises = function () {
+ var bitField = this._bitField;
+ var len = (bitField & 65535);
+
+ if (len > 0) {
+ if (((bitField & 16842752) !== 0)) {
+ var reason = this._fulfillmentHandler0;
+ this._settlePromise0(this._rejectionHandler0, reason, bitField);
+ this._rejectPromises(len, reason);
+ } else {
+ var value = this._rejectionHandler0;
+ this._settlePromise0(this._fulfillmentHandler0, value, bitField);
+ this._fulfillPromises(len, value);
+ }
+ this._setLength(0);
+ }
+ this._clearCancellationData();
+};
+
+Promise.prototype._settledValue = function() {
+ var bitField = this._bitField;
+ if (((bitField & 33554432) !== 0)) {
+ return this._rejectionHandler0;
+ } else if (((bitField & 16777216) !== 0)) {
+ return this._fulfillmentHandler0;
+ }
+};
+
+function deferResolve(v) {this.promise._resolveCallback(v);}
+function deferReject(v) {this.promise._rejectCallback(v, false);}
+
+Promise.defer = Promise.pending = function() {
+ debug.deprecated("Promise.defer", "new Promise");
+ var promise = new Promise(INTERNAL);
+ return {
+ promise: promise,
+ resolve: deferResolve,
+ reject: deferReject
+ };
+};
+
+util.notEnumerableProp(Promise,
+ "_makeSelfResolutionError",
+ makeSelfResolutionError);
+
+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.4.6";
+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..f874df3
--- /dev/null
+++ b/node_modules/bluebird/js/release/promise_array.js
@@ -0,0 +1,184 @@
+"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 {};
+ }
+}
+
+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..fc981ce
--- /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, -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..84d57d5
--- /dev/null
+++ b/node_modules/bluebird/js/release/queue.js
@@ -0,0 +1,90 @@
+"use strict";
+function arrayMove(src, srcIndex, dst, dstIndex, len) {
+ for (var j = 0; j < len; ++j) {
+ dst[j + dstIndex] = src[j + srcIndex];
+ src[j + srcIndex] = void 0;
+ }
+}
+
+function Queue(capacity) {
+ this._capacity = capacity;
+ this._length = 0;
+ this._front = 0;
+}
+
+Queue.prototype._willBeOverCapacity = function (size) {
+ return this._capacity < size;
+};
+
+Queue.prototype._pushOne = function (arg) {
+ var length = this.length();
+ this._checkCapacity(length + 1);
+ var i = (this._front + length) & (this._capacity - 1);
+ this[i] = arg;
+ this._length = length + 1;
+};
+
+Queue.prototype._unshiftOne = function(value) {
+ var capacity = this._capacity;
+ this._checkCapacity(this.length() + 1);
+ var front = this._front;
+ var i = (((( front - 1 ) &
+ ( capacity - 1) ) ^ capacity ) - capacity );
+ this[i] = value;
+ this._front = i;
+ this._length = this.length() + 1;
+};
+
+Queue.prototype.unshift = function(fn, receiver, arg) {
+ this._unshiftOne(arg);
+ this._unshiftOne(receiver);
+ this._unshiftOne(fn);
+};
+
+Queue.prototype.push = function (fn, receiver, arg) {
+ var length = this.length() + 3;
+ if (this._willBeOverCapacity(length)) {
+ this._pushOne(fn);
+ this._pushOne(receiver);
+ this._pushOne(arg);
+ return;
+ }
+ var j = this._front + length - 3;
+ this._checkCapacity(length);
+ var wrapMask = this._capacity - 1;
+ this[(j + 0) & wrapMask] = fn;
+ this[(j + 1) & wrapMask] = receiver;
+ this[(j + 2) & wrapMask] = arg;
+ this._length = length;
+};
+
+Queue.prototype.shift = function () {
+ var front = this._front,
+ ret = this[front];
+
+ this[front] = undefined;
+ this._front = (front + 1) & (this._capacity - 1);
+ this._length--;
+ return ret;
+};
+
+Queue.prototype.length = function () {
+ return this._length;
+};
+
+Queue.prototype._checkCapacity = function (size) {
+ if (this._capacity < size) {
+ this._resizeTo(this._capacity << 1);
+ }
+};
+
+Queue.prototype._resizeTo = function (capacity) {
+ var oldCapacity = this._capacity;
+ this._capacity = capacity;
+ var front = this._front;
+ var length = this._length;
+ var moveItemsCount = (front + length) & (oldCapacity - 1);
+ arrayMove(this, 0, this, oldCapacity, moveItemsCount);
+};
+
+module.exports = Queue;
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..a190728
--- /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..830ed7d
--- /dev/null
+++ b/node_modules/bluebird/js/release/util.js
@@ -0,0 +1,375 @@
+"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 !== null &&
+ typeof obj === "object" &&
+ typeof obj.message === "string" &&
+ typeof obj.name === "string";
+}
+
+function markAsOriginatingFromRejection(e) {
+ try {
+ notEnumerableProp(e, "isOperational", true);
+ }
+ catch(ignore) {}
+}
+
+function originatesFromRejection(e) {
+ if (e == null) return false;
+ return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
+ e["isOperational"] === true);
+}
+
+function canAttachTrace(obj) {
+ return isError(obj) && es5.propertyIsWritable(obj, "stack");
+}
+
+var ensureErrorObject = (function() {
+ if (!("stack" in new Error())) {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ try {throw new Error(safeToString(value));}
+ catch(err) {return err;}
+ };
+ } else {
+ return function(value) {
+ if (canAttachTrace(value)) return value;
+ return new Error(safeToString(value));
+ };
+ }
+})();
+
+function classString(obj) {
+ return {}.toString.call(obj);
+}
+
+function copyDescriptors(from, to, filter) {
+ var keys = es5.names(from);
+ for (var i = 0; i < keys.length; ++i) {
+ var key = keys[i];
+ if (filter(key)) {
+ try {
+ es5.defineProperty(to, key, es5.getDescriptor(from, key));
+ } catch (ignore) {}
+ }
+ }
+}
+
+var asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ }
+ return null;
+};
+
+if (typeof Symbol !== "undefined" && Symbol.iterator) {
+ var ArrayFrom = typeof Array.from === "function" ? function(v) {
+ return Array.from(v);
+ } : function(v) {
+ var ret = [];
+ var it = v[Symbol.iterator]();
+ var itResult;
+ while (!((itResult = it.next()).done)) {
+ ret.push(itResult.value);
+ }
+ return ret;
+ };
+
+ asArray = function(v) {
+ if (es5.isArray(v)) {
+ return v;
+ } else if (v != null && typeof v[Symbol.iterator] === "function") {
+ return ArrayFrom(v);
+ }
+ return null;
+ };
+}
+
+var isNode = typeof process !== "undefined" &&
+ classString(process).toLowerCase() === "[object process]";
+
+function env(key, def) {
+ return isNode ? process.env[key] : def;
+}
+
+function getNativePromise() {
+ if (typeof Promise === "function") {
+ try {
+ var promise = new Promise(function(){});
+ if ({}.toString.call(promise) === "[object Promise]") {
+ return Promise;
+ }
+ } catch (e) {}
+ }
+}
+
+function domainBind(self, cb) {
+ return self.bind(cb);
+}
+
+var ret = {
+ isClass: isClass,
+ isIdentifier: isIdentifier,
+ inheritedDataKeys: inheritedDataKeys,
+ getDataPropertyOrDefault: getDataPropertyOrDefault,
+ thrower: thrower,
+ isArray: es5.isArray,
+ asArray: asArray,
+ notEnumerableProp: notEnumerableProp,
+ isPrimitive: isPrimitive,
+ isObject: isObject,
+ isError: isError,
+ canEvaluate: canEvaluate,
+ errorObj: errorObj,
+ tryCatch: tryCatch,
+ inherits: inherits,
+ withAppended: withAppended,
+ maybeWrapAsError: maybeWrapAsError,
+ toFastProperties: toFastProperties,
+ filledRange: filledRange,
+ toString: safeToString,
+ canAttachTrace: canAttachTrace,
+ ensureErrorObject: ensureErrorObject,
+ originatesFromRejection: originatesFromRejection,
+ markAsOriginatingFromRejection: markAsOriginatingFromRejection,
+ classString: classString,
+ copyDescriptors: copyDescriptors,
+ hasDevTools: typeof chrome !== "undefined" && chrome &&
+ typeof chrome.loadTimes === "function",
+ isNode: isNode,
+ env: env,
+ global: globalObject,
+ getNativePromise: getNativePromise,
+ domainBind: domainBind
+};
+ret.isRecentNode = ret.isNode && (function() {
+ var version = process.versions.node.split(".").map(Number);
+ return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
+})();
+
+if (ret.isNode) ret.toFastProperties(process);
+
+try {throw new Error(); } catch (e) {ret.lastLineError = e;}
+module.exports = ret;
diff --git a/node_modules/bluebird/package.json b/node_modules/bluebird/package.json
new file mode 100644
index 0000000..9ac0058
--- /dev/null
+++ b/node_modules/bluebird/package.json
@@ -0,0 +1,76 @@
+{
+ "name": "bluebird",
+ "description": "Full featured Promises/A+ implementation with exceptionally good performance",
+ "version": "3.4.6",
+ "keywords": [
+ "promise",
+ "performance",
+ "promises",
+ "promises-a",
+ "promises-aplus",
+ "async",
+ "await",
+ "deferred",
+ "deferreds",
+ "future",
+ "flow control",
+ "dsl",
+ "fluent interface"
+ ],
+ "scripts": {
+ "lint": "node scripts/jshint.js",
+ "test": "node tools/test.js",
+ "istanbul": "istanbul",
+ "prepublish": "npm run generate-browser-core && npm run generate-browser-full",
+ "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify",
+ "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"
+ },
+ "homepage": "https://github.com/petkaantonov/bluebird",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/petkaantonov/bluebird.git"
+ },
+ "bugs": {
+ "url": "http://github.com/petkaantonov/bluebird/issues"
+ },
+ "license": "MIT",
+ "author": {
+ "name": "Petka Antonov",
+ "email": "petka_antonov@hotmail.com",
+ "url": "http://github.com/petkaantonov/"
+ },
+ "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",
+ "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",
+ "kefir": "^2.4.1"
+ },
+ "readmeFilename": "README.md",
+ "main": "./js/release/bluebird.js",
+ "browser": "./js/browser/bluebird.js",
+ "files": [
+ "js/browser",
+ "js/release",
+ "LICENSE"
+ ]
+}
diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md
new file mode 100644
index 0000000..f3ea28c
--- /dev/null
+++ b/node_modules/body-parser/HISTORY.md
@@ -0,0 +1,464 @@
+1.15.2 / 2016-06-19
+===================
+
+ * deps: bytes@2.4.0
+ * deps: content-type@~1.0.2
+ - perf: enable strict mode
+ * deps: http-errors@~1.5.0
+ - Use `setprototypeof` module to replace `__proto__` setting
+ - deps: statuses@'>= 1.3.0 < 2'
+ - perf: enable strict mode
+ * deps: qs@6.2.0
+ * deps: raw-body@~2.1.7
+ - deps: bytes@2.4.0
+ - perf: remove double-cleanup on happy path
+ * deps: type-is@~1.6.13
+ - deps: mime-types@~2.1.11
+
+1.15.1 / 2016-05-05
+===================
+
+ * deps: bytes@2.3.0
+ - Drop partial bytes on all parsed units
+ - Fix parsing byte string that looks like hex
+ * deps: raw-body@~2.1.6
+ - deps: bytes@2.3.0
+ * deps: type-is@~1.6.12
+ - deps: mime-types@~2.1.10
+
+1.15.0 / 2016-02-10
+===================
+
+ * deps: http-errors@~1.4.0
+ - Add `HttpError` export, for `err instanceof createError.HttpError`
+ - deps: inherits@2.0.1
+ - deps: statuses@'>= 1.2.1 < 2'
+ * deps: qs@6.1.0
+ * deps: type-is@~1.6.11
+ - deps: mime-types@~2.1.9
+
+1.14.2 / 2015-12-16
+===================
+
+ * deps: bytes@2.2.0
+ * deps: iconv-lite@0.4.13
+ * deps: qs@5.2.0
+ * deps: raw-body@~2.1.5
+ - deps: bytes@2.2.0
+ - deps: iconv-lite@0.4.13
+ * deps: type-is@~1.6.10
+ - deps: mime-types@~2.1.8
+
+1.14.1 / 2015-09-27
+===================
+
+ * Fix issue where invalid charset results in 400 when `verify` used
+ * deps: iconv-lite@0.4.12
+ - Fix CESU-8 decoding in Node.js 4.x
+ * deps: raw-body@~2.1.4
+ - Fix masking critical errors from `iconv-lite`
+ - deps: iconv-lite@0.4.12
+ * deps: type-is@~1.6.9
+ - deps: mime-types@~2.1.7
+
+1.14.0 / 2015-09-16
+===================
+
+ * Fix JSON strict parse error to match syntax errors
+ * Provide static `require` analysis in `urlencoded` parser
+ * deps: depd@~1.1.0
+ - Support web browser loading
+ * deps: qs@5.1.0
+ * deps: raw-body@~2.1.3
+ - Fix sync callback when attaching data listener causes sync read
+ * deps: type-is@~1.6.8
+ - Fix type error when given invalid type to match against
+ - deps: mime-types@~2.1.6
+
+1.13.3 / 2015-07-31
+===================
+
+ * deps: type-is@~1.6.6
+ - deps: mime-types@~2.1.4
+
+1.13.2 / 2015-07-05
+===================
+
+ * deps: iconv-lite@0.4.11
+ * deps: qs@4.0.0
+ - Fix dropping parameters like `hasOwnProperty`
+ - Fix user-visible incompatibilities from 3.1.0
+ - Fix various parsing edge cases
+ * deps: raw-body@~2.1.2
+ - Fix error stack traces to skip `makeError`
+ - deps: iconv-lite@0.4.11
+ * deps: type-is@~1.6.4
+ - deps: mime-types@~2.1.2
+ - perf: enable strict mode
+ - perf: remove argument reassignment
+
+1.13.1 / 2015-06-16
+===================
+
+ * deps: qs@2.4.2
+ - Downgraded from 3.1.0 because of user-visible incompatibilities
+
+1.13.0 / 2015-06-14
+===================
+
+ * Add `statusCode` property on `Error`s, in addition to `status`
+ * Change `type` default to `application/json` for JSON parser
+ * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser
+ * Provide static `require` analysis
+ * Use the `http-errors` module to generate errors
+ * deps: bytes@2.1.0
+ - Slight optimizations
+ * deps: iconv-lite@0.4.10
+ - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails
+ - Leading BOM is now removed when decoding
+ * deps: on-finished@~2.3.0
+ - Add defined behavior for HTTP `CONNECT` requests
+ - Add defined behavior for HTTP `Upgrade` requests
+ - deps: ee-first@1.1.1
+ * deps: qs@3.1.0
+ - Fix dropping parameters like `hasOwnProperty`
+ - Fix various parsing edge cases
+ - Parsed object now has `null` prototype
+ * deps: raw-body@~2.1.1
+ - Use `unpipe` module for unpiping requests
+ - deps: iconv-lite@0.4.10
+ * deps: type-is@~1.6.3
+ - deps: mime-types@~2.1.1
+ - perf: reduce try block size
+ - perf: remove bitwise operations
+ * perf: enable strict mode
+ * perf: remove argument reassignment
+ * perf: remove delete call
+
+1.12.4 / 2015-05-10
+===================
+
+ * deps: debug@~2.2.0
+ * deps: qs@2.4.2
+ - Fix allowing parameters like `constructor`
+ * deps: on-finished@~2.2.1
+ * deps: raw-body@~2.0.1
+ - Fix a false-positive when unpiping in Node.js 0.8
+ - deps: bytes@2.0.1
+ * deps: type-is@~1.6.2
+ - deps: mime-types@~2.0.11
+
+1.12.3 / 2015-04-15
+===================
+
+ * Slight efficiency improvement when not debugging
+ * deps: depd@~1.0.1
+ * deps: iconv-lite@0.4.8
+ - Add encoding alias UNICODE-1-1-UTF-7
+ * deps: raw-body@1.3.4
+ - Fix hanging callback if request aborts during read
+ - deps: iconv-lite@0.4.8
+
+1.12.2 / 2015-03-16
+===================
+
+ * deps: qs@2.4.1
+ - Fix error when parameter `hasOwnProperty` is present
+
+1.12.1 / 2015-03-15
+===================
+
+ * deps: debug@~2.1.3
+ - Fix high intensity foreground color for bold
+ - deps: ms@0.7.0
+ * deps: type-is@~1.6.1
+ - deps: mime-types@~2.0.10
+
+1.12.0 / 2015-02-13
+===================
+
+ * add `debug` messages
+ * accept a function for the `type` option
+ * use `content-type` to parse `Content-Type` headers
+ * deps: iconv-lite@0.4.7
+ - Gracefully support enumerables on `Object.prototype`
+ * deps: raw-body@1.3.3
+ - deps: iconv-lite@0.4.7
+ * deps: type-is@~1.6.0
+ - fix argument reassignment
+ - fix false-positives in `hasBody` `Transfer-Encoding` check
+ - support wildcard for both type and subtype (`*/*`)
+ - deps: mime-types@~2.0.9
+
+1.11.0 / 2015-01-30
+===================
+
+ * make internal `extended: true` depth limit infinity
+ * deps: type-is@~1.5.6
+ - deps: mime-types@~2.0.8
+
+1.10.2 / 2015-01-20
+===================
+
+ * deps: iconv-lite@0.4.6
+ - Fix rare aliases of single-byte encodings
+ * deps: raw-body@1.3.2
+ - deps: iconv-lite@0.4.6
+
+1.10.1 / 2015-01-01
+===================
+
+ * deps: on-finished@~2.2.0
+ * deps: type-is@~1.5.5
+ - deps: mime-types@~2.0.7
+
+1.10.0 / 2014-12-02
+===================
+
+ * make internal `extended: true` array limit dynamic
+
+1.9.3 / 2014-11-21
+==================
+
+ * deps: iconv-lite@0.4.5
+ - Fix Windows-31J and X-SJIS encoding support
+ * deps: qs@2.3.3
+ - Fix `arrayLimit` behavior
+ * deps: raw-body@1.3.1
+ - deps: iconv-lite@0.4.5
+ * deps: type-is@~1.5.3
+ - deps: mime-types@~2.0.3
+
+1.9.2 / 2014-10-27
+==================
+
+ * deps: qs@2.3.2
+ - Fix parsing of mixed objects and values
+
+1.9.1 / 2014-10-22
+==================
+
+ * deps: on-finished@~2.1.1
+ - Fix handling of pipelined requests
+ * deps: qs@2.3.0
+ - Fix parsing of mixed implicit and explicit arrays
+ * deps: type-is@~1.5.2
+ - deps: mime-types@~2.0.2
+
+1.9.0 / 2014-09-24
+==================
+
+ * include the charset in "unsupported charset" error message
+ * include the encoding in "unsupported content encoding" error message
+ * deps: depd@~1.0.0
+
+1.8.4 / 2014-09-23
+==================
+
+ * fix content encoding to be case-insensitive
+
+1.8.3 / 2014-09-19
+==================
+
+ * deps: qs@2.2.4
+ - Fix issue with object keys starting with numbers truncated
+
+1.8.2 / 2014-09-15
+==================
+
+ * deps: depd@0.4.5
+
+1.8.1 / 2014-09-07
+==================
+
+ * deps: media-typer@0.3.0
+ * deps: type-is@~1.5.1
+
+1.8.0 / 2014-09-05
+==================
+
+ * make empty-body-handling consistent between chunked requests
+ - empty `json` produces `{}`
+ - empty `raw` produces `new Buffer(0)`
+ - empty `text` produces `''`
+ - empty `urlencoded` produces `{}`
+ * deps: qs@2.2.3
+ - Fix issue where first empty value in array is discarded
+ * deps: type-is@~1.5.0
+ - fix `hasbody` to be true for `content-length: 0`
+
+1.7.0 / 2014-09-01
+==================
+
+ * add `parameterLimit` option to `urlencoded` parser
+ * change `urlencoded` extended array limit to 100
+ * respond with 413 when over `parameterLimit` in `urlencoded`
+
+1.6.7 / 2014-08-29
+==================
+
+ * deps: qs@2.2.2
+ - Remove unnecessary cloning
+
+1.6.6 / 2014-08-27
+==================
+
+ * deps: qs@2.2.0
+ - Array parsing fix
+ - Performance improvements
+
+1.6.5 / 2014-08-16
+==================
+
+ * deps: on-finished@2.1.0
+
+1.6.4 / 2014-08-14
+==================
+
+ * deps: qs@1.2.2
+
+1.6.3 / 2014-08-10
+==================
+
+ * deps: qs@1.2.1
+
+1.6.2 / 2014-08-07
+==================
+
+ * deps: qs@1.2.0
+ - Fix parsing array of objects
+
+1.6.1 / 2014-08-06
+==================
+
+ * deps: qs@1.1.0
+ - Accept urlencoded square brackets
+ - Accept empty values in implicit array notation
+
+1.6.0 / 2014-08-05
+==================
+
+ * deps: qs@1.0.2
+ - Complete rewrite
+ - Limits array length to 20
+ - Limits object depth to 5
+ - Limits parameters to 1,000
+
+1.5.2 / 2014-07-27
+==================
+
+ * deps: depd@0.4.4
+ - Work-around v8 generating empty stack traces
+
+1.5.1 / 2014-07-26
+==================
+
+ * deps: depd@0.4.3
+ - Fix exception when global `Error.stackTraceLimit` is too low
+
+1.5.0 / 2014-07-20
+==================
+
+ * deps: depd@0.4.2
+ - Add `TRACE_DEPRECATION` environment variable
+ - Remove non-standard grey color from color output
+ - Support `--no-deprecation` argument
+ - Support `--trace-deprecation` argument
+ * deps: iconv-lite@0.4.4
+ - Added encoding UTF-7
+ * deps: raw-body@1.3.0
+ - deps: iconv-lite@0.4.4
+ - Added encoding UTF-7
+ - Fix `Cannot switch to old mode now` error on Node.js 0.10+
+ * deps: type-is@~1.3.2
+
+1.4.3 / 2014-06-19
+==================
+
+ * deps: type-is@1.3.1
+ - fix global variable leak
+
+1.4.2 / 2014-06-19
+==================
+
+ * deps: type-is@1.3.0
+ - improve type parsing
+
+1.4.1 / 2014-06-19
+==================
+
+ * fix urlencoded extended deprecation message
+
+1.4.0 / 2014-06-19
+==================
+
+ * add `text` parser
+ * add `raw` parser
+ * check accepted charset in content-type (accepts utf-8)
+ * check accepted encoding in content-encoding (accepts identity)
+ * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed
+ * deprecate `urlencoded()` without provided `extended` option
+ * lazy-load urlencoded parsers
+ * parsers split into files for reduced mem usage
+ * support gzip and deflate bodies
+ - set `inflate: false` to turn off
+ * deps: raw-body@1.2.2
+ - Support all encodings from `iconv-lite`
+
+1.3.1 / 2014-06-11
+==================
+
+ * deps: type-is@1.2.1
+ - Switch dependency from mime to mime-types@1.0.0
+
+1.3.0 / 2014-05-31
+==================
+
+ * add `extended` option to urlencoded parser
+
+1.2.2 / 2014-05-27
+==================
+
+ * deps: raw-body@1.1.6
+ - assert stream encoding on node.js 0.8
+ - assert stream encoding on node.js < 0.10.6
+ - deps: bytes@1
+
+1.2.1 / 2014-05-26
+==================
+
+ * invoke `next(err)` after request fully read
+ - prevents hung responses and socket hang ups
+
+1.2.0 / 2014-05-11
+==================
+
+ * add `verify` option
+ * deps: type-is@1.2.0
+ - support suffix matching
+
+1.1.2 / 2014-05-11
+==================
+
+ * improve json parser speed
+
+1.1.1 / 2014-05-11
+==================
+
+ * fix repeated limit parsing with every request
+
+1.1.0 / 2014-05-10
+==================
+
+ * add `type` option
+ * deps: pin for safety and consistency
+
+1.0.2 / 2014-04-14
+==================
+
+ * use `type-is` module
+
+1.0.1 / 2014-03-20
+==================
+
+ * lower default limits to 100kb
diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE
new file mode 100644
index 0000000..386b7b6
--- /dev/null
+++ b/node_modules/body-parser/LICENSE
@@ -0,0 +1,23 @@
+(The MIT License)
+
+Copyright (c) 2014 Jonathan Ong
+Copyright (c) 2014-2015 Douglas Christopher Wilson
+
+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/body-parser/README.md b/node_modules/body-parser/README.md
new file mode 100644
index 0000000..6376536
--- /dev/null
+++ b/node_modules/body-parser/README.md
@@ -0,0 +1,409 @@
+# body-parser
+
+[![NPM Version][npm-image]][npm-url]
+[![NPM Downloads][downloads-image]][downloads-url]
+[![Build Status][travis-image]][travis-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+[![Gratipay][gratipay-image]][gratipay-url]
+
+Node.js body parsing middleware.
+
+Parse incoming request bodies in a middleware before your handlers, availabe
+under the `req.body` property.
+
+[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/).
+
+_This does not handle multipart bodies_, due to their complex and typically
+large nature. For multipart bodies, you may be interested in the following
+modules:
+
+ * [busboy](https://www.npmjs.org/package/busboy#readme) and
+ [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme)
+ * [multiparty](https://www.npmjs.org/package/multiparty#readme) and
+ [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme)
+ * [formidable](https://www.npmjs.org/package/formidable#readme)
+ * [multer](https://www.npmjs.org/package/multer#readme)
+
+This module provides the following parsers:
+
+ * [JSON body parser](#bodyparserjsonoptions)
+ * [Raw body parser](#bodyparserrawoptions)
+ * [Text body parser](#bodyparsertextoptions)
+ * [URL-encoded form body parser](#bodyparserurlencodedoptions)
+
+Other body parsers you might be interested in:
+
+- [body](https://www.npmjs.org/package/body#readme)
+- [co-body](https://www.npmjs.org/package/co-body#readme)
+
+## Installation
+
+```sh
+$ npm install body-parser
+```
+
+## API
+
+```js
+var bodyParser = require('body-parser')
+```
+
+The `bodyParser` object exposes various factories to create middlewares. All
+middlewares will populate the `req.body` property with the parsed body, or an
+empty object (`{}`) if there was no body to parse (or an error was returned).
+
+The various errors returned by this module are described in the
+[errors section](#errors).
+
+### bodyParser.json(options)
+
+Returns middleware that only parses `json`. This parser accepts any Unicode
+encoding of the body and supports automatic inflation of `gzip` and `deflate`
+encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`).
+
+#### Options
+
+The `json` function takes an option `options` object that may contain any of
+the following keys:
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### reviver
+
+The `reviver` option is passed directly to `JSON.parse` as the second
+argument. You can find more information on this argument
+[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter).
+
+##### strict
+
+When set to `true`, will only accept arrays and objects; when `false` will
+accept anything `JSON.parse` accepts. Defaults to `true`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a function or a string. If a string, `type` option
+is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme)
+library and this can be an extension name (like `json`), a mime type (like
+`application/json`), or a mime type with a wildcard (like `*/*` or `*/json`).
+If a function, the `type` option is called as `fn(req)` and the request is
+parsed if it returns a truthy value. Defaults to `application/json`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.raw(options)
+
+Returns middleware that parses all bodies as a `Buffer`. This parser
+supports automatic inflation of `gzip` and `deflate` encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This will be a `Buffer` object
+of the body.
+
+#### Options
+
+The `raw` function takes an option `options` object that may contain any of
+the following keys:
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a function or a string. If a string, `type` option
+is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme)
+library and this can be an extension name (like `bin`), a mime type (like
+`application/octet-stream`), or a mime type with a wildcard (like `*/*` or
+`application/*`). If a function, the `type` option is called as `fn(req)`
+and the request is parsed if it returns a truthy value. Defaults to
+`application/octet-stream`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.text(options)
+
+Returns middleware that parses all bodies as a string. This parser supports
+automatic inflation of `gzip` and `deflate` encodings.
+
+A new `body` string containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This will be a string of the
+body.
+
+#### Options
+
+The `text` function takes an option `options` object that may contain any of
+the following keys:
+
+##### defaultCharset
+
+Specify the default character set for the text content if the charset is not
+specified in the `Content-Type` header of the request. Defaults to `utf-8`.
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a function or a string. If a string, `type` option
+is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme)
+library and this can be an extension name (like `txt`), a mime type (like
+`text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`).
+If a function, the `type` option is called as `fn(req)` and the request is
+parsed if it returns a truthy value. Defaults to `text/plain`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+### bodyParser.urlencoded(options)
+
+Returns middleware that only parses `urlencoded` bodies. This parser accepts
+only UTF-8 encoding of the body and supports automatic inflation of `gzip`
+and `deflate` encodings.
+
+A new `body` object containing the parsed data is populated on the `request`
+object after the middleware (i.e. `req.body`). This object will contain
+key-value pairs, where the value can be a string or array (when `extended` is
+`false`), or any type (when `extended` is `true`).
+
+#### Options
+
+The `urlencoded` function takes an option `options` object that may contain
+any of the following keys:
+
+##### extended
+
+The `extended` option allows to choose between parsing the URL-encoded data
+with the `querystring` library (when `false`) or the `qs` library (when
+`true`). The "extended" syntax allows for rich objects and arrays to be
+encoded into the URL-encoded format, allowing for a JSON-like experience
+with URL-encoded. For more information, please
+[see the qs library](https://www.npmjs.org/package/qs#readme).
+
+Defaults to `true`, but using the default has been deprecated. Please
+research into the difference between `qs` and `querystring` and choose the
+appropriate setting.
+
+##### inflate
+
+When set to `true`, then deflated (compressed) bodies will be inflated; when
+`false`, deflated bodies are rejected. Defaults to `true`.
+
+##### limit
+
+Controls the maximum request body size. If this is a number, then the value
+specifies the number of bytes; if it is a string, the value is passed to the
+[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults
+to `'100kb'`.
+
+##### parameterLimit
+
+The `parameterLimit` option controls the maximum number of parameters that
+are allowed in the URL-encoded data. If a request contains more parameters
+than this value, a 413 will be returned to the client. Defaults to `1000`.
+
+##### type
+
+The `type` option is used to determine what media type the middleware will
+parse. This option can be a function or a string. If a string, `type` option
+is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme)
+library and this can be an extension name (like `urlencoded`), a mime type (like
+`application/x-www-form-urlencoded`), or a mime type with a wildcard (like
+`*/x-www-form-urlencoded`). If a function, the `type` option is called as
+`fn(req)` and the request is parsed if it returns a truthy value. Defaults
+to `application/x-www-form-urlencoded`.
+
+##### verify
+
+The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`,
+where `buf` is a `Buffer` of the raw request body and `encoding` is the
+encoding of the request. The parsing can be aborted by throwing an error.
+
+## Errors
+
+The middlewares provided by this module create errors depending on the error
+condition during parsing. The errors will typically have a `status` property
+that contains the suggested HTTP response code and a `body` property containing
+the read body, if available.
+
+The following are the common errors emitted, though any error can come through
+for various reasons.
+
+### content encoding unsupported
+
+This error will occur when the request had a `Content-Encoding` header that
+contained an encoding but the "inflation" option was set to `false`. The
+`status` property is set to `415`.
+
+### request aborted
+
+This error will occur when the request is aborted by the client before reading
+the body has finished. The `received` property will be set to the number of
+bytes received before the request was aborted and the `expected` property is
+set to the number of expected bytes. The `status` property is set to `400`.
+
+### request entity too large
+
+This error will occur when the request body's size is larger than the "limit"
+option. The `limit` property will be set to the byte limit and the `length`
+property will be set to the request body's length. The `status` property is
+set to `413`.
+
+### request size did not match content length
+
+This error will occur when the request's length did not match the length from
+the `Content-Length` header. This typically occurs when the request is malformed,
+typically when the `Content-Length` header was calculated based on characters
+instead of bytes. The `status` property is set to `400`.
+
+### stream encoding should not be set
+
+This error will occur when something called the `req.setEncoding` method prior
+to this middleware. This module operates directly on bytes only and you cannot
+call `req.setEncoding` when using this module. The `status` property is set to
+`500`.
+
+### unsupported charset "BOGUS"
+
+This error will occur when the request had a charset parameter in the
+`Content-Type` header, but the `iconv-lite` module does not support it OR the
+parser does not support it. The charset is contained in the message as well
+as in the `charset` property. The `status` property is set to `415`.
+
+### unsupported content encoding "bogus"
+
+This error will occur when the request had a `Content-Encoding` header that
+contained an unsupported encoding. The encoding is contained in the message
+as well as in the `encoding` property. The `status` property is set to `415`.
+
+## Examples
+
+### Express/Connect top-level generic
+
+This example demonstrates adding a generic JSON and URL-encoded parser as a
+top-level middleware, which will parse the bodies of all incoming requests.
+This is the simplest setup.
+
+```js
+var express = require('express')
+var bodyParser = require('body-parser')
+
+var app = express()
+
+// parse application/x-www-form-urlencoded
+app.use(bodyParser.urlencoded({ extended: false }))
+
+// parse application/json
+app.use(bodyParser.json())
+
+app.use(function (req, res) {
+ res.setHeader('Content-Type', 'text/plain')
+ res.write('you posted:\n')
+ res.end(JSON.stringify(req.body, null, 2))
+})
+```
+
+### Express route-specific
+
+This example demonstrates adding body parsers specifically to the routes that
+need them. In general, this is the most recommended way to use body-parser with
+Express.
+
+```js
+var express = require('express')
+var bodyParser = require('body-parser')
+
+var app = express()
+
+// create application/json parser
+var jsonParser = bodyParser.json()
+
+// create application/x-www-form-urlencoded parser
+var urlencodedParser = bodyParser.urlencoded({ extended: false })
+
+// POST /login gets urlencoded bodies
+app.post('/login', urlencodedParser, function (req, res) {
+ if (!req.body) return res.sendStatus(400)
+ res.send('welcome, ' + req.body.username)
+})
+
+// POST /api/users gets JSON bodies
+app.post('/api/users', jsonParser, function (req, res) {
+ if (!req.body) return res.sendStatus(400)
+ // create user in req.body
+})
+```
+
+### Change accepted type for parsers
+
+All the parsers accept a `type` option which allows you to change the
+`Content-Type` that the middleware will parse.
+
+```js
+// parse various different custom JSON types as JSON
+app.use(bodyParser.json({ type: 'application/*+json' }))
+
+// parse some custom thing into a Buffer
+app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
+
+// parse an HTML body into a string
+app.use(bodyParser.text({ type: 'text/html' }))
+```
+
+## License
+
+[MIT](LICENSE)
+
+[npm-image]: https://img.shields.io/npm/v/body-parser.svg
+[npm-url]: https://npmjs.org/package/body-parser
+[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg
+[travis-url]: https://travis-ci.org/expressjs/body-parser
+[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg
+[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
+[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg
+[downloads-url]: https://npmjs.org/package/body-parser
+[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg
+[gratipay-url]: https://www.gratipay.com/dougwilson/
diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js
new file mode 100644
index 0000000..93c3a1f
--- /dev/null
+++ b/node_modules/body-parser/index.js
@@ -0,0 +1,157 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var deprecate = require('depd')('body-parser')
+
+/**
+ * Cache of loaded parsers.
+ * @private
+ */
+
+var parsers = Object.create(null)
+
+/**
+ * @typedef Parsers
+ * @type {function}
+ * @property {function} json
+ * @property {function} raw
+ * @property {function} text
+ * @property {function} urlencoded
+ */
+
+/**
+ * Module exports.
+ * @type {Parsers}
+ */
+
+exports = module.exports = deprecate.function(bodyParser,
+ 'bodyParser: use individual json/urlencoded middlewares')
+
+/**
+ * JSON parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'json', {
+ configurable: true,
+ enumerable: true,
+ get: createParserGetter('json')
+})
+
+/**
+ * Raw parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'raw', {
+ configurable: true,
+ enumerable: true,
+ get: createParserGetter('raw')
+})
+
+/**
+ * Text parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'text', {
+ configurable: true,
+ enumerable: true,
+ get: createParserGetter('text')
+})
+
+/**
+ * URL-encoded parser.
+ * @public
+ */
+
+Object.defineProperty(exports, 'urlencoded', {
+ configurable: true,
+ enumerable: true,
+ get: createParserGetter('urlencoded')
+})
+
+/**
+ * Create a middleware to parse json and urlencoded bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @deprecated
+ * @public
+ */
+
+function bodyParser (options) {
+ var opts = {}
+
+ // exclude type option
+ if (options) {
+ for (var prop in options) {
+ if (prop !== 'type') {
+ opts[prop] = options[prop]
+ }
+ }
+ }
+
+ var _urlencoded = exports.urlencoded(opts)
+ var _json = exports.json(opts)
+
+ return function bodyParser (req, res, next) {
+ _json(req, res, function (err) {
+ if (err) return next(err)
+ _urlencoded(req, res, next)
+ })
+ }
+}
+
+/**
+ * Create a getter for loading a parser.
+ * @private
+ */
+
+function createParserGetter (name) {
+ return function get () {
+ return loadParser(name)
+ }
+}
+
+/**
+ * Load a parser module.
+ * @private
+ */
+
+function loadParser (parserName) {
+ var parser = parsers[parserName]
+
+ if (parser !== undefined) {
+ return parser
+ }
+
+ // this uses a switch for static require analysis
+ switch (parserName) {
+ case 'json':
+ parser = require('./lib/types/json')
+ break
+ case 'raw':
+ parser = require('./lib/types/raw')
+ break
+ case 'text':
+ parser = require('./lib/types/text')
+ break
+ case 'urlencoded':
+ parser = require('./lib/types/urlencoded')
+ break
+ }
+
+ // store to prevent invoking require()
+ return (parsers[parserName] = parser)
+}
diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js
new file mode 100644
index 0000000..3c0fe93
--- /dev/null
+++ b/node_modules/body-parser/lib/read.js
@@ -0,0 +1,188 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var createError = require('http-errors')
+var getBody = require('raw-body')
+var iconv = require('iconv-lite')
+var onFinished = require('on-finished')
+var zlib = require('zlib')
+
+/**
+ * Module exports.
+ */
+
+module.exports = read
+
+/**
+ * Read a request into a buffer and parse.
+ *
+ * @param {object} req
+ * @param {object} res
+ * @param {function} next
+ * @param {function} parse
+ * @param {function} debug
+ * @param {object} [options]
+ * @api private
+ */
+
+function read (req, res, next, parse, debug, options) {
+ var length
+ var opts = options || {}
+ var stream
+
+ // flag as parsed
+ req._body = true
+
+ // read options
+ var encoding = opts.encoding !== null
+ ? opts.encoding || 'utf-8'
+ : null
+ var verify = opts.verify
+
+ try {
+ // get the content stream
+ stream = contentstream(req, debug, opts.inflate)
+ length = stream.length
+ stream.length = undefined
+ } catch (err) {
+ return next(err)
+ }
+
+ // set raw-body options
+ opts.length = length
+ opts.encoding = verify
+ ? null
+ : encoding
+
+ // assert charset is supported
+ if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
+ return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
+ charset: encoding.toLowerCase()
+ }))
+ }
+
+ // read body
+ debug('read body')
+ getBody(stream, opts, function (err, body) {
+ if (err) {
+ // default to 400
+ setErrorStatus(err, 400)
+
+ // echo back charset
+ if (err.type === 'encoding.unsupported') {
+ err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
+ charset: encoding.toLowerCase()
+ })
+ }
+
+ // read off entire request
+ stream.resume()
+ onFinished(req, function onfinished () {
+ next(err)
+ })
+ return
+ }
+
+ // verify
+ if (verify) {
+ try {
+ debug('verify body')
+ verify(req, res, body, encoding)
+ } catch (err) {
+ // default to 403
+ setErrorStatus(err, 403)
+ next(err)
+ return
+ }
+ }
+
+ // parse
+ var str
+ try {
+ debug('parse body')
+ str = typeof body !== 'string' && encoding !== null
+ ? iconv.decode(body, encoding)
+ : body
+ req.body = parse(str)
+ } catch (err) {
+ err.body = str === undefined
+ ? body
+ : str
+
+ // default to 400
+ setErrorStatus(err, 400)
+
+ next(err)
+ return
+ }
+
+ next()
+ })
+}
+
+/**
+ * Get the content stream of the request.
+ *
+ * @param {object} req
+ * @param {function} debug
+ * @param {boolean} [inflate=true]
+ * @return {object}
+ * @api private
+ */
+
+function contentstream (req, debug, inflate) {
+ var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
+ var length = req.headers['content-length']
+ var stream
+
+ debug('content-encoding "%s"', encoding)
+
+ if (inflate === false && encoding !== 'identity') {
+ throw createError(415, 'content encoding unsupported')
+ }
+
+ switch (encoding) {
+ case 'deflate':
+ stream = zlib.createInflate()
+ debug('inflate body')
+ req.pipe(stream)
+ break
+ case 'gzip':
+ stream = zlib.createGunzip()
+ debug('gunzip body')
+ req.pipe(stream)
+ break
+ case 'identity':
+ stream = req
+ stream.length = length
+ break
+ default:
+ throw createError(415, 'unsupported content encoding "' + encoding + '"', {
+ encoding: encoding
+ })
+ }
+
+ return stream
+}
+
+/**
+ * Set a status on an error object, if ones does not exist
+ * @private
+ */
+
+function setErrorStatus (error, status) {
+ if (!error.status && !error.statusCode) {
+ error.status = status
+ error.statusCode = status
+ }
+}
diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js
new file mode 100644
index 0000000..d0023c7
--- /dev/null
+++ b/node_modules/body-parser/lib/types/json.js
@@ -0,0 +1,175 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var bytes = require('bytes')
+var contentType = require('content-type')
+var createError = require('http-errors')
+var debug = require('debug')('body-parser:json')
+var read = require('../read')
+var typeis = require('type-is')
+
+/**
+ * Module exports.
+ */
+
+module.exports = json
+
+/**
+ * RegExp to match the first non-space in a string.
+ *
+ * Allowed whitespace is defined in RFC 7159:
+ *
+ * ws = *(
+ * %x20 / ; Space
+ * %x09 / ; Horizontal tab
+ * %x0A / ; Line feed or New line
+ * %x0D ) ; Carriage return
+ */
+
+var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex
+
+/**
+ * Create a middleware to parse JSON bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @public
+ */
+
+function json (options) {
+ var opts = options || {}
+
+ var limit = typeof opts.limit !== 'number'
+ ? bytes.parse(opts.limit || '100kb')
+ : opts.limit
+ var inflate = opts.inflate !== false
+ var reviver = opts.reviver
+ var strict = opts.strict !== false
+ var type = opts.type || 'application/json'
+ var verify = opts.verify || false
+
+ if (verify !== false && typeof verify !== 'function') {
+ throw new TypeError('option verify must be function')
+ }
+
+ // create the appropriate type checking function
+ var shouldParse = typeof type !== 'function'
+ ? typeChecker(type)
+ : type
+
+ function parse (body) {
+ if (body.length === 0) {
+ // special-case empty json body, as it's a common client-side mistake
+ // TODO: maybe make this configurable or part of "strict" option
+ return {}
+ }
+
+ if (strict) {
+ var first = firstchar(body)
+
+ if (first !== '{' && first !== '[') {
+ debug('strict violation')
+ throw new SyntaxError('Unexpected token ' + first)
+ }
+ }
+
+ debug('parse json')
+ return JSON.parse(body, reviver)
+ }
+
+ return function jsonParser (req, res, next) {
+ if (req._body) {
+ debug('body already parsed')
+ next()
+ return
+ }
+
+ req.body = req.body || {}
+
+ // skip requests without bodies
+ if (!typeis.hasBody(req)) {
+ debug('skip empty body')
+ next()
+ return
+ }
+
+ debug('content-type %j', req.headers['content-type'])
+
+ // determine if request should be parsed
+ if (!shouldParse(req)) {
+ debug('skip parsing')
+ next()
+ return
+ }
+
+ // assert charset per RFC 7159 sec 8.1
+ var charset = getCharset(req) || 'utf-8'
+ if (charset.substr(0, 4) !== 'utf-') {
+ debug('invalid charset')
+ next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
+ charset: charset
+ }))
+ return
+ }
+
+ // read
+ read(req, res, next, parse, debug, {
+ encoding: charset,
+ inflate: inflate,
+ limit: limit,
+ verify: verify
+ })
+ }
+}
+
+/**
+ * Get the first non-whitespace character in a string.
+ *
+ * @param {string} str
+ * @return {function}
+ * @api public
+ */
+
+function firstchar (str) {
+ var match = FIRST_CHAR_REGEXP.exec(str)
+ return match ? match[1] : ''
+}
+
+/**
+ * Get the charset of a request.
+ *
+ * @param {object} req
+ * @api private
+ */
+
+function getCharset (req) {
+ try {
+ return contentType.parse(req).parameters.charset.toLowerCase()
+ } catch (e) {
+ return undefined
+ }
+}
+
+/**
+ * Get the simple type checker.
+ *
+ * @param {string} type
+ * @return {function}
+ */
+
+function typeChecker (type) {
+ return function checkType (req) {
+ return Boolean(typeis(req, type))
+ }
+}
diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js
new file mode 100644
index 0000000..f5d1b67
--- /dev/null
+++ b/node_modules/body-parser/lib/types/raw.js
@@ -0,0 +1,101 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ */
+
+var bytes = require('bytes')
+var debug = require('debug')('body-parser:raw')
+var read = require('../read')
+var typeis = require('type-is')
+
+/**
+ * Module exports.
+ */
+
+module.exports = raw
+
+/**
+ * Create a middleware to parse raw bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @api public
+ */
+
+function raw (options) {
+ var opts = options || {}
+
+ var inflate = opts.inflate !== false
+ var limit = typeof opts.limit !== 'number'
+ ? bytes.parse(opts.limit || '100kb')
+ : opts.limit
+ var type = opts.type || 'application/octet-stream'
+ var verify = opts.verify || false
+
+ if (verify !== false && typeof verify !== 'function') {
+ throw new TypeError('option verify must be function')
+ }
+
+ // create the appropriate type checking function
+ var shouldParse = typeof type !== 'function'
+ ? typeChecker(type)
+ : type
+
+ function parse (buf) {
+ return buf
+ }
+
+ return function rawParser (req, res, next) {
+ if (req._body) {
+ debug('body already parsed')
+ next()
+ return
+ }
+
+ req.body = req.body || {}
+
+ // skip requests without bodies
+ if (!typeis.hasBody(req)) {
+ debug('skip empty body')
+ next()
+ return
+ }
+
+ debug('content-type %j', req.headers['content-type'])
+
+ // determine if request should be parsed
+ if (!shouldParse(req)) {
+ debug('skip parsing')
+ next()
+ return
+ }
+
+ // read
+ read(req, res, next, parse, debug, {
+ encoding: null,
+ inflate: inflate,
+ limit: limit,
+ verify: verify
+ })
+ }
+}
+
+/**
+ * Get the simple type checker.
+ *
+ * @param {string} type
+ * @return {function}
+ */
+
+function typeChecker (type) {
+ return function checkType (req) {
+ return Boolean(typeis(req, type))
+ }
+}
diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js
new file mode 100644
index 0000000..8bf2637
--- /dev/null
+++ b/node_modules/body-parser/lib/types/text.js
@@ -0,0 +1,121 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ */
+
+var bytes = require('bytes')
+var contentType = require('content-type')
+var debug = require('debug')('body-parser:text')
+var read = require('../read')
+var typeis = require('type-is')
+
+/**
+ * Module exports.
+ */
+
+module.exports = text
+
+/**
+ * Create a middleware to parse text bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @api public
+ */
+
+function text (options) {
+ var opts = options || {}
+
+ var defaultCharset = opts.defaultCharset || 'utf-8'
+ var inflate = opts.inflate !== false
+ var limit = typeof opts.limit !== 'number'
+ ? bytes.parse(opts.limit || '100kb')
+ : opts.limit
+ var type = opts.type || 'text/plain'
+ var verify = opts.verify || false
+
+ if (verify !== false && typeof verify !== 'function') {
+ throw new TypeError('option verify must be function')
+ }
+
+ // create the appropriate type checking function
+ var shouldParse = typeof type !== 'function'
+ ? typeChecker(type)
+ : type
+
+ function parse (buf) {
+ return buf
+ }
+
+ return function textParser (req, res, next) {
+ if (req._body) {
+ debug('body already parsed')
+ next()
+ return
+ }
+
+ req.body = req.body || {}
+
+ // skip requests without bodies
+ if (!typeis.hasBody(req)) {
+ debug('skip empty body')
+ next()
+ return
+ }
+
+ debug('content-type %j', req.headers['content-type'])
+
+ // determine if request should be parsed
+ if (!shouldParse(req)) {
+ debug('skip parsing')
+ next()
+ return
+ }
+
+ // get charset
+ var charset = getCharset(req) || defaultCharset
+
+ // read
+ read(req, res, next, parse, debug, {
+ encoding: charset,
+ inflate: inflate,
+ limit: limit,
+ verify: verify
+ })
+ }
+}
+
+/**
+ * Get the charset of a request.
+ *
+ * @param {object} req
+ * @api private
+ */
+
+function getCharset (req) {
+ try {
+ return contentType.parse(req).parameters.charset.toLowerCase()
+ } catch (e) {
+ return undefined
+ }
+}
+
+/**
+ * Get the simple type checker.
+ *
+ * @param {string} type
+ * @return {function}
+ */
+
+function typeChecker (type) {
+ return function checkType (req) {
+ return Boolean(typeis(req, type))
+ }
+}
diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js
new file mode 100644
index 0000000..08157ae
--- /dev/null
+++ b/node_modules/body-parser/lib/types/urlencoded.js
@@ -0,0 +1,279 @@
+/*!
+ * body-parser
+ * Copyright(c) 2014 Jonathan Ong
+ * Copyright(c) 2014-2015 Douglas Christopher Wilson
+ * MIT Licensed
+ */
+
+'use strict'
+
+/**
+ * Module dependencies.
+ * @private
+ */
+
+var bytes = require('bytes')
+var contentType = require('content-type')
+var createError = require('http-errors')
+var debug = require('debug')('body-parser:urlencoded')
+var deprecate = require('depd')('body-parser')
+var read = require('../read')
+var typeis = require('type-is')
+
+/**
+ * Module exports.
+ */
+
+module.exports = urlencoded
+
+/**
+ * Cache of parser modules.
+ */
+
+var parsers = Object.create(null)
+
+/**
+ * Create a middleware to parse urlencoded bodies.
+ *
+ * @param {object} [options]
+ * @return {function}
+ * @public
+ */
+
+function urlencoded (options) {
+ var opts = options || {}
+
+ // notice because option default will flip in next major
+ if (opts.extended === undefined) {
+ deprecate('undefined extended: provide extended option')
+ }
+
+ var extended = opts.extended !== false
+ var inflate = opts.inflate !== false
+ var limit = typeof opts.limit !== 'number'
+ ? bytes.parse(opts.limit || '100kb')
+ : opts.limit
+ var type = opts.type || 'application/x-www-form-urlencoded'
+ var verify = opts.verify || false
+
+ if (verify !== false && typeof verify !== 'function') {
+ throw new TypeError('option verify must be function')
+ }
+
+ // create the appropriate query parser
+ var queryparse = extended
+ ? extendedparser(opts)
+ : simpleparser(opts)
+
+ // create the appropriate type checking function
+ var shouldParse = typeof type !== 'function'
+ ? typeChecker(type)
+ : type
+
+ function parse (body) {
+ return body.length
+ ? queryparse(body)
+ : {}
+ }
+
+ return function urlencodedParser (req, res, next) {
+ if (req._body) {
+ debug('body already parsed')
+ next()
+ return
+ }
+
+ req.body = req.body || {}
+
+ // skip requests without bodies
+ if (!typeis.hasBody(req)) {
+ debug('skip empty body')
+ next()
+ return
+ }
+
+ debug('content-type %j', req.headers['content-type'])
+
+ // determine if request should be parsed
+ if (!shouldParse(req)) {
+ debug('skip parsing')
+ next()
+ return
+ }
+
+ // assert charset
+ var charset = getCharset(req) || 'utf-8'
+ if (charset !== 'utf-8') {
+ debug('invalid charset')
+ next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
+ charset: charset
+ }))
+ return
+ }
+
+ // read
+ read(req, res, next, parse, debug, {
+ debug: debug,
+ encoding: charset,
+ inflate: inflate,
+ limit: limit,
+ verify: verify
+ })
+ }
+}
+
+/**
+ * Get the extended query parser.
+ *
+ * @param {object} options
+ */
+
+function extendedparser (options) {
+ var parameterLimit = options.parameterLimit !== undefined
+ ? options.parameterLimit
+ : 1000
+ var parse = parser('qs')
+
+ if (isNaN(parameterLimit) || parameterLimit < 1) {
+ throw new TypeError('option parameterLimit must be a positive number')
+ }
+
+ if (isFinite(parameterLimit)) {
+ parameterLimit = parameterLimit | 0
+ }
+
+ return function queryparse (body) {
+ var paramCount = parameterCount(body, parameterLimit)
+
+ if (paramCount === undefined) {
+ debug('too many parameters')
+ throw createError(413, 'too many parameters')
+ }
+
+ var arrayLimit = Math.max(100, paramCount)
+
+ debug('parse extended urlencoding')
+ return parse(body, {
+ allowPrototypes: true,
+ arrayLimit: arrayLimit,
+ depth: Infinity,
+ parameterLimit: parameterLimit
+ })
+ }
+}
+
+/**
+ * Get the charset of a request.
+ *
+ * @param {object} req
+ * @api private
+ */
+
+function getCharset (req) {
+ try {
+ return contentType.parse(req).parameters.charset.toLowerCase()
+ } catch (e) {
+ return undefined
+ }
+}
+
+/**
+ * Count the number of parameters, stopping once limit reached
+ *
+ * @param {string} body
+ * @param {number} limit
+ * @api private
+ */
+
+function parameterCount (body, limit) {
+ var count = 0
+ var index = 0
+
+ while ((index = body.indexOf('&', index)) !== -1) {
+ count++
+ index++
+
+ if (count === limit) {
+ return undefined
+ }
+ }
+
+ return count
+}
+
+/**
+ * Get parser for module name dynamically.
+ *
+ * @param {string} name
+ * @return {function}
+ * @api private
+ */
+
+function parser (name) {
+ var mod = parsers[name]
+
+ if (mod !== undefined) {
+ return mod.parse
+ }
+
+ // this uses a switch for static require analysis
+ switch (name) {
+ case 'qs':
+ mod = require('qs')
+ break
+ case 'querystring':
+ mod = require('querystring')
+ break
+ }
+
+ // store to prevent invoking require()
+ parsers[name] = mod
+
+ return mod.parse
+}
+
+/**
+ * Get the simple query parser.
+ *
+ * @param {object} options
+ */
+
+function simpleparser (options) {
+ var parameterLimit = options.parameterLimit !== undefined
+ ? options.parameterLimit
+ : 1000
+ var parse = parser('querystring')
+
+ if (isNaN(parameterLimit) || parameterLimit < 1) {
+ throw new TypeError('option parameterLimit must be a positive number')
+ }
+
+ if (isFinite(parameterLimit)) {
+ parameterLimit = parameterLimit | 0
+ }
+
+ return function queryparse (body) {
+ var paramCount = parameterCount(body, parameterLimit)
+
+ if (paramCount === undefined) {
+ debug('too many parameters')
+ throw createError(413, 'too many parameters')
+ }
+
+ debug('parse urlencoding')
+ return parse(body, undefined, undefined, {maxKeys: parameterLimit})
+ }
+}
+
+/**
+ * Get the simple type checker.
+ *
+ * @param {string} type
+ * @return {function}
+ */
+
+function typeChecker (type) {
+ return function checkType (req) {
+ return Boolean(typeis(req, type))
+ }
+}
diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json
new file mode 100644
index 0000000..725ddaf
--- /dev/null
+++ b/node_modules/body-parser/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "body-parser",
+ "description": "Node.js body parsing middleware",
+ "version": "1.15.2",
+ "contributors": [
+ "Douglas Christopher Wilson ",
+ "Jonathan Ong (http://jongleberry.com)"
+ ],
+ "license": "MIT",
+ "repository": "expressjs/body-parser",
+ "dependencies": {
+ "bytes": "2.4.0",
+ "content-type": "~1.0.2",
+ "debug": "~2.2.0",
+ "depd": "~1.1.0",
+ "http-errors": "~1.5.0",
+ "iconv-lite": "0.4.13",
+ "on-finished": "~2.3.0",
+ "qs": "6.2.0",
+ "raw-body": "~2.1.7",
+ "type-is": "~1.6.13"
+ },
+ "devDependencies": {
+ "eslint": "2.13.0",
+ "eslint-config-standard": "5.3.1",
+ "eslint-plugin-promise": "1.3.2",
+ "eslint-plugin-standard": "1.3.2",
+ "istanbul": "0.4.3",
+ "methods": "1.1.2",
+ "mocha": "2.5.3",
+ "supertest": "1.1.0"
+ },
+ "files": [
+ "lib/",
+ "LICENSE",
+ "HISTORY.md",
+ "index.js"
+ ],
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "scripts": {
+ "lint": "eslint **/*.js",
+ "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/",
+ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/",
+ "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/"
+ }
+}
diff --git a/node_modules/boom/.npmignore b/node_modules/boom/.npmignore
new file mode 100644
index 0000000..77ba16c
--- /dev/null
+++ b/node_modules/boom/.npmignore
@@ -0,0 +1,18 @@
+.idea
+*.iml
+npm-debug.log
+dump.rdb
+node_modules
+results.tap
+results.xml
+npm-shrinkwrap.json
+config.json
+.DS_Store
+*/.DS_Store
+*/*/.DS_Store
+._*
+*/._*
+*/*/._*
+coverage.*
+lib-cov
+
diff --git a/node_modules/boom/.travis.yml b/node_modules/boom/.travis.yml
new file mode 100755
index 0000000..dd1b24f
--- /dev/null
+++ b/node_modules/boom/.travis.yml
@@ -0,0 +1,8 @@
+language: node_js
+
+node_js:
+ - 0.10
+ - 4.0
+
+sudo: false
+
diff --git a/node_modules/boom/CONTRIBUTING.md b/node_modules/boom/CONTRIBUTING.md
new file mode 100644
index 0000000..8928361
--- /dev/null
+++ b/node_modules/boom/CONTRIBUTING.md
@@ -0,0 +1 @@
+Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md).
diff --git a/node_modules/boom/LICENSE b/node_modules/boom/LICENSE
new file mode 100755
index 0000000..3946889
--- /dev/null
+++ b/node_modules/boom/LICENSE
@@ -0,0 +1,28 @@
+Copyright (c) 2012-2014, Walmart and other contributors.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hapijs/boom/graphs/contributors
\ No newline at end of file
diff --git a/node_modules/boom/README.md b/node_modules/boom/README.md
new file mode 100755
index 0000000..cbd91c9
--- /dev/null
+++ b/node_modules/boom/README.md
@@ -0,0 +1,652 @@
+![boom Logo](https://raw.github.com/hapijs/boom/master/images/boom.png)
+
+HTTP-friendly error objects
+
+[![Build Status](https://secure.travis-ci.org/hapijs/boom.png)](http://travis-ci.org/hapijs/boom)
+[![Current Version](https://img.shields.io/npm/v/boom.svg)](https://www.npmjs.com/package/boom)
+
+Lead Maintainer: [Adam Bretz](https://github.com/arb)
+
+**boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response
+object (instance of `Error`) which includes the following properties:
+- `isBoom` - if `true`, indicates this is a `Boom` object instance.
+- `isServer` - convenience bool indicating status code >= 500.
+- `message` - the error message.
+- `output` - the formatted response. Can be directly manipulated after object construction to return a custom
+ error response. Allowed root keys:
+ - `statusCode` - the HTTP status code (typically 4xx or 5xx).
+ - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content.
+ - `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any
+ changes will be lost
+ if `reformat()` is called. Any content allowed and by default includes the following content:
+ - `statusCode` - the HTTP status code, derived from `error.output.statusCode`.
+ - `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`.
+ - `message` - the error message derived from `error.message`.
+- inherited `Error` properties.
+
+The `Boom` object also supports the following method:
+- `reformat()` - rebuilds `error.output` using the other object properties.
+
+## Overview
+
+- Helper methods
+ - [`wrap(error, [statusCode], [message])`](#wraperror-statuscode-message)
+ - [`create(statusCode, [message], [data])`](#createstatuscode-message-data)
+- HTTP 4xx Errors
+ - 400: [`Boom.badRequest([message], [data])`](#boombadrequestmessage-data)
+ - 401: [`Boom.unauthorized([message], [scheme], [attributes])`](#boomunauthorizedmessage-scheme-attributes)
+ - 403: [`Boom.forbidden([message], [data])`](#boomforbiddenmessage-data)
+ - 404: [`Boom.notFound([message], [data])`](#boomnotfoundmessage-data)
+ - 405: [`Boom.methodNotAllowed([message], [data])`](#boommethodnotallowedmessage-data)
+ - 406: [`Boom.notAcceptable([message], [data])`](#boomnotacceptablemessage-data)
+ - 407: [`Boom.proxyAuthRequired([message], [data])`](#boomproxyauthrequiredmessage-data)
+ - 408: [`Boom.clientTimeout([message], [data])`](#boomclienttimeoutmessage-data)
+ - 409: [`Boom.conflict([message], [data])`](#boomconflictmessage-data)
+ - 410: [`Boom.resourceGone([message], [data])`](#boomresourcegonemessage-data)
+ - 411: [`Boom.lengthRequired([message], [data])`](#boomlengthrequiredmessage-data)
+ - 412: [`Boom.preconditionFailed([message], [data])`](#boompreconditionfailedmessage-data)
+ - 413: [`Boom.entityTooLarge([message], [data])`](#boomentitytoolargemessage-data)
+ - 414: [`Boom.uriTooLong([message], [data])`](#boomuritoolongmessage-data)
+ - 415: [`Boom.unsupportedMediaType([message], [data])`](#boomunsupportedmediatypemessage-data)
+ - 416: [`Boom.rangeNotSatisfiable([message], [data])`](#boomrangenotsatisfiablemessage-data)
+ - 417: [`Boom.expectationFailed([message], [data])`](#boomexpectationfailedmessage-data)
+ - 422: [`Boom.badData([message], [data])`](#boombaddatamessage-data)
+ - 428: [`Boom.preconditionRequired([message], [data])`](#boompreconditionrequiredmessage-data)
+ - 429: [`Boom.tooManyRequests([message], [data])`](#boomtoomanyrequestsmessage-data)
+- HTTP 5xx Errors
+ - 500: [`Boom.badImplementation([message], [data])`](#boombadimplementationmessage-data)
+ - 501: [`Boom.notImplemented([message], [data])`](#boomnotimplementedmessage-data)
+ - 502: [`Boom.badGateway([message], [data])`](#boombadgatewaymessage-data)
+ - 503: [`Boom.serverTimeout([message], [data])`](#boomservertimeoutmessage-data)
+ - 504: [`Boom.gatewayTimeout([message], [data])`](#boomgatewaytimeoutmessage-data)
+- [FAQ](#faq)
+
+
+## Helper Methods
+
+### `wrap(error, [statusCode], [message])`
+
+Decorates an error with the **boom** properties where:
+- `error` - the error object to wrap. If `error` is already a **boom** object, returns back the same object.
+- `statusCode` - optional HTTP status code. Defaults to `500`.
+- `message` - optional message string. If the error already has a message, it adds the message as a prefix.
+ Defaults to no message.
+
+```js
+var error = new Error('Unexpected input');
+Boom.wrap(error, 400);
+```
+
+### `create(statusCode, [message], [data])`
+
+Generates an `Error` object with the **boom** decorations where:
+- `statusCode` - an HTTP error code number. Must be greater or equal 400.
+- `message` - optional message string.
+- `data` - additional error data set to `error.data` property.
+
+```js
+var error = Boom.create(400, 'Bad request', { timestamp: Date.now() });
+```
+
+## HTTP 4xx Errors
+
+### `Boom.badRequest([message], [data])`
+
+Returns a 400 Bad Request error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badRequest('invalid query');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 400,
+ "error": "Bad Request",
+ "message": "invalid query"
+}
+```
+
+### `Boom.unauthorized([message], [scheme], [attributes])`
+
+Returns a 401 Unauthorized error where:
+- `message` - optional message.
+- `scheme` can be one of the following:
+ - an authentication scheme name
+ - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
+- `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used
+ when `schema` is a string, otherwise it is ignored. Every key/value pair will be included in the
+ 'WWW-Authenticate' in the format of 'key="value"' as well as in the response payload under the `attributes` key.
+ `null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as
+ the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header
+ will not be present and `isMissing` will be true on the error object.
+
+If either `scheme` or `attributes` are set, the resultant `Boom` object will have the 'WWW-Authenticate' header set for the response.
+
+```js
+Boom.unauthorized('invalid password');
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password"
+},
+"headers" {}
+```
+
+```js
+Boom.unauthorized('invalid password', 'sample');
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password",
+ "attributes": {
+ "error": "invalid password"
+ }
+},
+"headers" {
+ "WWW-Authenticate": "sample error=\"invalid password\""
+}
+```
+
+```js
+Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' });
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password",
+ "attributes": {
+ "error": "invalid password",
+ "ttl": 0,
+ "cache": "",
+ "foo": "bar"
+ }
+},
+"headers" {
+ "WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\""
+}
+```
+
+### `Boom.forbidden([message], [data])`
+
+Returns a 403 Forbidden error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.forbidden('try again some time');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 403,
+ "error": "Forbidden",
+ "message": "try again some time"
+}
+```
+
+### `Boom.notFound([message], [data])`
+
+Returns a 404 Not Found error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notFound('missing');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 404,
+ "error": "Not Found",
+ "message": "missing"
+}
+```
+
+### `Boom.methodNotAllowed([message], [data])`
+
+Returns a 405 Method Not Allowed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.methodNotAllowed('that method is not allowed');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 405,
+ "error": "Method Not Allowed",
+ "message": "that method is not allowed"
+}
+```
+
+### `Boom.notAcceptable([message], [data])`
+
+Returns a 406 Not Acceptable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notAcceptable('unacceptable');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 406,
+ "error": "Not Acceptable",
+ "message": "unacceptable"
+}
+```
+
+### `Boom.proxyAuthRequired([message], [data])`
+
+Returns a 407 Proxy Authentication Required error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.proxyAuthRequired('auth missing');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 407,
+ "error": "Proxy Authentication Required",
+ "message": "auth missing"
+}
+```
+
+### `Boom.clientTimeout([message], [data])`
+
+Returns a 408 Request Time-out error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.clientTimeout('timed out');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 408,
+ "error": "Request Time-out",
+ "message": "timed out"
+}
+```
+
+### `Boom.conflict([message], [data])`
+
+Returns a 409 Conflict error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.conflict('there was a conflict');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 409,
+ "error": "Conflict",
+ "message": "there was a conflict"
+}
+```
+
+### `Boom.resourceGone([message], [data])`
+
+Returns a 410 Gone error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.resourceGone('it is gone');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 410,
+ "error": "Gone",
+ "message": "it is gone"
+}
+```
+
+### `Boom.lengthRequired([message], [data])`
+
+Returns a 411 Length Required error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.lengthRequired('length needed');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 411,
+ "error": "Length Required",
+ "message": "length needed"
+}
+```
+
+### `Boom.preconditionFailed([message], [data])`
+
+Returns a 412 Precondition Failed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.preconditionFailed();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 412,
+ "error": "Precondition Failed"
+}
+```
+
+### `Boom.entityTooLarge([message], [data])`
+
+Returns a 413 Request Entity Too Large error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.entityTooLarge('too big');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 413,
+ "error": "Request Entity Too Large",
+ "message": "too big"
+}
+```
+
+### `Boom.uriTooLong([message], [data])`
+
+Returns a 414 Request-URI Too Large error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.uriTooLong('uri is too long');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 414,
+ "error": "Request-URI Too Large",
+ "message": "uri is too long"
+}
+```
+
+### `Boom.unsupportedMediaType([message], [data])`
+
+Returns a 415 Unsupported Media Type error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.unsupportedMediaType('that media is not supported');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 415,
+ "error": "Unsupported Media Type",
+ "message": "that media is not supported"
+}
+```
+
+### `Boom.rangeNotSatisfiable([message], [data])`
+
+Returns a 416 Requested Range Not Satisfiable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.rangeNotSatisfiable();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 416,
+ "error": "Requested Range Not Satisfiable"
+}
+```
+
+### `Boom.expectationFailed([message], [data])`
+
+Returns a 417 Expectation Failed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.expectationFailed('expected this to work');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 417,
+ "error": "Expectation Failed",
+ "message": "expected this to work"
+}
+```
+
+### `Boom.badData([message], [data])`
+
+Returns a 422 Unprocessable Entity error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badData('your data is bad and you should feel bad');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 422,
+ "error": "Unprocessable Entity",
+ "message": "your data is bad and you should feel bad"
+}
+```
+
+### `Boom.preconditionRequired([message], [data])`
+
+Returns a 428 Precondition Required error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.preconditionRequired('you must supply an If-Match header');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 428,
+ "error": "Precondition Required",
+ "message": "you must supply an If-Match header"
+}
+```
+
+### `Boom.tooManyRequests([message], [data])`
+
+Returns a 429 Too Many Requests error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.tooManyRequests('you have exceeded your request limit');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 429,
+ "error": "Too Many Requests",
+ "message": "you have exceeded your request limit"
+}
+```
+
+## HTTP 5xx Errors
+
+All 500 errors hide your message from the end user. Your message is recorded in the server log.
+
+### `Boom.badImplementation([message], [data])`
+
+Returns a 500 Internal Server Error error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badImplementation('terrible implementation');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 500,
+ "error": "Internal Server Error",
+ "message": "An internal server error occurred"
+}
+```
+
+### `Boom.notImplemented([message], [data])`
+
+Returns a 501 Not Implemented error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notImplemented('method not implemented');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 501,
+ "error": "Not Implemented",
+ "message": "method not implemented"
+}
+```
+
+### `Boom.badGateway([message], [data])`
+
+Returns a 502 Bad Gateway error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badGateway('that is a bad gateway');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 502,
+ "error": "Bad Gateway",
+ "message": "that is a bad gateway"
+}
+```
+
+### `Boom.serverTimeout([message], [data])`
+
+Returns a 503 Service Unavailable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.serverTimeout('unavailable');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 503,
+ "error": "Service Unavailable",
+ "message": "unavailable"
+}
+```
+
+### `Boom.gatewayTimeout([message], [data])`
+
+Returns a 504 Gateway Time-out error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.gatewayTimeout();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 504,
+ "error": "Gateway Time-out"
+}
+```
+
+## F.A.Q.
+
+###### How do I include extra information in my responses? `output.payload` is missing `data`, what gives?
+
+There is a reason the values passed back in the response payloads are pretty locked down. It's mostly for security and to not leak any important information back to the client. This means you will need to put in a little more effort to include extra information about your custom error. Check out the ["Error transformation"](https://github.com/hapijs/hapi/blob/master/API.md#error-transformation) section in the hapi documentation.
diff --git a/node_modules/boom/images/boom.png b/node_modules/boom/images/boom.png
new file mode 100755
index 0000000..373bc13
Binary files /dev/null and b/node_modules/boom/images/boom.png differ
diff --git a/node_modules/boom/lib/index.js b/node_modules/boom/lib/index.js
new file mode 100755
index 0000000..6bdea69
--- /dev/null
+++ b/node_modules/boom/lib/index.js
@@ -0,0 +1,318 @@
+// Load modules
+
+var Http = require('http');
+var Hoek = require('hoek');
+
+
+// Declare internals
+
+var internals = {};
+
+exports.wrap = function (error, statusCode, message) {
+
+ Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
+ return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
+};
+
+
+exports.create = function (statusCode, message, data) {
+
+ return internals.create(statusCode, message, data, exports.create);
+};
+
+internals.create = function (statusCode, message, data, ctor) {
+
+ var error = new Error(message ? message : undefined); // Avoids settings null message
+ Error.captureStackTrace(error, ctor); // Filter the stack to our external API
+ error.data = data || null;
+ internals.initialize(error, statusCode);
+ return error;
+};
+
+internals.initialize = function (error, statusCode, message) {
+
+ var numberCode = parseInt(statusCode, 10);
+ Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode);
+
+ error.isBoom = true;
+ error.isServer = numberCode >= 500;
+
+ if (!error.hasOwnProperty('data')) {
+ error.data = null;
+ }
+
+ error.output = {
+ statusCode: numberCode,
+ payload: {},
+ headers: {}
+ };
+
+ error.reformat = internals.reformat;
+ error.reformat();
+
+ if (!message &&
+ !error.message) {
+
+ message = error.output.payload.error;
+ }
+
+ if (message) {
+ error.message = (message + (error.message ? ': ' + error.message : ''));
+ }
+
+ return error;
+};
+
+
+internals.reformat = function () {
+
+ this.output.payload.statusCode = this.output.statusCode;
+ this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown';
+
+ if (this.output.statusCode === 500) {
+ this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user
+ }
+ else if (this.message) {
+ this.output.payload.message = this.message;
+ }
+};
+
+
+// 4xx Client Errors
+
+exports.badRequest = function (message, data) {
+
+ return internals.create(400, message, data, exports.badRequest);
+};
+
+
+exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[])
+
+ var err = internals.create(401, message, undefined, exports.unauthorized);
+
+ if (!scheme) {
+ return err;
+ }
+
+ var wwwAuthenticate = '';
+ var i = 0;
+ var il = 0;
+
+ if (typeof scheme === 'string') {
+
+ // function (message, scheme, attributes)
+
+ wwwAuthenticate = scheme;
+
+ if (attributes || message) {
+ err.output.payload.attributes = {};
+ }
+
+ if (attributes) {
+ var names = Object.keys(attributes);
+ for (i = 0, il = names.length; i < il; ++i) {
+ var name = names[i];
+ if (i) {
+ wwwAuthenticate += ',';
+ }
+
+ var value = attributes[name];
+ if (value === null ||
+ value === undefined) { // Value can be zero
+
+ value = '';
+ }
+ wwwAuthenticate += ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"';
+ err.output.payload.attributes[name] = value;
+ }
+ }
+
+ if (message) {
+ if (attributes) {
+ wwwAuthenticate += ',';
+ }
+ wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"';
+ err.output.payload.attributes.error = message;
+ }
+ else {
+ err.isMissing = true;
+ }
+ }
+ else {
+
+ // function (message, wwwAuthenticate[])
+
+ var wwwArray = scheme;
+ for (i = 0, il = wwwArray.length; i < il; ++i) {
+ if (i) {
+ wwwAuthenticate += ', ';
+ }
+
+ wwwAuthenticate += wwwArray[i];
+ }
+ }
+
+ err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
+
+ return err;
+};
+
+
+exports.forbidden = function (message, data) {
+
+ return internals.create(403, message, data, exports.forbidden);
+};
+
+
+exports.notFound = function (message, data) {
+
+ return internals.create(404, message, data, exports.notFound);
+};
+
+
+exports.methodNotAllowed = function (message, data) {
+
+ return internals.create(405, message, data, exports.methodNotAllowed);
+};
+
+
+exports.notAcceptable = function (message, data) {
+
+ return internals.create(406, message, data, exports.notAcceptable);
+};
+
+
+exports.proxyAuthRequired = function (message, data) {
+
+ return internals.create(407, message, data, exports.proxyAuthRequired);
+};
+
+
+exports.clientTimeout = function (message, data) {
+
+ return internals.create(408, message, data, exports.clientTimeout);
+};
+
+
+exports.conflict = function (message, data) {
+
+ return internals.create(409, message, data, exports.conflict);
+};
+
+
+exports.resourceGone = function (message, data) {
+
+ return internals.create(410, message, data, exports.resourceGone);
+};
+
+
+exports.lengthRequired = function (message, data) {
+
+ return internals.create(411, message, data, exports.lengthRequired);
+};
+
+
+exports.preconditionFailed = function (message, data) {
+
+ return internals.create(412, message, data, exports.preconditionFailed);
+};
+
+
+exports.entityTooLarge = function (message, data) {
+
+ return internals.create(413, message, data, exports.entityTooLarge);
+};
+
+
+exports.uriTooLong = function (message, data) {
+
+ return internals.create(414, message, data, exports.uriTooLong);
+};
+
+
+exports.unsupportedMediaType = function (message, data) {
+
+ return internals.create(415, message, data, exports.unsupportedMediaType);
+};
+
+
+exports.rangeNotSatisfiable = function (message, data) {
+
+ return internals.create(416, message, data, exports.rangeNotSatisfiable);
+};
+
+
+exports.expectationFailed = function (message, data) {
+
+ return internals.create(417, message, data, exports.expectationFailed);
+};
+
+exports.badData = function (message, data) {
+
+ return internals.create(422, message, data, exports.badData);
+};
+
+
+exports.preconditionRequired = function (message, data) {
+
+ return internals.create(428, message, data, exports.preconditionRequired);
+};
+
+
+exports.tooManyRequests = function (message, data) {
+
+ return internals.create(429, message, data, exports.tooManyRequests);
+};
+
+
+// 5xx Server Errors
+
+exports.internal = function (message, data, statusCode) {
+
+ return internals.serverError(message, data, statusCode, exports.internal);
+};
+
+internals.serverError = function (message, data, statusCode, ctor) {
+
+ var error;
+ if (data instanceof Error) {
+ error = exports.wrap(data, statusCode, message);
+ } else {
+ error = internals.create(statusCode || 500, message, undefined, ctor);
+ error.data = data;
+ }
+
+ return error;
+};
+
+
+exports.notImplemented = function (message, data) {
+
+ return internals.serverError(message, data, 501, exports.notImplemented);
+};
+
+
+exports.badGateway = function (message, data) {
+
+ return internals.serverError(message, data, 502, exports.badGateway);
+};
+
+
+exports.serverTimeout = function (message, data) {
+
+ return internals.serverError(message, data, 503, exports.serverTimeout);
+};
+
+
+exports.gatewayTimeout = function (message, data) {
+
+ return internals.serverError(message, data, 504, exports.gatewayTimeout);
+};
+
+
+exports.badImplementation = function (message, data) {
+
+ var err = internals.serverError(message, data, 500, exports.badImplementation);
+ err.isDeveloperError = true;
+ return err;
+};
diff --git a/node_modules/boom/package.json b/node_modules/boom/package.json
new file mode 100644
index 0000000..f5eea12
--- /dev/null
+++ b/node_modules/boom/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "boom",
+ "description": "HTTP-friendly error objects",
+ "version": "2.10.1",
+ "repository": "git://github.com/hapijs/boom",
+ "main": "lib/index.js",
+ "keywords": [
+ "error",
+ "http"
+ ],
+ "engines": {
+ "node": ">=0.10.40"
+ },
+ "dependencies": {
+ "hoek": "2.x.x"
+ },
+ "devDependencies": {
+ "code": "1.x.x",
+ "lab": "7.x.x"
+ },
+ "scripts": {
+ "test": "lab -a code -t 100 -L",
+ "test-cov-html": "lab -a code -r html -o coverage.html -L"
+ },
+ "license": "BSD-3-Clause"
+}
diff --git a/node_modules/boom/test/index.js b/node_modules/boom/test/index.js
new file mode 100755
index 0000000..79a59e9
--- /dev/null
+++ b/node_modules/boom/test/index.js
@@ -0,0 +1,654 @@
+// Load modules
+
+var Code = require('code');
+var Boom = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.describe;
+var it = lab.it;
+var expect = Code.expect;
+
+
+it('returns the same object when already boom', function (done) {
+
+ var error = Boom.badRequest();
+ var wrapped = Boom.wrap(error);
+ expect(error).to.equal(wrapped);
+ done();
+});
+
+it('returns an error with info when constructed using another error', function (done) {
+
+ var error = new Error('ka-boom');
+ error.xyz = 123;
+ var err = Boom.wrap(error);
+ expect(err.xyz).to.equal(123);
+ expect(err.message).to.equal('ka-boom');
+ expect(err.output).to.deep.equal({
+ statusCode: 500,
+ payload: {
+ statusCode: 500,
+ error: 'Internal Server Error',
+ message: 'An internal server error occurred'
+ },
+ headers: {}
+ });
+ expect(err.data).to.equal(null);
+ done();
+});
+
+it('does not override data when constructed using another error', function (done) {
+
+ var error = new Error('ka-boom');
+ error.data = { useful: 'data' };
+ var err = Boom.wrap(error);
+ expect(err.data).to.equal(error.data);
+ done();
+});
+
+it('sets new message when none exists', function (done) {
+
+ var error = new Error();
+ var wrapped = Boom.wrap(error, 400, 'something bad');
+ expect(wrapped.message).to.equal('something bad');
+ done();
+});
+
+it('throws when statusCode is not a number', function (done) {
+
+ expect(function () {
+
+ Boom.create('x');
+ }).to.throw('First argument must be a number (400+): x');
+ done();
+});
+
+it('will cast a number-string to an integer', function (done) {
+
+ var codes = [
+ { input: '404', result: 404 },
+ { input: '404.1', result: 404 },
+ { input: 400, result: 400 },
+ { input: 400.123, result: 400 }];
+ for (var i = 0, il = codes.length; i < il; ++i) {
+ var code = codes[i];
+ var err = Boom.create(code.input);
+ expect(err.output.statusCode).to.equal(code.result);
+ }
+
+ done();
+});
+
+it('throws when statusCode is not finite', function (done) {
+
+ expect(function () {
+
+ Boom.create(1 / 0);
+ }).to.throw('First argument must be a number (400+): null');
+ done();
+});
+
+it('sets error code to unknown', function (done) {
+
+ var err = Boom.create(999);
+ expect(err.output.payload.error).to.equal('Unknown');
+ done();
+});
+
+describe('create()', function () {
+
+ it('does not sets null message', function (done) {
+
+ var error = Boom.unauthorized(null);
+ expect(error.output.payload.message).to.not.exist();
+ expect(error.isServer).to.be.false();
+ done();
+ });
+
+ it('sets message and data', function (done) {
+
+ var error = Boom.badRequest('Missing data', { type: 'user' });
+ expect(error.data.type).to.equal('user');
+ expect(error.output.payload.message).to.equal('Missing data');
+ done();
+ });
+});
+
+describe('isBoom()', function () {
+
+ it('returns true for Boom object', function (done) {
+
+ expect(Boom.badRequest().isBoom).to.equal(true);
+ done();
+ });
+
+ it('returns false for Error object', function (done) {
+
+ expect((new Error()).isBoom).to.not.exist();
+ done();
+ });
+});
+
+describe('badRequest()', function () {
+
+ it('returns a 400 error statusCode', function (done) {
+
+ var error = Boom.badRequest();
+
+ expect(error.output.statusCode).to.equal(400);
+ expect(error.isServer).to.be.false();
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.badRequest('my message').message).to.equal('my message');
+ done();
+ });
+
+ it('sets the message to HTTP status if none provided', function (done) {
+
+ expect(Boom.badRequest().message).to.equal('Bad Request');
+ done();
+ });
+});
+
+describe('unauthorized()', function () {
+
+ it('returns a 401 error statusCode', function (done) {
+
+ var err = Boom.unauthorized();
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers).to.deep.equal({});
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.unauthorized('my message').message).to.equal('my message');
+ done();
+ });
+
+ it('returns a WWW-Authenticate header when passed a scheme', function (done) {
+
+ var err = Boom.unauthorized('boom', 'Test');
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"');
+ done();
+ });
+
+ it('returns a WWW-Authenticate header set to the schema array value', function (done) {
+
+ var err = Boom.unauthorized(null, ['Test','one','two']);
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test, one, two');
+ done();
+ });
+
+ it('returns a WWW-Authenticate header when passed a scheme and attributes', function (done) {
+
+ var err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 });
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"');
+ expect(err.output.payload.attributes).to.deep.equal({ a: 1, b: 'something', c: '', d: 0, error: 'boom' });
+ done();
+ });
+
+ it('returns a WWW-Authenticate header when passed attributes, missing error', function (done) {
+
+ var err = Boom.unauthorized(null, 'Test', { a: 1, b: 'something', c: null, d: 0 });
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0"');
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
+
+ it('sets the isMissing flag when error message is empty', function (done) {
+
+ var err = Boom.unauthorized('', 'Basic');
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
+
+ it('does not set the isMissing flag when error message is not empty', function (done) {
+
+ var err = Boom.unauthorized('message', 'Basic');
+ expect(err.isMissing).to.equal(undefined);
+ done();
+ });
+
+ it('sets a WWW-Authenticate when passed as an array', function (done) {
+
+ var err = Boom.unauthorized('message', ['Basic', 'Example e="1"', 'Another x="3", y="4"']);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Basic, Example e="1", Another x="3", y="4"');
+ done();
+ });
+});
+
+
+describe('methodNotAllowed()', function () {
+
+ it('returns a 405 error statusCode', function (done) {
+
+ expect(Boom.methodNotAllowed().output.statusCode).to.equal(405);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.methodNotAllowed('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('notAcceptable()', function () {
+
+ it('returns a 406 error statusCode', function (done) {
+
+ expect(Boom.notAcceptable().output.statusCode).to.equal(406);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.notAcceptable('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('proxyAuthRequired()', function () {
+
+ it('returns a 407 error statusCode', function (done) {
+
+ expect(Boom.proxyAuthRequired().output.statusCode).to.equal(407);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.proxyAuthRequired('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('clientTimeout()', function () {
+
+ it('returns a 408 error statusCode', function (done) {
+
+ expect(Boom.clientTimeout().output.statusCode).to.equal(408);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.clientTimeout('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('conflict()', function () {
+
+ it('returns a 409 error statusCode', function (done) {
+
+ expect(Boom.conflict().output.statusCode).to.equal(409);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.conflict('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('resourceGone()', function () {
+
+ it('returns a 410 error statusCode', function (done) {
+
+ expect(Boom.resourceGone().output.statusCode).to.equal(410);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.resourceGone('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('lengthRequired()', function () {
+
+ it('returns a 411 error statusCode', function (done) {
+
+ expect(Boom.lengthRequired().output.statusCode).to.equal(411);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.lengthRequired('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('preconditionFailed()', function () {
+
+ it('returns a 412 error statusCode', function (done) {
+
+ expect(Boom.preconditionFailed().output.statusCode).to.equal(412);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.preconditionFailed('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('entityTooLarge()', function () {
+
+ it('returns a 413 error statusCode', function (done) {
+
+ expect(Boom.entityTooLarge().output.statusCode).to.equal(413);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.entityTooLarge('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('uriTooLong()', function () {
+
+ it('returns a 414 error statusCode', function (done) {
+
+ expect(Boom.uriTooLong().output.statusCode).to.equal(414);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.uriTooLong('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('unsupportedMediaType()', function () {
+
+ it('returns a 415 error statusCode', function (done) {
+
+ expect(Boom.unsupportedMediaType().output.statusCode).to.equal(415);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.unsupportedMediaType('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('rangeNotSatisfiable()', function () {
+
+ it('returns a 416 error statusCode', function (done) {
+
+ expect(Boom.rangeNotSatisfiable().output.statusCode).to.equal(416);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.rangeNotSatisfiable('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('expectationFailed()', function () {
+
+ it('returns a 417 error statusCode', function (done) {
+
+ expect(Boom.expectationFailed().output.statusCode).to.equal(417);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.expectationFailed('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('badData()', function () {
+
+ it('returns a 422 error statusCode', function (done) {
+
+ expect(Boom.badData().output.statusCode).to.equal(422);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.badData('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('preconditionRequired()', function () {
+
+ it('returns a 428 error statusCode', function (done) {
+
+ expect(Boom.preconditionRequired().output.statusCode).to.equal(428);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.preconditionRequired('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('tooManyRequests()', function () {
+
+ it('returns a 429 error statusCode', function (done) {
+
+ expect(Boom.tooManyRequests().output.statusCode).to.equal(429);
+ done();
+ });
+
+ it('sets the message with the passed-in message', function (done) {
+
+ expect(Boom.tooManyRequests('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('serverTimeout()', function () {
+
+ it('returns a 503 error statusCode', function (done) {
+
+ expect(Boom.serverTimeout().output.statusCode).to.equal(503);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.serverTimeout('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('forbidden()', function () {
+
+ it('returns a 403 error statusCode', function (done) {
+
+ expect(Boom.forbidden().output.statusCode).to.equal(403);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.forbidden('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('notFound()', function () {
+
+ it('returns a 404 error statusCode', function (done) {
+
+ expect(Boom.notFound().output.statusCode).to.equal(404);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.notFound('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('internal()', function () {
+
+ it('returns a 500 error statusCode', function (done) {
+
+ expect(Boom.internal().output.statusCode).to.equal(500);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ var err = Boom.internal('my message');
+ expect(err.message).to.equal('my message');
+ expect(err.isServer).to.true();
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+
+ it('passes data on the callback if its passed in', function (done) {
+
+ expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data');
+ done();
+ });
+
+ it('returns an error with composite message', function (done) {
+
+ try {
+ JSON.parse('{');
+ }
+ catch (err) {
+ var boom = Boom.internal('Someting bad', err);
+ expect(boom.message).to.equal('Someting bad: Unexpected end of input');
+ expect(boom.isServer).to.be.true();
+ done();
+ }
+ });
+});
+
+describe('notImplemented()', function () {
+
+ it('returns a 501 error statusCode', function (done) {
+
+ expect(Boom.notImplemented().output.statusCode).to.equal(501);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.notImplemented('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('badGateway()', function () {
+
+ it('returns a 502 error statusCode', function (done) {
+
+ expect(Boom.badGateway().output.statusCode).to.equal(502);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.badGateway('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('gatewayTimeout()', function () {
+
+ it('returns a 504 error statusCode', function (done) {
+
+ expect(Boom.gatewayTimeout().output.statusCode).to.equal(504);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.gatewayTimeout('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('badImplementation()', function () {
+
+ it('returns a 500 error statusCode', function (done) {
+
+ var err = Boom.badImplementation();
+ expect(err.output.statusCode).to.equal(500);
+ expect(err.isDeveloperError).to.equal(true);
+ expect(err.isServer).to.be.true();
+ done();
+ });
+});
+
+describe('stack trace', function () {
+
+ it('should omit lib', function (done) {
+
+ ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed',
+ 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict',
+ 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge',
+ 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed',
+ 'badData', 'preconditionRequired', 'tooManyRequests',
+
+ // 500s
+ 'internal', 'notImplemented', 'badGateway', 'serverTimeout', 'gatewayTimeout',
+ 'badImplementation'
+ ].forEach(function (name) {
+
+ var err = Boom[name]();
+ expect(err.stack).to.not.match(/\/lib\/index\.js/);
+ });
+
+ done();
+ });
+});
diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md
new file mode 100644
index 0000000..1793929
--- /dev/null
+++ b/node_modules/brace-expansion/README.md
@@ -0,0 +1,122 @@
+# brace-expansion
+
+[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
+as known from sh/bash, in JavaScript.
+
+[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
+[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
+
+[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
+
+## Example
+
+```js
+var expand = require('brace-expansion');
+
+expand('file-{a,b,c}.jpg')
+// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
+
+expand('-v{,,}')
+// => ['-v', '-v', '-v']
+
+expand('file{0..2}.jpg')
+// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
+
+expand('file-{a..c}.jpg')
+// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
+
+expand('file{2..0}.jpg')
+// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
+
+expand('file{0..4..2}.jpg')
+// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
+
+expand('file-{a..e..2}.jpg')
+// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
+
+expand('file{00..10..5}.jpg')
+// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
+
+expand('{{A..C},{a..c}}')
+// => ['A', 'B', 'C', 'a', 'b', 'c']
+
+expand('ppp{,config,oe{,conf}}')
+// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
+```
+
+## API
+
+```js
+var expand = require('brace-expansion');
+```
+
+### var expanded = expand(str)
+
+Return an array of all possible and valid expansions of `str`. If none are
+found, `[str]` is returned.
+
+Valid expansions are:
+
+```js
+/^(.*,)+(.+)?$/
+// {a,b,...}
+```
+
+A comma seperated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
+
+```js
+/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
+// {x..y[..incr]}
+```
+
+A numeric sequence from `x` to `y` inclusive, with optional increment.
+If `x` or `y` start with a leading `0`, all the numbers will be padded
+to have equal length. Negative numbers and backwards iteration work too.
+
+```js
+/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
+// {x..y[..incr]}
+```
+
+An alphabetic sequence from `x` to `y` inclusive, with optional increment.
+`x` and `y` must be exactly one character, and if given, `incr` must be a
+number.
+
+For compatibility reasons, the string `${` is not eligible for brace expansion.
+
+## Installation
+
+With [npm](https://npmjs.org) do:
+
+```bash
+npm install brace-expansion
+```
+
+## Contributors
+
+- [Julian Gruber](https://github.com/juliangruber)
+- [Isaac Z. Schlueter](https://github.com/isaacs)
+
+## 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/brace-expansion/index.js b/node_modules/brace-expansion/index.js
new file mode 100644
index 0000000..955f27c
--- /dev/null
+++ b/node_modules/brace-expansion/index.js
@@ -0,0 +1,201 @@
+var concatMap = require('concat-map');
+var balanced = require('balanced-match');
+
+module.exports = expandTop;
+
+var escSlash = '\0SLASH'+Math.random()+'\0';
+var escOpen = '\0OPEN'+Math.random()+'\0';
+var escClose = '\0CLOSE'+Math.random()+'\0';
+var escComma = '\0COMMA'+Math.random()+'\0';
+var escPeriod = '\0PERIOD'+Math.random()+'\0';
+
+function numeric(str) {
+ return parseInt(str, 10) == str
+ ? parseInt(str, 10)
+ : str.charCodeAt(0);
+}
+
+function escapeBraces(str) {
+ return str.split('\\\\').join(escSlash)
+ .split('\\{').join(escOpen)
+ .split('\\}').join(escClose)
+ .split('\\,').join(escComma)
+ .split('\\.').join(escPeriod);
+}
+
+function unescapeBraces(str) {
+ return str.split(escSlash).join('\\')
+ .split(escOpen).join('{')
+ .split(escClose).join('}')
+ .split(escComma).join(',')
+ .split(escPeriod).join('.');
+}
+
+
+// Basically just str.split(","), but handling cases
+// where we have nested braced sections, which should be
+// treated as individual members, like {a,{b,c},d}
+function parseCommaParts(str) {
+ if (!str)
+ return [''];
+
+ var parts = [];
+ var m = balanced('{', '}', str);
+
+ if (!m)
+ return str.split(',');
+
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(',');
+
+ p[p.length-1] += '{' + body + '}';
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length-1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
+
+ parts.push.apply(parts, p);
+
+ return parts;
+}
+
+function expandTop(str) {
+ if (!str)
+ return [];
+
+ // I don't know why Bash 4.3 does this, but it does.
+ // Anything starting with {} will have the first two bytes preserved
+ // but *only* at the top level, so {},a}b will not expand to anything,
+ // but a{},b}c will be expanded to [a}c,abc].
+ // One could argue that this is a bug in Bash, but since the goal of
+ // this module is to match Bash's rules, we escape a leading {}
+ if (str.substr(0, 2) === '{}') {
+ str = '\\{\\}' + str.substr(2);
+ }
+
+ return expand(escapeBraces(str), true).map(unescapeBraces);
+}
+
+function identity(e) {
+ return e;
+}
+
+function embrace(str) {
+ return '{' + str + '}';
+}
+function isPadded(el) {
+ return /^-?0\d/.test(el);
+}
+
+function lte(i, y) {
+ return i <= y;
+}
+function gte(i, y) {
+ return i >= y;
+}
+
+function expand(str, isTop) {
+ var expansions = [];
+
+ var m = balanced('{', '}', str);
+ if (!m || /\$$/.test(m.pre)) return [str];
+
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = /^(.*,)+(.+)?$/.test(m.body);
+ if (!isSequence && !isOptions) {
+ // {a},b}
+ if (m.post.match(/,.*\}/)) {
+ str = m.pre + '{' + m.body + escClose + m.post;
+ return expand(str);
+ }
+ return [str];
+ }
+
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ // x{{a,b}}y ==> x{a}y x{b}y
+ n = expand(n[0], false).map(embrace);
+ if (n.length === 1) {
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
+ }
+ }
+ }
+
+ // at this point, n is the parts, and we know it's not a comma set
+ // with a single entry.
+
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
+ var pre = m.pre;
+ var post = m.post.length
+ ? expand(m.post, false)
+ : [''];
+
+ var N;
+
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length)
+ var incr = n.length == 3
+ ? Math.abs(numeric(n[2]))
+ : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ var pad = n.some(isPadded);
+
+ N = [];
+
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === '\\')
+ c = '';
+ } else {
+ c = String(i);
+ if (pad) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join('0');
+ if (i < 0)
+ c = '-' + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
+ }
+ } else {
+ N = concatMap(n, function(el) { return expand(el, false) });
+ }
+
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
+ }
+
+ return expansions;
+}
+
diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json
new file mode 100644
index 0000000..0ce5829
--- /dev/null
+++ b/node_modules/brace-expansion/package.json
@@ -0,0 +1,45 @@
+{
+ "name": "brace-expansion",
+ "description": "Brace expansion as known from sh/bash",
+ "version": "1.1.6",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/juliangruber/brace-expansion.git"
+ },
+ "homepage": "https://github.com/juliangruber/brace-expansion",
+ "main": "index.js",
+ "scripts": {
+ "test": "tape test/*.js",
+ "gentest": "bash test/generate.sh"
+ },
+ "dependencies": {
+ "balanced-match": "^0.4.1",
+ "concat-map": "0.0.1"
+ },
+ "devDependencies": {
+ "tape": "^4.6.0"
+ },
+ "keywords": [],
+ "author": {
+ "name": "Julian Gruber",
+ "email": "mail@juliangruber.com",
+ "url": "http://juliangruber.com"
+ },
+ "license": "MIT",
+ "testling": {
+ "files": "test/*.js",
+ "browsers": [
+ "ie/8..latest",
+ "firefox/20..latest",
+ "firefox/nightly",
+ "chrome/25..latest",
+ "chrome/canary",
+ "opera/12..latest",
+ "opera/next",
+ "safari/5.1..latest",
+ "ipad/6.0..latest",
+ "iphone/6.0..latest",
+ "android-browser/4.2..latest"
+ ]
+ }
+}
diff --git a/node_modules/braces/LICENSE b/node_modules/braces/LICENSE
new file mode 100644
index 0000000..39245ac
--- /dev/null
+++ b/node_modules/braces/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014-2016, Jon Schlinkert.
+
+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/braces/README.md b/node_modules/braces/README.md
new file mode 100644
index 0000000..52fa756
--- /dev/null
+++ b/node_modules/braces/README.md
@@ -0,0 +1,248 @@
+# braces [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Build Status](https://img.shields.io/travis/jonschlinkert/braces.svg?style=flat)](https://travis-ci.org/jonschlinkert/braces)
+
+Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces specification.
+
+## Install
+
+Install with [npm](https://www.npmjs.com/):
+
+```sh
+$ npm install braces --save
+```
+
+## Features
+
+* Complete support for the braces part of the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/). Braces passes [all of the relevant unit tests](#bash-4-3-support) from the spec.
+* Expands comma-separated values: `a/{b,c}/d` => `['a/b/d', 'a/c/d']`
+* Expands alphabetical or numerical ranges: `{1..3}` => `['1', '2', '3']`
+* [Very fast](#benchmarks)
+* [Special characters](./patterns.md) can be used to generate interesting patterns.
+
+## Example usage
+
+```js
+var braces = require('braces');
+
+braces('a/{x,y}/c{d}e')
+//=> ['a/x/cde', 'a/y/cde']
+
+braces('a/b/c/{x,y}')
+//=> ['a/b/c/x', 'a/b/c/y']
+
+braces('a/{x,{1..5},y}/c{d}e')
+//=> ['a/x/cde', 'a/1/cde', 'a/y/cde', 'a/2/cde', 'a/3/cde', 'a/4/cde', 'a/5/cde']
+```
+
+### Use case: fixtures
+
+> Use braces to generate test fixtures!
+
+**Example**
+
+```js
+var braces = require('./');
+var path = require('path');
+var fs = require('fs');
+
+braces('blah/{a..z}.js').forEach(function(fp) {
+ if (!fs.existsSync(path.dirname(fp))) {
+ fs.mkdirSync(path.dirname(fp));
+ }
+ fs.writeFileSync(fp, '');
+});
+```
+
+See the [tests](./test/test.js) for more examples and use cases (also see the [bash spec tests](./test/bash-mm-adjusted.js));
+
+### Range expansion
+
+Uses [expand-range](https://github.com/jonschlinkert/expand-range) for range expansion.
+
+```js
+braces('a{1..3}b')
+//=> ['a1b', 'a2b', 'a3b']
+
+braces('a{5..8}b')
+//=> ['a5b', 'a6b', 'a7b', 'a8b']
+
+braces('a{00..05}b')
+//=> ['a00b', 'a01b', 'a02b', 'a03b', 'a04b', 'a05b']
+
+braces('a{01..03}b')
+//=> ['a01b', 'a02b', 'a03b']
+
+braces('a{000..005}b')
+//=> ['a000b', 'a001b', 'a002b', 'a003b', 'a004b', 'a005b']
+
+braces('a{a..e}b')
+//=> ['aab', 'abb', 'acb', 'adb', 'aeb']
+
+braces('a{A..E}b')
+//=> ['aAb', 'aBb', 'aCb', 'aDb', 'aEb']
+```
+
+Pass a function as the last argument to customize range expansions:
+
+```js
+var range = braces('x{a..e}y', function (str, i) {
+ return String.fromCharCode(str) + i;
+});
+
+console.log(range);
+//=> ['xa0y', 'xb1y', 'xc2y', 'xd3y', 'xe4y']
+```
+
+See [expand-range](https://github.com/jonschlinkert/expand-range) for benchmarks, tests and the full list of range expansion features.
+
+## Options
+
+### options.makeRe
+
+Type: `Boolean`
+
+Deafault: `false`
+
+Return a regex-optimal string. If you're using braces to generate regex, this will result in dramatically faster performance.
+
+**Examples**
+
+With the default settings (`{makeRe: false}`):
+
+```js
+braces('{1..5}');
+//=> ['1', '2', '3', '4', '5']
+```
+
+With `{makeRe: true}`:
+
+```js
+braces('{1..5}', {makeRe: true});
+//=> ['[1-5]']
+
+braces('{3..9..3}', {makeRe: true});
+//=> ['(3|6|9)']
+```
+
+### options.bash
+
+Type: `Boolean`
+
+Default: `false`
+
+Enables complete support for the Bash specification. The downside is a 20-25% speed decrease.
+
+**Example**
+
+Using the default setting (`{bash: false}`):
+
+```js
+braces('a{b}c');
+//=> ['abc']
+```
+
+In bash (and minimatch), braces with one item are not expanded. To get the same result with braces, set `{bash: true}`:
+
+```js
+braces('a{b}c', {bash: true});
+//=> ['a{b}c']
+```
+
+### options.nodupes
+
+Type: `Boolean`
+
+Deafault: `true`
+
+Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options
+
+## Bash 4.3 Support
+
+> Better support for Bash 4.3 than minimatch
+
+This project has comprehensive unit tests, including tests coverted from [Bash 4.3](www.gnu.org/software/bash/). Currently only 8 of 102 unit tests fail, and
+
+## Run benchmarks
+
+Install dev dependencies:
+
+```bash
+npm i -d && npm benchmark
+```
+
+### Latest results
+
+```bash
+#1: escape.js
+ brace-expansion.js x 114,934 ops/sec ±1.24% (93 runs sampled)
+ braces.js x 342,254 ops/sec ±0.84% (90 runs sampled)
+
+#2: exponent.js
+ brace-expansion.js x 12,359 ops/sec ±0.86% (96 runs sampled)
+ braces.js x 20,389 ops/sec ±0.71% (97 runs sampled)
+
+#3: multiple.js
+ brace-expansion.js x 114,469 ops/sec ±1.44% (94 runs sampled)
+ braces.js x 401,621 ops/sec ±0.87% (91 runs sampled)
+
+#4: nested.js
+ brace-expansion.js x 102,769 ops/sec ±1.55% (92 runs sampled)
+ braces.js x 314,088 ops/sec ±0.71% (98 runs sampled)
+
+#5: normal.js
+ brace-expansion.js x 157,577 ops/sec ±1.65% (91 runs sampled)
+ braces.js x 1,115,950 ops/sec ±0.74% (94 runs sampled)
+
+#6: range.js
+ brace-expansion.js x 138,822 ops/sec ±1.71% (91 runs sampled)
+ braces.js x 1,108,353 ops/sec ±0.85% (94 runs sampled)
+```
+
+## Related projects
+
+You might also be interested in these projects:
+
+* [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://www.npmjs.com/package/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range)
+* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or multiplier to… [more](https://www.npmjs.com/package/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range)
+* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch)
+
+## Contributing
+
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/braces/issues/new).
+
+## Building docs
+
+Generate readme and API documentation with [verb](https://github.com/verbose/verb):
+
+```sh
+$ npm install verb && npm run docs
+```
+
+Or, if [verb](https://github.com/verbose/verb) is installed globally:
+
+```sh
+$ verb
+```
+
+## Running tests
+
+Install dev dependencies:
+
+```sh
+$ npm install -d && npm test
+```
+
+## Author
+
+**Jon Schlinkert**
+
+* [github/jonschlinkert](https://github.com/jonschlinkert)
+* [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+
+Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert).
+Released under the [MIT license](https://github.com/jonschlinkert/braces/blob/master/LICENSE).
+
+***
+
+_This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on May 21, 2016._
\ No newline at end of file
diff --git a/node_modules/braces/index.js b/node_modules/braces/index.js
new file mode 100644
index 0000000..3b4c58d
--- /dev/null
+++ b/node_modules/braces/index.js
@@ -0,0 +1,399 @@
+/*!
+ * braces
+ *
+ * Copyright (c) 2014-2015, Jon Schlinkert.
+ * Licensed under the MIT license.
+ */
+
+'use strict';
+
+/**
+ * Module dependencies
+ */
+
+var expand = require('expand-range');
+var repeat = require('repeat-element');
+var tokens = require('preserve');
+
+/**
+ * Expose `braces`
+ */
+
+module.exports = function(str, options) {
+ if (typeof str !== 'string') {
+ throw new Error('braces expects a string');
+ }
+ return braces(str, options);
+};
+
+/**
+ * Expand `{foo,bar}` or `{1..5}` braces in the
+ * given `string`.
+ *
+ * @param {String} `str`
+ * @param {Array} `arr`
+ * @param {Object} `options`
+ * @return {Array}
+ */
+
+function braces(str, arr, options) {
+ if (str === '') {
+ return [];
+ }
+
+ if (!Array.isArray(arr)) {
+ options = arr;
+ arr = [];
+ }
+
+ var opts = options || {};
+ arr = arr || [];
+
+ if (typeof opts.nodupes === 'undefined') {
+ opts.nodupes = true;
+ }
+
+ var fn = opts.fn;
+ var es6;
+
+ if (typeof opts === 'function') {
+ fn = opts;
+ opts = {};
+ }
+
+ if (!(patternRe instanceof RegExp)) {
+ patternRe = patternRegex();
+ }
+
+ var matches = str.match(patternRe) || [];
+ var m = matches[0];
+
+ switch(m) {
+ case '\\,':
+ return escapeCommas(str, arr, opts);
+ case '\\.':
+ return escapeDots(str, arr, opts);
+ case '\/.':
+ return escapePaths(str, arr, opts);
+ case ' ':
+ return splitWhitespace(str);
+ case '{,}':
+ return exponential(str, opts, braces);
+ case '{}':
+ return emptyBraces(str, arr, opts);
+ case '\\{':
+ case '\\}':
+ return escapeBraces(str, arr, opts);
+ case '${':
+ if (!/\{[^{]+\{/.test(str)) {
+ return arr.concat(str);
+ } else {
+ es6 = true;
+ str = tokens.before(str, es6Regex());
+ }
+ }
+
+ if (!(braceRe instanceof RegExp)) {
+ braceRe = braceRegex();
+ }
+
+ var match = braceRe.exec(str);
+ if (match == null) {
+ return [str];
+ }
+
+ var outter = match[1];
+ var inner = match[2];
+ if (inner === '') { return [str]; }
+
+ var segs, segsLength;
+
+ if (inner.indexOf('..') !== -1) {
+ segs = expand(inner, opts, fn) || inner.split(',');
+ segsLength = segs.length;
+
+ } else if (inner[0] === '"' || inner[0] === '\'') {
+ return arr.concat(str.split(/['"]/).join(''));
+
+ } else {
+ segs = inner.split(',');
+ if (opts.makeRe) {
+ return braces(str.replace(outter, wrap(segs, '|')), opts);
+ }
+
+ segsLength = segs.length;
+ if (segsLength === 1 && opts.bash) {
+ segs[0] = wrap(segs[0], '\\');
+ }
+ }
+
+ var len = segs.length;
+ var i = 0, val;
+
+ while (len--) {
+ var path = segs[i++];
+
+ if (/(\.[^.\/])/.test(path)) {
+ if (segsLength > 1) {
+ return segs;
+ } else {
+ return [str];
+ }
+ }
+
+ val = splice(str, outter, path);
+
+ if (/\{[^{}]+?\}/.test(val)) {
+ arr = braces(val, arr, opts);
+ } else if (val !== '') {
+ if (opts.nodupes && arr.indexOf(val) !== -1) { continue; }
+ arr.push(es6 ? tokens.after(val) : val);
+ }
+ }
+
+ if (opts.strict) { return filter(arr, filterEmpty); }
+ return arr;
+}
+
+/**
+ * Expand exponential ranges
+ *
+ * `a{,}{,}` => ['a', 'a', 'a', 'a']
+ */
+
+function exponential(str, options, fn) {
+ if (typeof options === 'function') {
+ fn = options;
+ options = null;
+ }
+
+ var opts = options || {};
+ var esc = '__ESC_EXP__';
+ var exp = 0;
+ var res;
+
+ var parts = str.split('{,}');
+ if (opts.nodupes) {
+ return fn(parts.join(''), opts);
+ }
+
+ exp = parts.length - 1;
+ res = fn(parts.join(esc), opts);
+ var len = res.length;
+ var arr = [];
+ var i = 0;
+
+ while (len--) {
+ var ele = res[i++];
+ var idx = ele.indexOf(esc);
+
+ if (idx === -1) {
+ arr.push(ele);
+
+ } else {
+ ele = ele.split('__ESC_EXP__').join('');
+ if (!!ele && opts.nodupes !== false) {
+ arr.push(ele);
+
+ } else {
+ var num = Math.pow(2, exp);
+ arr.push.apply(arr, repeat(ele, num));
+ }
+ }
+ }
+ return arr;
+}
+
+/**
+ * Wrap a value with parens, brackets or braces,
+ * based on the given character/separator.
+ *
+ * @param {String|Array} `val`
+ * @param {String} `ch`
+ * @return {String}
+ */
+
+function wrap(val, ch) {
+ if (ch === '|') {
+ return '(' + val.join(ch) + ')';
+ }
+ if (ch === ',') {
+ return '{' + val.join(ch) + '}';
+ }
+ if (ch === '-') {
+ return '[' + val.join(ch) + ']';
+ }
+ if (ch === '\\') {
+ return '\\{' + val + '\\}';
+ }
+}
+
+/**
+ * Handle empty braces: `{}`
+ */
+
+function emptyBraces(str, arr, opts) {
+ return braces(str.split('{}').join('\\{\\}'), arr, opts);
+}
+
+/**
+ * Filter out empty-ish values
+ */
+
+function filterEmpty(ele) {
+ return !!ele && ele !== '\\';
+}
+
+/**
+ * Handle patterns with whitespace
+ */
+
+function splitWhitespace(str) {
+ var segs = str.split(' ');
+ var len = segs.length;
+ var res = [];
+ var i = 0;
+
+ while (len--) {
+ res.push.apply(res, braces(segs[i++]));
+ }
+ return res;
+}
+
+/**
+ * Handle escaped braces: `\\{foo,bar}`
+ */
+
+function escapeBraces(str, arr, opts) {
+ if (!/\{[^{]+\{/.test(str)) {
+ return arr.concat(str.split('\\').join(''));
+ } else {
+ str = str.split('\\{').join('__LT_BRACE__');
+ str = str.split('\\}').join('__RT_BRACE__');
+ return map(braces(str, arr, opts), function(ele) {
+ ele = ele.split('__LT_BRACE__').join('{');
+ return ele.split('__RT_BRACE__').join('}');
+ });
+ }
+}
+
+/**
+ * Handle escaped dots: `{1\\.2}`
+ */
+
+function escapeDots(str, arr, opts) {
+ if (!/[^\\]\..+\\\./.test(str)) {
+ return arr.concat(str.split('\\').join(''));
+ } else {
+ str = str.split('\\.').join('__ESC_DOT__');
+ return map(braces(str, arr, opts), function(ele) {
+ return ele.split('__ESC_DOT__').join('.');
+ });
+ }
+}
+
+/**
+ * Handle escaped dots: `{1\\.2}`
+ */
+
+function escapePaths(str, arr, opts) {
+ str = str.split('\/.').join('__ESC_PATH__');
+ return map(braces(str, arr, opts), function(ele) {
+ return ele.split('__ESC_PATH__').join('\/.');
+ });
+}
+
+/**
+ * Handle escaped commas: `{a\\,b}`
+ */
+
+function escapeCommas(str, arr, opts) {
+ if (!/\w,/.test(str)) {
+ return arr.concat(str.split('\\').join(''));
+ } else {
+ str = str.split('\\,').join('__ESC_COMMA__');
+ return map(braces(str, arr, opts), function(ele) {
+ return ele.split('__ESC_COMMA__').join(',');
+ });
+ }
+}
+
+/**
+ * Regex for common patterns
+ */
+
+function patternRegex() {
+ return /\${|( (?=[{,}])|(?=[{,}]) )|{}|{,}|\\,(?=.*[{}])|\/\.(?=.*[{}])|\\\.(?={)|\\{|\\}/;
+}
+
+/**
+ * Braces regex.
+ */
+
+function braceRegex() {
+ return /.*(\\?\{([^}]+)\})/;
+}
+
+/**
+ * es6 delimiter regex.
+ */
+
+function es6Regex() {
+ return /\$\{([^}]+)\}/;
+}
+
+var braceRe;
+var patternRe;
+
+/**
+ * Faster alternative to `String.replace()` when the
+ * index of the token to be replaces can't be supplied
+ */
+
+function splice(str, token, replacement) {
+ var i = str.indexOf(token);
+ return str.substr(0, i) + replacement
+ + str.substr(i + token.length);
+}
+
+/**
+ * Fast array map
+ */
+
+function map(arr, fn) {
+ if (arr == null) {
+ return [];
+ }
+
+ var len = arr.length;
+ var res = new Array(len);
+ var i = -1;
+
+ while (++i < len) {
+ res[i] = fn(arr[i], i, arr);
+ }
+
+ return res;
+}
+
+/**
+ * Fast array filter
+ */
+
+function filter(arr, cb) {
+ if (arr == null) return [];
+ if (typeof cb !== 'function') {
+ throw new TypeError('braces: filter expects a callback function.');
+ }
+
+ var len = arr.length;
+ var res = arr.slice();
+ var i = 0;
+
+ while (len--) {
+ if (!cb(arr[len], i++)) {
+ res.splice(len, 1);
+ }
+ }
+ return res;
+}
diff --git a/node_modules/braces/package.json b/node_modules/braces/package.json
new file mode 100644
index 0000000..ab6bcdc
--- /dev/null
+++ b/node_modules/braces/package.json
@@ -0,0 +1,83 @@
+{
+ "name": "braces",
+ "description": "Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces specification.",
+ "version": "1.8.5",
+ "homepage": "https://github.com/jonschlinkert/braces",
+ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
+ "repository": "jonschlinkert/braces",
+ "bugs": {
+ "url": "https://github.com/jonschlinkert/braces/issues"
+ },
+ "license": "MIT",
+ "files": [
+ "index.js"
+ ],
+ "main": "index.js",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "mocha"
+ },
+ "dependencies": {
+ "expand-range": "^1.8.1",
+ "preserve": "^0.2.0",
+ "repeat-element": "^1.1.2"
+ },
+ "devDependencies": {
+ "benchmarked": "^0.1.5",
+ "brace-expansion": "^1.1.3",
+ "chalk": "^1.1.3",
+ "gulp-format-md": "^0.1.8",
+ "minimatch": "^3.0.0",
+ "minimist": "^1.2.0",
+ "mocha": "^2.4.5",
+ "should": "^8.3.1"
+ },
+ "keywords": [
+ "alpha",
+ "alphabetical",
+ "bash",
+ "brace",
+ "expand",
+ "expansion",
+ "filepath",
+ "fill",
+ "fs",
+ "glob",
+ "globbing",
+ "letter",
+ "match",
+ "matches",
+ "matching",
+ "number",
+ "numerical",
+ "path",
+ "range",
+ "ranges",
+ "sh"
+ ],
+ "verb": {
+ "plugins": [
+ "gulp-format-md"
+ ],
+ "reflinks": [
+ "verb"
+ ],
+ "toc": false,
+ "layout": "default",
+ "lint": {
+ "reflinks": true
+ },
+ "tasks": [
+ "readme"
+ ],
+ "related": {
+ "list": [
+ "micromatch",
+ "expand-range",
+ "fill-range"
+ ]
+ }
+ }
+}
diff --git a/node_modules/browserify-zlib/.npmignore b/node_modules/browserify-zlib/.npmignore
new file mode 100644
index 0000000..2752eb9
--- /dev/null
+++ b/node_modules/browserify-zlib/.npmignore
@@ -0,0 +1,2 @@
+node_modules/
+.DS_Store
diff --git a/node_modules/browserify-zlib/.travis.yml b/node_modules/browserify-zlib/.travis.yml
new file mode 100644
index 0000000..87f8cd9
--- /dev/null
+++ b/node_modules/browserify-zlib/.travis.yml
@@ -0,0 +1,3 @@
+language: node_js
+node_js:
+ - "0.10"
\ No newline at end of file
diff --git a/node_modules/browserify-zlib/README.md b/node_modules/browserify-zlib/README.md
new file mode 100644
index 0000000..61f323a
--- /dev/null
+++ b/node_modules/browserify-zlib/README.md
@@ -0,0 +1,22 @@
+# browserify-zlib
+
+Emulates Node's [zlib](http://nodejs.org/api/zlib.html) module for [Browserify](http://browserify.org)
+using [pako](https://github.com/nodeca/pako). It uses the actual Node source code and passes the Node zlib tests
+by emulating the C++ binding that actually calls zlib.
+
+[![browser support](https://ci.testling.com/devongovett/browserify-zlib.png)
+](https://ci.testling.com/devongovett/browserify-zlib)
+
+[![node tests](https://travis-ci.org/devongovett/browserify-zlib.svg)
+](https://travis-ci.org/devongovett/browserify-zlib)
+
+## Not implemented
+
+The following options/methods are not supported because pako does not support them yet.
+
+* The `params` method
+* The `dictionary` option
+
+## License
+
+MIT
diff --git a/node_modules/browserify-zlib/package.json b/node_modules/browserify-zlib/package.json
new file mode 100644
index 0000000..dfa960d
--- /dev/null
+++ b/node_modules/browserify-zlib/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "browserify-zlib",
+ "version": "0.1.4",
+ "description": "Full zlib module for browserify",
+ "keywords": ["zlib", "browserify"],
+ "main": "index.js",
+ "directories": {
+ "test": "test"
+ },
+ "dependencies": {
+ "pako": "~0.2.0"
+ },
+ "devDependencies": {
+ "tape": "^2.12.3",
+ "brfs": "^1.0.1"
+ },
+ "testling": {
+ "files": "test/*.js",
+ "browsers": [
+ "ie/6..latest",
+ "chrome/22..latest",
+ "firefox/16..latest",
+ "safari/latest",
+ "opera/11.0..latest",
+ "iphone/6",
+ "ipad/6",
+ "android-browser/latest"
+ ]
+ },
+ "scripts": {
+ "test": "node_modules/tape/bin/tape test/*.js"
+ },
+ "main": "src/index.js",
+ "author": "Devon Govett ",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/devongovett/browserify-zlib.git"
+ }
+}
diff --git a/node_modules/browserify-zlib/src/binding.js b/node_modules/browserify-zlib/src/binding.js
new file mode 100644
index 0000000..7244b43
--- /dev/null
+++ b/node_modules/browserify-zlib/src/binding.js
@@ -0,0 +1,236 @@
+var msg = require('pako/lib/zlib/messages');
+var zstream = require('pako/lib/zlib/zstream');
+var zlib_deflate = require('pako/lib/zlib/deflate.js');
+var zlib_inflate = require('pako/lib/zlib/inflate.js');
+var constants = require('pako/lib/zlib/constants');
+
+for (var key in constants) {
+ exports[key] = constants[key];
+}
+
+// zlib modes
+exports.NONE = 0;
+exports.DEFLATE = 1;
+exports.INFLATE = 2;
+exports.GZIP = 3;
+exports.GUNZIP = 4;
+exports.DEFLATERAW = 5;
+exports.INFLATERAW = 6;
+exports.UNZIP = 7;
+
+/**
+ * Emulate Node's zlib C++ layer for use by the JS layer in index.js
+ */
+function Zlib(mode) {
+ if (mode < exports.DEFLATE || mode > exports.UNZIP)
+ throw new TypeError("Bad argument");
+
+ this.mode = mode;
+ this.init_done = false;
+ this.write_in_progress = false;
+ this.pending_close = false;
+ this.windowBits = 0;
+ this.level = 0;
+ this.memLevel = 0;
+ this.strategy = 0;
+ this.dictionary = null;
+}
+
+Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
+ this.windowBits = windowBits;
+ this.level = level;
+ this.memLevel = memLevel;
+ this.strategy = strategy;
+ // dictionary not supported.
+
+ if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
+ this.windowBits += 16;
+
+ if (this.mode === exports.UNZIP)
+ this.windowBits += 32;
+
+ if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
+ this.windowBits = -this.windowBits;
+
+ this.strm = new zstream();
+
+ switch (this.mode) {
+ case exports.DEFLATE:
+ case exports.GZIP:
+ case exports.DEFLATERAW:
+ var status = zlib_deflate.deflateInit2(
+ this.strm,
+ this.level,
+ exports.Z_DEFLATED,
+ this.windowBits,
+ this.memLevel,
+ this.strategy
+ );
+ break;
+ case exports.INFLATE:
+ case exports.GUNZIP:
+ case exports.INFLATERAW:
+ case exports.UNZIP:
+ var status = zlib_inflate.inflateInit2(
+ this.strm,
+ this.windowBits
+ );
+ break;
+ default:
+ throw new Error("Unknown mode " + this.mode);
+ }
+
+ if (status !== exports.Z_OK) {
+ this._error(status);
+ return;
+ }
+
+ this.write_in_progress = false;
+ this.init_done = true;
+};
+
+Zlib.prototype.params = function() {
+ throw new Error("deflateParams Not supported");
+};
+
+Zlib.prototype._writeCheck = function() {
+ if (!this.init_done)
+ throw new Error("write before init");
+
+ if (this.mode === exports.NONE)
+ throw new Error("already finalized");
+
+ if (this.write_in_progress)
+ throw new Error("write already in progress");
+
+ if (this.pending_close)
+ throw new Error("close is pending");
+};
+
+Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this._writeCheck();
+ this.write_in_progress = true;
+
+ var self = this;
+ process.nextTick(function() {
+ self.write_in_progress = false;
+ var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
+ self.callback(res[0], res[1]);
+
+ if (self.pending_close)
+ self.close();
+ });
+
+ return this;
+};
+
+// set method for Node buffers, used by pako
+function bufferSet(data, offset) {
+ for (var i = 0; i < data.length; i++) {
+ this[offset + i] = data[i];
+ }
+}
+
+Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this._writeCheck();
+ return this._write(flush, input, in_off, in_len, out, out_off, out_len);
+};
+
+Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
+ this.write_in_progress = true;
+
+ if (flush !== exports.Z_NO_FLUSH &&
+ flush !== exports.Z_PARTIAL_FLUSH &&
+ flush !== exports.Z_SYNC_FLUSH &&
+ flush !== exports.Z_FULL_FLUSH &&
+ flush !== exports.Z_FINISH &&
+ flush !== exports.Z_BLOCK) {
+ throw new Error("Invalid flush value");
+ }
+
+ if (input == null) {
+ input = new Buffer(0);
+ in_len = 0;
+ in_off = 0;
+ }
+
+ if (out._set)
+ out.set = out._set;
+ else
+ out.set = bufferSet;
+
+ var strm = this.strm;
+ strm.avail_in = in_len;
+ strm.input = input;
+ strm.next_in = in_off;
+ strm.avail_out = out_len;
+ strm.output = out;
+ strm.next_out = out_off;
+
+ switch (this.mode) {
+ case exports.DEFLATE:
+ case exports.GZIP:
+ case exports.DEFLATERAW:
+ var status = zlib_deflate.deflate(strm, flush);
+ break;
+ case exports.UNZIP:
+ case exports.INFLATE:
+ case exports.GUNZIP:
+ case exports.INFLATERAW:
+ var status = zlib_inflate.inflate(strm, flush);
+ break;
+ default:
+ throw new Error("Unknown mode " + this.mode);
+ }
+
+ if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
+ this._error(status);
+ }
+
+ this.write_in_progress = false;
+ return [strm.avail_in, strm.avail_out];
+};
+
+Zlib.prototype.close = function() {
+ if (this.write_in_progress) {
+ this.pending_close = true;
+ return;
+ }
+
+ this.pending_close = false;
+
+ if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
+ zlib_deflate.deflateEnd(this.strm);
+ } else {
+ zlib_inflate.inflateEnd(this.strm);
+ }
+
+ this.mode = exports.NONE;
+};
+
+Zlib.prototype.reset = function() {
+ switch (this.mode) {
+ case exports.DEFLATE:
+ case exports.DEFLATERAW:
+ var status = zlib_deflate.deflateReset(this.strm);
+ break;
+ case exports.INFLATE:
+ case exports.INFLATERAW:
+ var status = zlib_inflate.inflateReset(this.strm);
+ break;
+ }
+
+ if (status !== exports.Z_OK) {
+ this._error(status);
+ }
+};
+
+Zlib.prototype._error = function(status) {
+ this.onerror(msg[status] + ': ' + this.strm.msg, status);
+
+ this.write_in_progress = false;
+ if (this.pending_close)
+ this.close();
+};
+
+exports.Zlib = Zlib;
diff --git a/node_modules/browserify-zlib/src/index.js b/node_modules/browserify-zlib/src/index.js
new file mode 100644
index 0000000..032689c
--- /dev/null
+++ b/node_modules/browserify-zlib/src/index.js
@@ -0,0 +1,610 @@
+// 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 Transform = require('_stream_transform');
+
+var binding = require('./binding');
+var util = require('util');
+var assert = require('assert').ok;
+
+// zlib doesn't provide these, so kludge them in following the same
+// const naming scheme zlib uses.
+binding.Z_MIN_WINDOWBITS = 8;
+binding.Z_MAX_WINDOWBITS = 15;
+binding.Z_DEFAULT_WINDOWBITS = 15;
+
+// fewer than 64 bytes per chunk is stupid.
+// technically it could work with as few as 8, but even 64 bytes
+// is absurdly low. Usually a MB or more is best.
+binding.Z_MIN_CHUNK = 64;
+binding.Z_MAX_CHUNK = Infinity;
+binding.Z_DEFAULT_CHUNK = (16 * 1024);
+
+binding.Z_MIN_MEMLEVEL = 1;
+binding.Z_MAX_MEMLEVEL = 9;
+binding.Z_DEFAULT_MEMLEVEL = 8;
+
+binding.Z_MIN_LEVEL = -1;
+binding.Z_MAX_LEVEL = 9;
+binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
+
+// expose all the zlib constants
+Object.keys(binding).forEach(function(k) {
+ if (k.match(/^Z/)) exports[k] = binding[k];
+});
+
+// translation table for return codes.
+exports.codes = {
+ Z_OK: binding.Z_OK,
+ Z_STREAM_END: binding.Z_STREAM_END,
+ Z_NEED_DICT: binding.Z_NEED_DICT,
+ Z_ERRNO: binding.Z_ERRNO,
+ Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
+ Z_DATA_ERROR: binding.Z_DATA_ERROR,
+ Z_MEM_ERROR: binding.Z_MEM_ERROR,
+ Z_BUF_ERROR: binding.Z_BUF_ERROR,
+ Z_VERSION_ERROR: binding.Z_VERSION_ERROR
+};
+
+Object.keys(exports.codes).forEach(function(k) {
+ exports.codes[exports.codes[k]] = k;
+});
+
+exports.Deflate = Deflate;
+exports.Inflate = Inflate;
+exports.Gzip = Gzip;
+exports.Gunzip = Gunzip;
+exports.DeflateRaw = DeflateRaw;
+exports.InflateRaw = InflateRaw;
+exports.Unzip = Unzip;
+
+exports.createDeflate = function(o) {
+ return new Deflate(o);
+};
+
+exports.createInflate = function(o) {
+ return new Inflate(o);
+};
+
+exports.createDeflateRaw = function(o) {
+ return new DeflateRaw(o);
+};
+
+exports.createInflateRaw = function(o) {
+ return new InflateRaw(o);
+};
+
+exports.createGzip = function(o) {
+ return new Gzip(o);
+};
+
+exports.createGunzip = function(o) {
+ return new Gunzip(o);
+};
+
+exports.createUnzip = function(o) {
+ return new Unzip(o);
+};
+
+
+// Convenience methods.
+// compress/decompress a string or buffer in one step.
+exports.deflate = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Deflate(opts), buffer, callback);
+};
+
+exports.deflateSync = function(buffer, opts) {
+ return zlibBufferSync(new Deflate(opts), buffer);
+};
+
+exports.gzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Gzip(opts), buffer, callback);
+};
+
+exports.gzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Gzip(opts), buffer);
+};
+
+exports.deflateRaw = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new DeflateRaw(opts), buffer, callback);
+};
+
+exports.deflateRawSync = function(buffer, opts) {
+ return zlibBufferSync(new DeflateRaw(opts), buffer);
+};
+
+exports.unzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Unzip(opts), buffer, callback);
+};
+
+exports.unzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Unzip(opts), buffer);
+};
+
+exports.inflate = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Inflate(opts), buffer, callback);
+};
+
+exports.inflateSync = function(buffer, opts) {
+ return zlibBufferSync(new Inflate(opts), buffer);
+};
+
+exports.gunzip = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new Gunzip(opts), buffer, callback);
+};
+
+exports.gunzipSync = function(buffer, opts) {
+ return zlibBufferSync(new Gunzip(opts), buffer);
+};
+
+exports.inflateRaw = function(buffer, opts, callback) {
+ if (typeof opts === 'function') {
+ callback = opts;
+ opts = {};
+ }
+ return zlibBuffer(new InflateRaw(opts), buffer, callback);
+};
+
+exports.inflateRawSync = function(buffer, opts) {
+ return zlibBufferSync(new InflateRaw(opts), buffer);
+};
+
+function zlibBuffer(engine, buffer, callback) {
+ var buffers = [];
+ var nread = 0;
+
+ engine.on('error', onError);
+ engine.on('end', onEnd);
+
+ engine.end(buffer);
+ flow();
+
+ function flow() {
+ var chunk;
+ while (null !== (chunk = engine.read())) {
+ buffers.push(chunk);
+ nread += chunk.length;
+ }
+ engine.once('readable', flow);
+ }
+
+ function onError(err) {
+ engine.removeListener('end', onEnd);
+ engine.removeListener('readable', flow);
+ callback(err);
+ }
+
+ function onEnd() {
+ var buf = Buffer.concat(buffers, nread);
+ buffers = [];
+ callback(null, buf);
+ engine.close();
+ }
+}
+
+function zlibBufferSync(engine, buffer) {
+ if (typeof buffer === 'string')
+ buffer = new Buffer(buffer);
+ if (!Buffer.isBuffer(buffer))
+ throw new TypeError('Not a string or buffer');
+
+ var flushFlag = binding.Z_FINISH;
+
+ return engine._processChunk(buffer, flushFlag);
+}
+
+// generic zlib
+// minimal 2-byte header
+function Deflate(opts) {
+ if (!(this instanceof Deflate)) return new Deflate(opts);
+ Zlib.call(this, opts, binding.DEFLATE);
+}
+
+function Inflate(opts) {
+ if (!(this instanceof Inflate)) return new Inflate(opts);
+ Zlib.call(this, opts, binding.INFLATE);
+}
+
+
+
+// gzip - bigger header, same deflate compression
+function Gzip(opts) {
+ if (!(this instanceof Gzip)) return new Gzip(opts);
+ Zlib.call(this, opts, binding.GZIP);
+}
+
+function Gunzip(opts) {
+ if (!(this instanceof Gunzip)) return new Gunzip(opts);
+ Zlib.call(this, opts, binding.GUNZIP);
+}
+
+
+
+// raw - no header
+function DeflateRaw(opts) {
+ if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
+ Zlib.call(this, opts, binding.DEFLATERAW);
+}
+
+function InflateRaw(opts) {
+ if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
+ Zlib.call(this, opts, binding.INFLATERAW);
+}
+
+
+// auto-detect header.
+function Unzip(opts) {
+ if (!(this instanceof Unzip)) return new Unzip(opts);
+ Zlib.call(this, opts, binding.UNZIP);
+}
+
+
+// the Zlib class they all inherit from
+// This thing manages the queue of requests, and returns
+// true or false if there is anything in the queue when
+// you call the .write() method.
+
+function Zlib(opts, mode) {
+ this._opts = opts = opts || {};
+ this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
+
+ Transform.call(this, opts);
+
+ if (opts.flush) {
+ if (opts.flush !== binding.Z_NO_FLUSH &&
+ opts.flush !== binding.Z_PARTIAL_FLUSH &&
+ opts.flush !== binding.Z_SYNC_FLUSH &&
+ opts.flush !== binding.Z_FULL_FLUSH &&
+ opts.flush !== binding.Z_FINISH &&
+ opts.flush !== binding.Z_BLOCK) {
+ throw new Error('Invalid flush flag: ' + opts.flush);
+ }
+ }
+ this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
+
+ if (opts.chunkSize) {
+ if (opts.chunkSize < exports.Z_MIN_CHUNK ||
+ opts.chunkSize > exports.Z_MAX_CHUNK) {
+ throw new Error('Invalid chunk size: ' + opts.chunkSize);
+ }
+ }
+
+ if (opts.windowBits) {
+ if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
+ opts.windowBits > exports.Z_MAX_WINDOWBITS) {
+ throw new Error('Invalid windowBits: ' + opts.windowBits);
+ }
+ }
+
+ if (opts.level) {
+ if (opts.level < exports.Z_MIN_LEVEL ||
+ opts.level > exports.Z_MAX_LEVEL) {
+ throw new Error('Invalid compression level: ' + opts.level);
+ }
+ }
+
+ if (opts.memLevel) {
+ if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
+ opts.memLevel > exports.Z_MAX_MEMLEVEL) {
+ throw new Error('Invalid memLevel: ' + opts.memLevel);
+ }
+ }
+
+ if (opts.strategy) {
+ if (opts.strategy != exports.Z_FILTERED &&
+ opts.strategy != exports.Z_HUFFMAN_ONLY &&
+ opts.strategy != exports.Z_RLE &&
+ opts.strategy != exports.Z_FIXED &&
+ opts.strategy != exports.Z_DEFAULT_STRATEGY) {
+ throw new Error('Invalid strategy: ' + opts.strategy);
+ }
+ }
+
+ if (opts.dictionary) {
+ if (!Buffer.isBuffer(opts.dictionary)) {
+ throw new Error('Invalid dictionary: it should be a Buffer instance');
+ }
+ }
+
+ this._binding = new binding.Zlib(mode);
+
+ var self = this;
+ this._hadError = false;
+ this._binding.onerror = function(message, errno) {
+ // there is no way to cleanly recover.
+ // continuing only obscures problems.
+ self._binding = null;
+ self._hadError = true;
+
+ var error = new Error(message);
+ error.errno = errno;
+ error.code = exports.codes[errno];
+ self.emit('error', error);
+ };
+
+ var level = exports.Z_DEFAULT_COMPRESSION;
+ if (typeof opts.level === 'number') level = opts.level;
+
+ var strategy = exports.Z_DEFAULT_STRATEGY;
+ if (typeof opts.strategy === 'number') strategy = opts.strategy;
+
+ this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
+ level,
+ opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
+ strategy,
+ opts.dictionary);
+
+ this._buffer = new Buffer(this._chunkSize);
+ this._offset = 0;
+ this._closed = false;
+ this._level = level;
+ this._strategy = strategy;
+
+ this.once('end', this.close);
+}
+
+util.inherits(Zlib, Transform);
+
+Zlib.prototype.params = function(level, strategy, callback) {
+ if (level < exports.Z_MIN_LEVEL ||
+ level > exports.Z_MAX_LEVEL) {
+ throw new RangeError('Invalid compression level: ' + level);
+ }
+ if (strategy != exports.Z_FILTERED &&
+ strategy != exports.Z_HUFFMAN_ONLY &&
+ strategy != exports.Z_RLE &&
+ strategy != exports.Z_FIXED &&
+ strategy != exports.Z_DEFAULT_STRATEGY) {
+ throw new TypeError('Invalid strategy: ' + strategy);
+ }
+
+ if (this._level !== level || this._strategy !== strategy) {
+ var self = this;
+ this.flush(binding.Z_SYNC_FLUSH, function() {
+ self._binding.params(level, strategy);
+ if (!self._hadError) {
+ self._level = level;
+ self._strategy = strategy;
+ if (callback) callback();
+ }
+ });
+ } else {
+ process.nextTick(callback);
+ }
+};
+
+Zlib.prototype.reset = function() {
+ return this._binding.reset();
+};
+
+// This is the _flush function called by the transform class,
+// internally, when the last chunk has been written.
+Zlib.prototype._flush = function(callback) {
+ this._transform(new Buffer(0), '', callback);
+};
+
+Zlib.prototype.flush = function(kind, callback) {
+ var ws = this._writableState;
+
+ if (typeof kind === 'function' || (kind === void 0 && !callback)) {
+ callback = kind;
+ kind = binding.Z_FULL_FLUSH;
+ }
+
+ if (ws.ended) {
+ if (callback)
+ process.nextTick(callback);
+ } else if (ws.ending) {
+ if (callback)
+ this.once('end', callback);
+ } else if (ws.needDrain) {
+ var self = this;
+ this.once('drain', function() {
+ self.flush(callback);
+ });
+ } else {
+ this._flushFlag = kind;
+ this.write(new Buffer(0), '', callback);
+ }
+};
+
+Zlib.prototype.close = function(callback) {
+ if (callback)
+ process.nextTick(callback);
+
+ if (this._closed)
+ return;
+
+ this._closed = true;
+
+ this._binding.close();
+
+ var self = this;
+ process.nextTick(function() {
+ self.emit('close');
+ });
+};
+
+Zlib.prototype._transform = function(chunk, encoding, cb) {
+ var flushFlag;
+ var ws = this._writableState;
+ var ending = ws.ending || ws.ended;
+ var last = ending && (!chunk || ws.length === chunk.length);
+
+ if (!chunk === null && !Buffer.isBuffer(chunk))
+ return cb(new Error('invalid input'));
+
+ // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
+ // If it's explicitly flushing at some other time, then we use
+ // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
+ // goodness.
+ if (last)
+ flushFlag = binding.Z_FINISH;
+ else {
+ flushFlag = this._flushFlag;
+ // once we've flushed the last of the queue, stop flushing and
+ // go back to the normal behavior.
+ if (chunk.length >= ws.length) {
+ this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
+ }
+ }
+
+ var self = this;
+ this._processChunk(chunk, flushFlag, cb);
+};
+
+Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
+ var availInBefore = chunk && chunk.length;
+ var availOutBefore = this._chunkSize - this._offset;
+ var inOff = 0;
+
+ var self = this;
+
+ var async = typeof cb === 'function';
+
+ if (!async) {
+ var buffers = [];
+ var nread = 0;
+
+ var error;
+ this.on('error', function(er) {
+ error = er;
+ });
+
+ do {
+ var res = this._binding.writeSync(flushFlag,
+ chunk, // in
+ inOff, // in_off
+ availInBefore, // in_len
+ this._buffer, // out
+ this._offset, //out_off
+ availOutBefore); // out_len
+ } while (!this._hadError && callback(res[0], res[1]));
+
+ if (this._hadError) {
+ throw error;
+ }
+
+ var buf = Buffer.concat(buffers, nread);
+ this.close();
+
+ return buf;
+ }
+
+ var req = this._binding.write(flushFlag,
+ chunk, // in
+ inOff, // in_off
+ availInBefore, // in_len
+ this._buffer, // out
+ this._offset, //out_off
+ availOutBefore); // out_len
+
+ req.buffer = chunk;
+ req.callback = callback;
+
+ function callback(availInAfter, availOutAfter) {
+ if (self._hadError)
+ return;
+
+ var have = availOutBefore - availOutAfter;
+ assert(have >= 0, 'have should not go down');
+
+ if (have > 0) {
+ var out = self._buffer.slice(self._offset, self._offset + have);
+ self._offset += have;
+ // serve some output to the consumer.
+ if (async) {
+ self.push(out);
+ } else {
+ buffers.push(out);
+ nread += out.length;
+ }
+ }
+
+ // exhausted the output buffer, or used all the input create a new one.
+ if (availOutAfter === 0 || self._offset >= self._chunkSize) {
+ availOutBefore = self._chunkSize;
+ self._offset = 0;
+ self._buffer = new Buffer(self._chunkSize);
+ }
+
+ if (availOutAfter === 0) {
+ // Not actually done. Need to reprocess.
+ // Also, update the availInBefore to the availInAfter value,
+ // so that if we have to hit it a third (fourth, etc.) time,
+ // it'll have the correct byte counts.
+ inOff += (availInBefore - availInAfter);
+ availInBefore = availInAfter;
+
+ if (!async)
+ return true;
+
+ var newReq = self._binding.write(flushFlag,
+ chunk,
+ inOff,
+ availInBefore,
+ self._buffer,
+ self._offset,
+ self._chunkSize);
+ newReq.callback = callback; // this same function
+ newReq.buffer = chunk;
+ return;
+ }
+
+ if (!async)
+ return false;
+
+ // finished with the chunk.
+ cb();
+ }
+};
+
+util.inherits(Deflate, Zlib);
+util.inherits(Inflate, Zlib);
+util.inherits(Gzip, Zlib);
+util.inherits(Gunzip, Zlib);
+util.inherits(DeflateRaw, Zlib);
+util.inherits(InflateRaw, Zlib);
+util.inherits(Unzip, Zlib);
diff --git a/node_modules/browserify-zlib/test/fixtures/elipses.txt b/node_modules/browserify-zlib/test/fixtures/elipses.txt
new file mode 100644
index 0000000..6105600
--- /dev/null
+++ b/node_modules/browserify-zlib/test/fixtures/elipses.txt
@@ -0,0 +1 @@
+…………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………
\ No newline at end of file
diff --git a/node_modules/browserify-zlib/test/fixtures/empty.txt b/node_modules/browserify-zlib/test/fixtures/empty.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/node_modules/browserify-zlib/test/fixtures/empty.txt
@@ -0,0 +1 @@
+
diff --git a/node_modules/browserify-zlib/test/fixtures/person.jpg b/node_modules/browserify-zlib/test/fixtures/person.jpg
new file mode 100644
index 0000000..4f71881
Binary files /dev/null and b/node_modules/browserify-zlib/test/fixtures/person.jpg differ
diff --git a/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js b/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js
new file mode 100755
index 0000000..fd35a01
--- /dev/null
+++ b/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary-fail.js
@@ -0,0 +1,48 @@
+// 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 zlib = require('zlib');
+
+// Should raise an error, not trigger an assertion in src/node_zlib.cc
+(function() {
+ var stream = zlib.createInflate();
+
+ stream.on('error', common.mustCall(function(err) {
+ assert(/Missing dictionary/.test(err.message));
+ }));
+
+ // String "test" encoded with dictionary "dict".
+ stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5]));
+})();
+
+// Should raise an error, not trigger an assertion in src/node_zlib.cc
+(function() {
+ var stream = zlib.createInflate({ dictionary: Buffer('fail') });
+
+ stream.on('error', common.mustCall(function(err) {
+ assert(/Bad dictionary/.test(err.message));
+ }));
+
+ // String "test" encoded with dictionary "dict".
+ stream.write(Buffer([0x78,0xBB,0x04,0x09,0x01,0xA5]));
+})();
diff --git a/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js b/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js
new file mode 100755
index 0000000..58da810
--- /dev/null
+++ b/node_modules/browserify-zlib/test/ignored/test-zlib-dictionary.js
@@ -0,0 +1,95 @@
+// 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.
+
+// test compression/decompression with dictionary
+
+var common = require('../common.js');
+var assert = require('assert');
+var zlib = require('zlib');
+var path = require('path');
+
+var spdyDict = new Buffer([
+ 'optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-',
+ 'languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi',
+ 'f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser',
+ '-agent10010120020120220320420520630030130230330430530630740040140240340440',
+ '5406407408409410411412413414415416417500501502503504505accept-rangesageeta',
+ 'glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic',
+ 'ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran',
+ 'sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati',
+ 'oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo',
+ 'ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe',
+ 'pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic',
+ 'ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1',
+ '.1statusversionurl\0'
+].join(''));
+
+var deflate = zlib.createDeflate({ dictionary: spdyDict });
+
+var input = [
+ 'HTTP/1.1 200 Ok',
+ 'Server: node.js',
+ 'Content-Length: 0',
+ ''
+].join('\r\n');
+
+var called = 0;
+
+//
+// We'll use clean-new inflate stream each time
+// and .reset() old dirty deflate one
+//
+function run(num) {
+ var inflate = zlib.createInflate({ dictionary: spdyDict });
+
+ if (num === 2) {
+ deflate.reset();
+ deflate.removeAllListeners('data');
+ }
+
+ // Put data into deflate stream
+ deflate.on('data', function(chunk) {
+ inflate.write(chunk);
+ });
+
+ // Get data from inflate stream
+ var output = [];
+ inflate.on('data', function(chunk) {
+ output.push(chunk);
+ });
+ inflate.on('end', function() {
+ called++;
+
+ assert.equal(output.join(''), input);
+
+ if (num < 2) run(num + 1);
+ });
+
+ deflate.write(input);
+ deflate.flush(function() {
+ inflate.end();
+ });
+}
+run(1);
+
+process.on('exit', function() {
+ assert.equal(called, 2);
+});
diff --git a/node_modules/browserify-zlib/test/ignored/test-zlib-params.js b/node_modules/browserify-zlib/test/ignored/test-zlib-params.js
new file mode 100755
index 0000000..006f1ea
--- /dev/null
+++ b/node_modules/browserify-zlib/test/ignored/test-zlib-params.js
@@ -0,0 +1,33 @@
+var common = require('../common.js');
+var assert = require('assert');
+var zlib = require('zlib');
+var path = require('path');
+var fs = require('fs');
+
+var file = fs.readFileSync(path.resolve(common.fixturesDir, 'person.jpg')),
+ chunkSize = 24 * 1024,
+ opts = { level: 9, strategy: zlib.Z_DEFAULT_STRATEGY },
+ deflater = zlib.createDeflate(opts);
+
+var chunk1 = file.slice(0, chunkSize),
+ chunk2 = file.slice(chunkSize),
+ blkhdr = new Buffer([0x00, 0x48, 0x82, 0xb7, 0x7d]),
+ expected = Buffer.concat([blkhdr, chunk2]),
+ actual;
+
+deflater.write(chunk1, function() {
+ deflater.params(0, zlib.Z_DEFAULT_STRATEGY, function() {
+ while (deflater.read());
+ deflater.end(chunk2, function() {
+ var bufs = [], buf;
+ while (buf = deflater.read())
+ bufs.push(buf);
+ actual = Buffer.concat(bufs);
+ });
+ });
+ while (deflater.read());
+});
+
+process.once('exit', function() {
+ assert.deepEqual(actual, expected);
+});
diff --git a/node_modules/browserify-zlib/test/package.json b/node_modules/browserify-zlib/test/package.json
new file mode 100644
index 0000000..189e120
--- /dev/null
+++ b/node_modules/browserify-zlib/test/package.json
@@ -0,0 +1,7 @@
+{
+ "browserify": {
+ "transform": [
+ "brfs"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/node_modules/browserify-zlib/test/test-zlib-close-after-write.js b/node_modules/browserify-zlib/test/test-zlib-close-after-write.js
new file mode 100755
index 0000000..6d5a083
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-close-after-write.js
@@ -0,0 +1,35 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+
+tape(function(t) {
+ t.plan(1);
+
+ zlib.gzip('hello', function(err, out) {
+ var unzip = zlib.createGunzip();
+ unzip.write(out);
+ unzip.close(function() {
+ t.ok(true);
+ });
+ });
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js b/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js
new file mode 100755
index 0000000..223160b
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-convenience-methods.js
@@ -0,0 +1,70 @@
+// 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.
+
+// test convenience methods with and without options supplied
+
+var tape = require('tape');
+var zlib = require('../');
+
+var expect = 'blahblahblahblahblahblah';
+var opts = {
+ level: 9,
+ chunkSize: 1024,
+};
+
+[
+ ['gzip', 'gunzip'],
+ ['gzip', 'unzip'],
+ ['deflate', 'inflate'],
+ ['deflateRaw', 'inflateRaw'],
+].forEach(function(method) {
+ tape(method.join(' '), function(t) {
+ t.plan(4);
+
+ zlib[method[0]](expect, opts, function(err, result) {
+ zlib[method[1]](result, opts, function(err, result) {
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' with options.');
+ });
+ });
+
+ zlib[method[0]](expect, function(err, result) {
+ zlib[method[1]](result, function(err, result) {
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' without options.');
+ });
+ });
+
+ var result = zlib[method[0] + 'Sync'](expect, opts);
+ result = zlib[method[1] + 'Sync'](result, opts);
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' with options.');
+
+ result = zlib[method[0] + 'Sync'](expect);
+ result = zlib[method[1] + 'Sync'](result);
+ t.deepEqual(result, new Buffer(expect),
+ 'Should get original string after ' +
+ method[0] + '/' + method[1] + ' without options.');
+ });
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib-from-string.js b/node_modules/browserify-zlib/test/test-zlib-from-string.js
new file mode 100755
index 0000000..0376c55
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-from-string.js
@@ -0,0 +1,89 @@
+// 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.
+
+// test compressing and uncompressing a string with zlib
+
+var tape = require('tape');
+var zlib = require('../');
+
+var inputString = '\u03A9\u03A9Lorem ipsum dolor sit amet, consectetur adipiscing el' +
+ 'it. Morbi faucibus, purus at gravida dictum, libero arcu convallis la' +
+ 'cus, in commodo libero metus eu nisi. Nullam commodo, neque nec porta' +
+ ' placerat, nisi est fermentum augue, vitae gravida tellus sapien sit ' +
+ 'amet tellus. Aenean non diam orci. Proin quis elit turpis. Suspendiss' +
+ 'e non diam ipsum. Suspendisse nec ullamcorper odio. Vestibulum arcu m' +
+ 'i, sodales non suscipit id, ultrices ut massa. Sed ac sem sit amet ar' +
+ 'cu malesuada fermentum. Nunc sed. ';
+var expectedBase64Deflate = 'eJxdUUtOQzEMvMoc4OndgT0gJCT2buJWlpI4jePeqZfpm' +
+ 'XAKLRKbLOzx/HK73q6vOrhCunlF1qIDJhNUeW5I2ozT5OkDlKWLJWkncJG5403HQXAkT3' +
+ 'Jw29B9uIEmToMukglZ0vS6ociBh4JG8sV4oVLEUCitK2kxq1WzPnChHDzsaGKy491Lofo' +
+ 'AbWh8do43oeuYhB5EPCjcLjzYJo48KrfQBvnJecNFJvHT1+RSQsGoC7dn2t/xjhduTA1N' +
+ 'WyQIZR0pbHwMDatnD+crPqKSqGPHp1vnlsWM/07ubf7bheF7kqSj84Bm0R1fYTfaK8vqq' +
+ 'qfKBtNMhe3OZh6N95CTvMX5HJJi4xOVzCgUOIMSLH7wmeOHaFE4RdpnGavKtrB5xzfO/Ll9';
+var expectedBase64Gzip = 'H4sIAAAAAAAAA11RS05DMQy8yhzg6d2BPSAkJPZu4laWkjiN' +
+ '496pl+mZcAotEpss7PH8crverq86uEK6eUXWogMmE1R5bkjajNPk6QOUpYslaSdwkbnjT' +
+ 'cdBcCRPcnDb0H24gSZOgy6SCVnS9LqhyIGHgkbyxXihUsRQKK0raTGrVbM+cKEcPOxoYr' +
+ 'Lj3Uuh+gBtaHx2jjeh65iEHkQ8KNwuPNgmjjwqt9AG+cl5w0Um8dPX5FJCwagLt2fa3/G' +
+ 'OF25MDU1bJAhlHSlsfAwNq2cP5ys+opKoY8enW+eWxYz/Tu5t/tuF4XuSpKPzgGbRHV9h' +
+ 'N9ory+qqp8oG00yF7c5mHo33kJO8xfkckmLjE5XMKBQ4gxIsfvCZ44doUThF2mcZq8q2s' +
+ 'HnHNzRtagj5AQAA';
+
+tape('deflate', function(t) {
+ t.plan(1);
+ zlib.deflate(inputString, function(err, buffer) {
+ t.equal(buffer.toString('base64'), expectedBase64Deflate,
+ 'deflate encoded string should match');
+ });
+});
+
+tape('gzip', function(t) {
+ t.plan(1);
+ zlib.gzip(inputString, function(err, buffer) {
+ // Can't actually guarantee that we'll get exactly the same
+ // deflated bytes when we compress a string, since the header
+ // depends on stuff other than the input string itself.
+ // However, decrypting it should definitely yield the same
+ // result that we're expecting, and this should match what we get
+ // from inflating the known valid deflate data.
+ zlib.gunzip(buffer, function(err, gunzipped) {
+ t.equal(gunzipped.toString(), inputString,
+ 'Should get original string after gzip/gunzip');
+ });
+ });
+});
+
+tape('unzip deflate', function(t) {
+ t.plan(1);
+ var buffer = new Buffer(expectedBase64Deflate, 'base64');
+ zlib.unzip(buffer, function(err, buffer) {
+ t.equal(buffer.toString(), inputString,
+ 'decoded inflated string should match');
+ });
+});
+
+tape('unzip gzip', function(t) {
+ t.plan(1);
+ buffer = new Buffer(expectedBase64Gzip, 'base64');
+ zlib.unzip(buffer, function(err, buffer) {
+ t.equal(buffer.toString(), inputString,
+ 'decoded gunzipped string should match');
+ });
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib-invalid-input.js b/node_modules/browserify-zlib/test/test-zlib-invalid-input.js
new file mode 100755
index 0000000..5ac08c3
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-invalid-input.js
@@ -0,0 +1,62 @@
+// 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.
+
+// test uncompressing invalid input
+
+var tape = require('tape'),
+ zlib = require('../');
+
+tape('non-strings', function(t) {
+ var nonStringInputs = [1, true, {a: 1}, ['a']];
+ t.plan(12);
+
+ nonStringInputs.forEach(function(input) {
+ // zlib.gunzip should not throw an error when called with bad input.
+ t.doesNotThrow(function() {
+ zlib.gunzip(input, function(err, buffer) {
+ // zlib.gunzip should pass the error to the callback.
+ t.ok(err);
+ });
+ });
+ });
+});
+
+tape('unzips', function(t) {
+ // zlib.Unzip classes need to get valid data, or else they'll throw.
+ var unzips = [ zlib.Unzip(),
+ zlib.Gunzip(),
+ zlib.Inflate(),
+ zlib.InflateRaw() ];
+
+ t.plan(4);
+ unzips.forEach(function (uz, i) {
+ uz.on('error', function(er) {
+ t.ok(er);
+ });
+
+ uz.on('end', function(er) {
+ throw new Error('end event should not be emitted '+uz.constructor.name);
+ });
+
+ // this will trigger error event
+ uz.write('this is not valid compressed data.');
+ });
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js b/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js
new file mode 100755
index 0000000..6dba4c2
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-random-byte-pipes.js
@@ -0,0 +1,176 @@
+// 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 crypto = require('crypto');
+var stream = require('stream');
+var Stream = stream.Stream;
+var util = require('util');
+var tape = require('tape');
+var zlib = require('../');
+
+
+
+// emit random bytes, and keep a shasum
+function RandomReadStream(opt) {
+ Stream.call(this);
+
+ this.readable = true;
+ this._paused = false;
+ this._processing = false;
+
+ this._hasher = crypto.createHash('sha1');
+ opt = opt || {};
+
+ // base block size.
+ opt.block = opt.block || 256 * 1024;
+
+ // total number of bytes to emit
+ opt.total = opt.total || 256 * 1024 * 1024;
+ this._remaining = opt.total;
+
+ // how variable to make the block sizes
+ opt.jitter = opt.jitter || 1024;
+
+ this._opt = opt;
+
+ this._process = this._process.bind(this);
+
+ process.nextTick(this._process);
+}
+
+util.inherits(RandomReadStream, Stream);
+
+RandomReadStream.prototype.pause = function() {
+ this._paused = true;
+ this.emit('pause');
+};
+
+RandomReadStream.prototype.resume = function() {
+ this._paused = false;
+ this.emit('resume');
+ this._process();
+};
+
+RandomReadStream.prototype._process = function() {
+ if (this._processing) return;
+ if (this._paused) return;
+
+ this._processing = true;
+
+ if (!this._remaining) {
+ this._hash = this._hasher.digest('hex').toLowerCase().trim();
+ this._processing = false;
+
+ this.emit('end');
+ return;
+ }
+
+ // figure out how many bytes to output
+ // if finished, then just emit end.
+ var block = this._opt.block;
+ var jitter = this._opt.jitter;
+ if (jitter) {
+ block += Math.ceil(Math.random() * jitter - (jitter / 2));
+ }
+ block = Math.min(block, this._remaining);
+ var buf = new Buffer(block);
+ for (var i = 0; i < block; i++) {
+ buf[i] = Math.random() * 256;
+ }
+
+ this._hasher.update(buf);
+
+ this._remaining -= block;
+
+ this._processing = false;
+
+ this.emit('data', buf);
+ process.nextTick(this._process);
+};
+
+
+// a filter that just verifies a shasum
+function HashStream() {
+ Stream.call(this);
+
+ this.readable = this.writable = true;
+ this._hasher = crypto.createHash('sha1');
+}
+
+util.inherits(HashStream, Stream);
+
+HashStream.prototype.write = function(c) {
+ // Simulate the way that an fs.ReadStream returns false
+ // on *every* write like a jerk, only to resume a
+ // moment later.
+ this._hasher.update(c);
+ process.nextTick(this.resume.bind(this));
+ return false;
+};
+
+HashStream.prototype.resume = function() {
+ this.emit('resume');
+ process.nextTick(this.emit.bind(this, 'drain'));
+};
+
+HashStream.prototype.end = function(c) {
+ if (c) {
+ this.write(c);
+ }
+ this._hash = this._hasher.digest('hex').toLowerCase().trim();
+ this.emit('data', this._hash);
+ this.emit('end');
+};
+
+tape('random byte pipes', function(t) {
+ var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 });
+ var out = new HashStream();
+ var gzip = zlib.createGzip();
+ var gunz = zlib.createGunzip();
+
+ inp.pipe(gzip).pipe(gunz).pipe(out);
+
+ inp.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ gzip.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ gunz.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ out.on('data', function(c) {
+ t.ok(c.length);
+ });
+
+ out.on('data', function(c) {
+ t.ok(c.length);
+ t.equal(c, inp._hash, 'hashes should match');
+ });
+
+ out.on('end', function() {
+ t.end();
+ })
+});
+
diff --git a/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js b/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js
new file mode 100755
index 0000000..5841ef8
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-write-after-flush.js
@@ -0,0 +1,55 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+var fs = require('fs');
+
+tape('write after flush', function(t) {
+ t.plan(2);
+
+ var gzip = zlib.createGzip();
+ var gunz = zlib.createUnzip();
+
+ gzip.pipe(gunz);
+
+ var output = '';
+ var input = 'A line of data\n';
+ gunz.setEncoding('utf8');
+ gunz.on('data', function(c) {
+ output += c;
+ });
+
+ gunz.on('end', function() {
+ t.equal(output, input);
+
+ // Make sure that the flush flag was set back to normal
+ t.equal(gzip._flushFlag, zlib.Z_NO_FLUSH);
+ });
+
+ // make sure that flush/write doesn't trigger an assert failure
+ gzip.flush(); write();
+ function write() {
+ gzip.write(input);
+ gzip.end();
+ gunz.read(0);
+ }
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib-zero-byte.js b/node_modules/browserify-zlib/test/test-zlib-zero-byte.js
new file mode 100755
index 0000000..88bdd8c
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib-zero-byte.js
@@ -0,0 +1,41 @@
+// 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 tape = require('tape');
+var zlib = require('../');
+
+tape('zero byte', function(t) {
+ t.plan(2);
+ var gz = zlib.Gzip()
+ var emptyBuffer = new Buffer(0);
+ var received = 0;
+ gz.on('data', function(c) {
+ received += c.length;
+ });
+ gz.on('end', function() {
+ t.equal(received, 20);
+ });
+ gz.on('finish', function() {
+ t.ok(true);
+ });
+ gz.write(emptyBuffer);
+ gz.end();
+});
diff --git a/node_modules/browserify-zlib/test/test-zlib.js b/node_modules/browserify-zlib/test/test-zlib.js
new file mode 100644
index 0000000..64c02c5
--- /dev/null
+++ b/node_modules/browserify-zlib/test/test-zlib.js
@@ -0,0 +1,206 @@
+// 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 assert = require('assert');
+var zlib = require('../');
+var path = require('path');
+
+var zlibPairs =
+ [[zlib.Deflate, zlib.Inflate],
+ [zlib.Gzip, zlib.Gunzip],
+ [zlib.Deflate, zlib.Unzip],
+ [zlib.Gzip, zlib.Unzip],
+ [zlib.DeflateRaw, zlib.InflateRaw]];
+
+// how fast to trickle through the slowstream
+var trickle = [128, 1024, 1024 * 1024];
+
+// tunable options for zlib classes.
+
+// several different chunk sizes
+var chunkSize = [128, 1024, 1024 * 16, 1024 * 1024];
+
+// this is every possible value.
+var level = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+var windowBits = [8, 9, 10, 11, 12, 13, 14, 15];
+var memLevel = [1, 2, 3, 4, 5, 6, 7, 8, 9];
+var strategy = [0, 1, 2, 3, 4];
+
+// it's nice in theory to test every combination, but it
+// takes WAY too long. Maybe a pummel test could do this?
+if (!process.env.PUMMEL) {
+ trickle = [1024];
+ chunkSize = [1024 * 16];
+ level = [6];
+ memLevel = [8];
+ windowBits = [15];
+ strategy = [0];
+}
+
+var fs = require('fs');
+
+if (process.env.FAST) {
+ zlibPairs = [[zlib.Gzip, zlib.Unzip]];
+}
+
+var tests = {
+ 'person.jpg': fs.readFileSync(__dirname + '/fixtures/person.jpg'),
+ 'elipses.txt': fs.readFileSync(__dirname + '/fixtures/elipses.txt'),
+ 'empty.txt': fs.readFileSync(__dirname + '/fixtures/empty.txt')
+};
+
+var util = require('util');
+var stream = require('stream');
+
+
+// stream that saves everything
+function BufferStream() {
+ this.chunks = [];
+ this.length = 0;
+ this.writable = true;
+ this.readable = true;
+}
+
+util.inherits(BufferStream, stream.Stream);
+
+BufferStream.prototype.write = function(c) {
+ this.chunks.push(c);
+ this.length += c.length;
+ return true;
+};
+
+BufferStream.prototype.end = function(c) {
+ if (c) this.write(c);
+ // flatten
+ var buf = new Buffer(this.length);
+ var i = 0;
+ this.chunks.forEach(function(c) {
+ c.copy(buf, i);
+ i += c.length;
+ });
+ this.emit('data', buf);
+ this.emit('end');
+ return true;
+};
+
+
+function SlowStream(trickle) {
+ this.trickle = trickle;
+ this.offset = 0;
+ this.readable = this.writable = true;
+}
+
+util.inherits(SlowStream, stream.Stream);
+
+SlowStream.prototype.write = function() {
+ throw new Error('not implemented, just call ss.end(chunk)');
+};
+
+SlowStream.prototype.pause = function() {
+ this.paused = true;
+ this.emit('pause');
+};
+
+SlowStream.prototype.resume = function() {
+ var self = this;
+ if (self.ended) return;
+ self.emit('resume');
+ if (!self.chunk) return;
+ self.paused = false;
+ emit();
+ function emit() {
+ if (self.paused) return;
+ if (self.offset >= self.length) {
+ self.ended = true;
+ return self.emit('end');
+ }
+ var end = Math.min(self.offset + self.trickle, self.length);
+ var c = self.chunk.slice(self.offset, end);
+ self.offset += c.length;
+ self.emit('data', c);
+ process.nextTick(emit);
+ }
+};
+
+SlowStream.prototype.end = function(chunk) {
+ // walk over the chunk in blocks.
+ var self = this;
+ self.chunk = chunk;
+ self.length = chunk.length;
+ self.resume();
+ return self.ended;
+};
+
+
+
+// for each of the files, make sure that compressing and
+// decompressing results in the same data, for every combination
+// of the options set above.
+var tape = require('tape');
+
+Object.keys(tests).forEach(function(file) {
+ var test = tests[file];
+ chunkSize.forEach(function(chunkSize) {
+ trickle.forEach(function(trickle) {
+ windowBits.forEach(function(windowBits) {
+ level.forEach(function(level) {
+ memLevel.forEach(function(memLevel) {
+ strategy.forEach(function(strategy) {
+ zlibPairs.forEach(function(pair) {
+ var Def = pair[0];
+ var Inf = pair[1];
+ var opts = {
+ level: level,
+ windowBits: windowBits,
+ memLevel: memLevel,
+ strategy: strategy
+ };
+
+ var msg = file + ' ' +
+ chunkSize + ' ' +
+ JSON.stringify(opts) + ' ' +
+ Def.name + ' -> ' + Inf.name;
+
+ tape('zlib ' + msg, function(t) {
+ t.plan(1);
+
+ var def = new Def(opts);
+ var inf = new Inf(opts);
+ var ss = new SlowStream(trickle);
+ var buf = new BufferStream();
+
+ // verify that the same exact buffer comes out the other end.
+ buf.on('data', function(c) {
+ t.deepEqual(c, test);
+ });
+
+ // the magic happens here.
+ ss.pipe(def).pipe(inf).pipe(buf);
+ ss.end(test);
+ });
+ });
+ });
+ });
+ });
+ });
+ });
+ });
+});
diff --git a/node_modules/buffer-shims/index.js b/node_modules/buffer-shims/index.js
new file mode 100644
index 0000000..1cab4c0
--- /dev/null
+++ b/node_modules/buffer-shims/index.js
@@ -0,0 +1,108 @@
+'use strict';
+
+var buffer = require('buffer');
+var Buffer = buffer.Buffer;
+var SlowBuffer = buffer.SlowBuffer;
+var MAX_LEN = buffer.kMaxLength || 2147483647;
+exports.alloc = function alloc(size, fill, encoding) {
+ if (typeof Buffer.alloc === 'function') {
+ return Buffer.alloc(size, fill, encoding);
+ }
+ if (typeof encoding === 'number') {
+ throw new TypeError('encoding must not be number');
+ }
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size > MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ var enc = encoding;
+ var _fill = fill;
+ if (_fill === undefined) {
+ enc = undefined;
+ _fill = 0;
+ }
+ var buf = new Buffer(size);
+ if (typeof _fill === 'string') {
+ var fillBuf = new Buffer(_fill, enc);
+ var flen = fillBuf.length;
+ var i = -1;
+ while (++i < size) {
+ buf[i] = fillBuf[i % flen];
+ }
+ } else {
+ buf.fill(_fill);
+ }
+ return buf;
+}
+exports.allocUnsafe = function allocUnsafe(size) {
+ if (typeof Buffer.allocUnsafe === 'function') {
+ return Buffer.allocUnsafe(size);
+ }
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size > MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ return new Buffer(size);
+}
+exports.from = function from(value, encodingOrOffset, length) {
+ if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
+ return Buffer.from(value, encodingOrOffset, length);
+ }
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number');
+ }
+ if (typeof value === 'string') {
+ return new Buffer(value, encodingOrOffset);
+ }
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ var offset = encodingOrOffset;
+ if (arguments.length === 1) {
+ return new Buffer(value);
+ }
+ if (typeof offset === 'undefined') {
+ offset = 0;
+ }
+ var len = length;
+ if (typeof len === 'undefined') {
+ len = value.byteLength - offset;
+ }
+ if (offset >= value.byteLength) {
+ throw new RangeError('\'offset\' is out of bounds');
+ }
+ if (len > value.byteLength - offset) {
+ throw new RangeError('\'length\' is out of bounds');
+ }
+ return new Buffer(value.slice(offset, offset + len));
+ }
+ if (Buffer.isBuffer(value)) {
+ var out = new Buffer(value.length);
+ value.copy(out, 0, 0, value.length);
+ return out;
+ }
+ if (value) {
+ if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
+ return new Buffer(value);
+ }
+ if (value.type === 'Buffer' && Array.isArray(value.data)) {
+ return new Buffer(value.data);
+ }
+ }
+
+ throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
+}
+exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
+ if (typeof Buffer.allocUnsafeSlow === 'function') {
+ return Buffer.allocUnsafeSlow(size);
+ }
+ if (typeof size !== 'number') {
+ throw new TypeError('size must be a number');
+ }
+ if (size >= MAX_LEN) {
+ throw new RangeError('size is too large');
+ }
+ return new SlowBuffer(size);
+}
diff --git a/node_modules/buffer-shims/license.md b/node_modules/buffer-shims/license.md
new file mode 100644
index 0000000..01cfaef
--- /dev/null
+++ b/node_modules/buffer-shims/license.md
@@ -0,0 +1,19 @@
+# Copyright (c) 2016 Calvin Metcalf
+
+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-shims/package.json b/node_modules/buffer-shims/package.json
new file mode 100644
index 0000000..be34aa4
--- /dev/null
+++ b/node_modules/buffer-shims/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "buffer-shims",
+ "version": "1.0.0",
+ "description": "some shims for node buffers",
+ "main": "index.js",
+ "scripts": {
+ "test": "tape test/*.js"
+ },
+ "files": ["index.js"],
+ "license": "MIT",
+ "devDependencies": {
+ "tape": "^4.5.1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:calvinmetcalf/buffer-shims.git"
+ }
+}
diff --git a/node_modules/buffer-shims/readme.md b/node_modules/buffer-shims/readme.md
new file mode 100644
index 0000000..7ea6475
--- /dev/null
+++ b/node_modules/buffer-shims/readme.md
@@ -0,0 +1,21 @@
+buffer-shims
+===
+
+functions to make sure the new buffer methods work in older browsers.
+
+```js
+var bufferShim = require('buffer-shims');
+bufferShim.from('foo');
+bufferShim.alloc(9, 'cafeface', 'hex');
+bufferShim.allocUnsafe(15);
+bufferShim.allocUnsafeSlow(21);
+```
+
+should just use the original in newer nodes and on older nodes uses fallbacks.
+
+Known Issues
+===
+- this does not patch the buffer object, only the constructor stuff
+- it's actually a polyfill
+
+![](https://i.imgur.com/zxII3jJ.gif)
diff --git a/node_modules/buffer/.npmignore b/node_modules/buffer/.npmignore
new file mode 100644
index 0000000..a274035
--- /dev/null
+++ b/node_modules/buffer/.npmignore
@@ -0,0 +1,2 @@
+.zuul.yml
+perf/
diff --git a/node_modules/buffer/.travis.yml b/node_modules/buffer/.travis.yml
new file mode 100644
index 0000000..6789094
--- /dev/null
+++ b/node_modules/buffer/.travis.yml
@@ -0,0 +1,8 @@
+language: node_js
+node_js:
+- 'node'
+sudo: false
+env:
+ global:
+ - secure: AUsK+8fYSpwIMHcVt8Mu9SpG9RPHp4XDAwCQfpU3d5U65q8OVVC6C+XjvnNmEd2PoEJRHem8ZXEyRVfGM1sttKZLZP70TEKZOpOiRQnZiTQCAJ92TfGsDj/F4LoWSjUZUpfeg9b3iSp8G5dVw3+q9QZPIu6eykASK6bfcg//Cyg=
+ - secure: eQBKJWu7XbhAN4ZvOOhMenC0IPpoYj+wZVVzzsLwUppfJqlrHV0CUW8rJdvZNiaGhYhoyHTnAcynpTE5kZfg3XjevOvF8PGY5wUYCki9BI+rp+pvVPZE/DNUAQpFR2gd2nxMJ4kYv7GVb6i/DfuqJa0h8IuY4zcMuKWwbQd3Az8=
diff --git a/node_modules/buffer/AUTHORS.md b/node_modules/buffer/AUTHORS.md
new file mode 100644
index 0000000..8df343a
--- /dev/null
+++ b/node_modules/buffer/AUTHORS.md
@@ -0,0 +1,44 @@
+# Authors
+
+#### Ordered by first contribution.
+
+- Romain Beauxis (toots@rastageeks.org)
+- Tobias Koppers (tobias.koppers@googlemail.com)
+- Janus (ysangkok@gmail.com)
+- Rainer Dreyer (rdrey1@gmail.com)
+- Tõnis Tiigi (tonistiigi@gmail.com)
+- James Halliday (mail@substack.net)
+- Michael Williamson (mike@zwobble.org)
+- elliottcable (github@elliottcable.name)
+- rafael (rvalle@livelens.net)
+- Andrew Kelley (superjoe30@gmail.com)
+- Andreas Madsen (amwebdk@gmail.com)
+- Mike Brevoort (mike.brevoort@pearson.com)
+- Brian White (mscdex@mscdex.net)
+- Feross Aboukhadijeh (feross@feross.org)
+- Ruben Verborgh (ruben@verborgh.org)
+- eliang (eliang.cs@gmail.com)
+- Jesse Tane (jesse.tane@gmail.com)
+- Alfonso Boza (alfonso@cloud.com)
+- Mathias Buus (mathiasbuus@gmail.com)
+- Devon Govett (devongovett@gmail.com)
+- Daniel Cousens (github@dcousens.com)
+- Joseph Dykstra (josephdykstra@gmail.com)
+- Parsha Pourkhomami (parshap+git@gmail.com)
+- Damjan Košir (damjan.kosir@gmail.com)
+- daverayment (dave.rayment@gmail.com)
+- kawanet (u-suke@kawa.net)
+- Linus Unnebäck (linus@folkdatorn.se)
+- Nolan Lawson (nolan.lawson@gmail.com)
+- Calvin Metcalf (calvin.metcalf@gmail.com)
+- Koki Takahashi (hakatasiloving@gmail.com)
+- Guy Bedford (guybedford@gmail.com)
+- Jan Schär (jscissr@gmail.com)
+- RaulTsc (tomescu.raul@gmail.com)
+- Matthieu Monsch (monsch@alum.mit.edu)
+- Dan Ehrenberg (littledan@chromium.org)
+- Kirill Fomichev (fanatid@ya.ru)
+- Yusuke Kawasaki (u-suke@kawa.net)
+- DC (dcposch@dcpos.ch)
+
+#### Generated by bin/update-authors.sh.
diff --git a/node_modules/buffer/LICENSE b/node_modules/buffer/LICENSE
new file mode 100644
index 0000000..d6bf75d
--- /dev/null
+++ b/node_modules/buffer/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Feross Aboukhadijeh, and other 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/buffer/README.md b/node_modules/buffer/README.md
new file mode 100644
index 0000000..d3b82f6
--- /dev/null
+++ b/node_modules/buffer/README.md
@@ -0,0 +1,378 @@
+# buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url]
+
+#### The buffer module from [node.js](https://nodejs.org/), for the browser.
+
+[![saucelabs][saucelabs-image]][saucelabs-url]
+
+[travis-image]: https://img.shields.io/travis/feross/buffer/master.svg
+[travis-url]: https://travis-ci.org/feross/buffer
+[npm-image]: https://img.shields.io/npm/v/buffer.svg
+[npm-url]: https://npmjs.org/package/buffer
+[downloads-image]: https://img.shields.io/npm/dm/buffer.svg
+[saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg
+[saucelabs-url]: https://saucelabs.com/u/buffer
+
+With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module.
+
+The goal is to provide an API that is 100% identical to
+[node's Buffer API](https://nodejs.org/api/buffer.html). Read the
+[official docs](https://nodejs.org/api/buffer.html) for the full list of properties,
+instance methods, and class methods that are supported.
+
+## features
+
+- Manipulate binary data like a boss, in all browsers -- even IE6!
+- Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`)
+- Extremely small bundle size (**5.04KB minified + gzipped**, 35.5KB with comments)
+- Excellent browser support (IE 6+, Chrome 4+, Firefox 3+, Safari 5.1+, Opera 11+, iOS, etc.)
+- Preserves Node API exactly, with one minor difference (see below)
+- Square-bracket `buf[4]` notation works, even in old browsers like IE6!
+- Does not modify any browser prototypes or put anything on `window`
+- Comprehensive test suite (including all buffer tests from node.js core)
+
+
+## install
+
+To use this module directly (without browserify), install it:
+
+```bash
+npm install buffer
+```
+
+This module was previously called **native-buffer-browserify**, but please use **buffer**
+from now on.
+
+A standalone bundle is available [here](https://wzrd.in/standalone/buffer), for non-browserify users.
+
+
+## usage
+
+The module's API is identical to node's `Buffer` API. Read the
+[official docs](https://nodejs.org/api/buffer.html) for the full list of properties,
+instance methods, and class methods that are supported.
+
+As mentioned above, `require('buffer')` or use the `Buffer` global with
+[browserify](http://browserify.org) and this module will automatically be included
+in your bundle. Almost any npm module will work in the browser, even if it assumes that
+the node `Buffer` API will be available.
+
+To depend on this module explicitly (without browserify), require it like this:
+
+```js
+var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
+```
+
+To require this module explicitly, use `require('buffer/')` which tells the node.js module
+lookup algorithm (also used by browserify) to use the **npm module** named `buffer`
+instead of the **node.js core** module named `buffer`!
+
+
+## how does it work?
+
+The Buffer constructor returns instances of `Uint8Array` that have their prototype
+changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`,
+so the returned instances will have all the node `Buffer` methods and the
+`Uint8Array` methods. Square bracket notation works as expected -- it returns a
+single octet.
+
+The `Uint8Array` prototype remains unmodified.
+
+
+## one minor difference
+
+#### In old browsers, `buf.slice()` does not modify parent buffer's memory
+
+If you only support modern browsers (specifically, those with typed array support),
+then this issue does not affect you. If you support super old browsers, then read on.
+
+In node, the `slice()` method returns a new `Buffer` that shares underlying memory
+with the original Buffer. When you modify one buffer, you modify the other.
+[Read more.](https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end)
+
+In browsers with typed array support, this `Buffer` implementation supports this
+behavior. In browsers without typed arrays, an alternate buffer implementation is
+used that is based on `Object` which has no mechanism to point separate
+`Buffer`s to the same underlying slab of memory.
+
+You can see which browser versions lack typed array support
+[here](https://github.com/feross/buffer/blob/master/index.js#L22-L48).
+
+
+## tracking the latest node api
+
+This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer
+API is considered **stable** in the
+[node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index),
+so it is unlikely that there will ever be breaking changes.
+Nonetheless, when/if the Buffer API changes in node, this module's API will change
+accordingly.
+
+## related packages
+
+- [`buffer-equals`](https://www.npmjs.com/package/buffer-equals) - Node.js 0.12 buffer.equals() ponyfill
+- [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - A lite module for reverse-operations on buffers
+- [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - A simple module for bitwise-xor on buffers
+- [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package
+- [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) - Convert a typed array to a Buffer without a copy
+
+## performance
+
+See perf tests in `/perf`.
+
+`BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a
+sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will
+always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module,
+which is included to compare against.
+
+NOTE: Performance has improved since these benchmarks were taken. PR welcoem to update the README.
+
+### Chrome 38
+
+| Method | Operations | Accuracy | Sampled | Fastest |
+|:-------|:-----------|:---------|:--------|:-------:|
+| BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ |
+| Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | |
+| | | | |
+| BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | |
+| Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | |
+| Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | |
+| Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | |
+| Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ |
+| | | | |
+| BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | |
+| Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ |
+| | | | |
+| BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ |
+| DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | |
+| | | | |
+| BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ |
+| DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | |
+| | | | |
+| BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ |
+| DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | |
+| | | | |
+| BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | |
+| Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ |
+| | | | |
+| BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | |
+| DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ |
+
+
+### Firefox 33
+
+| Method | Operations | Accuracy | Sampled | Fastest |
+|:-------|:-----------|:---------|:--------|:-------:|
+| BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | |
+| Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ |
+| | | | |
+| BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | |
+| Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | |
+| Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | |
+| Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | |
+| Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ |
+| | | | |
+| BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | |
+| Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | |
+| DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | |
+| DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ |
+| DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | |
+| | | | |
+| BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | |
+| Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ |
+| | | | |
+| BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | |
+| DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ |
+
+### Safari 8
+
+| Method | Operations | Accuracy | Sampled | Fastest |
+|:-------|:-----------|:---------|:--------|:-------:|
+| BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ |
+| Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | |
+| | | | |
+| BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | |
+| Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | |
+| Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | |
+| Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ |
+| | | | |
+| BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | |
+| Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ |
+| | | | |
+| BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | |
+| Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ |
+| | | | |
+| BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | |
+| DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ |
+| | | | |
+| BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | |
+| DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ |
+| | | | |
+| BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | |
+| DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ |
+| | | | |
+| BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | |
+| Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ |
+| | | | |
+| BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | |
+| DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ |
+
+
+### Node 0.11.14
+
+| Method | Operations | Accuracy | Sampled | Fastest |
+|:-------|:-----------|:---------|:--------|:-------:|
+| BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | |
+| Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ |
+| NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | |
+| | | | |
+| BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | |
+| Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ |
+| NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | |
+| | | | |
+| BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | |
+| Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ |
+| NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | |
+| | | | |
+| BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | |
+| Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ |
+| NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | |
+| | | | |
+| BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | |
+| Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | |
+| NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ |
+| | | | |
+| BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | |
+| Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ |
+| NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | |
+| | | | |
+| BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ |
+| DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | |
+| NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | |
+| | | | |
+| BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ |
+| DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | |
+| NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | |
+| | | | |
+| BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | |
+| DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | |
+| NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ |
+| | | | |
+| BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | |
+| Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ |
+| NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | |
+| | | | |
+| BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | |
+| DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ |
+| NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | |
+
+### iojs 1.8.1
+
+| Method | Operations | Accuracy | Sampled | Fastest |
+|:-------|:-----------|:---------|:--------|:-------:|
+| BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | |
+| Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | |
+| NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ |
+| | | | |
+| BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | |
+| Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | |
+| NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | |
+| Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | |
+| NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ |
+| | | | |
+| BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | |
+| Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ |
+| NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | |
+| | | | |
+| BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | |
+| Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | |
+| NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ |
+| | | | |
+| BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | |
+| Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ |
+| NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | |
+| | | | |
+| BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ |
+| DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | |
+| NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | |
+| | | | |
+| BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ |
+| DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | |
+| NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | |
+| | | | |
+| BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | |
+| DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | |
+| NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ |
+| | | | |
+| BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | |
+| Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | |
+| NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ |
+| | | | |
+| BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | |
+| DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ |
+| NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | |
+| | | | |
+
+## Testing the project
+
+First, install the project:
+
+ npm install
+
+Then, to run tests in Node.js, run:
+
+ npm run test-node
+
+To test locally in a browser, you can run:
+
+ npm run test-browser-local
+
+This will print out a URL that you can then open in a browser to run the tests, using [Zuul](https://github.com/defunctzombie/zuul).
+
+To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run:
+
+ npm test
+
+This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `.zuul.yml` file.
+
+## JavaScript Standard Style
+
+This module uses [JavaScript Standard Style](https://github.com/feross/standard).
+
+[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
+
+To test that the code conforms to the style, `npm install` and run:
+
+ ./node_modules/.bin/standard
+
+## credit
+
+This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify).
+
+
+## license
+
+MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis.
diff --git a/node_modules/buffer/bin/download-node-tests.js b/node_modules/buffer/bin/download-node-tests.js
new file mode 100755
index 0000000..97efde0
--- /dev/null
+++ b/node_modules/buffer/bin/download-node-tests.js
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+
+var concat = require('concat-stream')
+var cp = require('child_process')
+var fs = require('fs')
+var hyperquest = require('hyperquest')
+var path = require('path')
+var split = require('split')
+var through = require('through2')
+
+var url = 'https://api.github.com/repos/nodejs/node/contents'
+var dirs = [
+ '/test/parallel',
+ '/test/pummel'
+]
+
+cp.execSync('rm -rf node/*.js', { cwd: path.join(__dirname, '../test') })
+
+var httpOpts = {
+ headers: {
+ 'User-Agent': null
+ // auth if github rate-limits you...
+ // 'Authorization': 'Basic ' + Buffer('username:password').toString('base64'),
+ }
+}
+
+dirs.forEach(function (dir) {
+ var req = hyperquest(url + dir, httpOpts)
+ req.pipe(concat(function (data) {
+ if (req.response.statusCode !== 200) {
+ throw new Error(url + dir + ': ' + data.toString())
+ }
+ downloadBufferTests(dir, JSON.parse(data))
+ }))
+})
+
+function downloadBufferTests (dir, files) {
+ files.forEach(function (file) {
+ if (!/test-buffer.*/.test(file.name)) return
+
+ if (file.name === 'test-buffer-fakes.js') {
+ // These teses only apply to node, where they're calling into C++ and need to
+ // ensure the prototype can't be faked, or else there will be a segfault.
+ return
+ }
+
+ console.log(file.download_url)
+
+ var out = path.join(__dirname, '../test/node', file.name)
+ hyperquest(file.download_url, httpOpts)
+ .pipe(split())
+ .pipe(testfixer(file.name))
+ .pipe(fs.createWriteStream(out))
+ .on('finish', function () {
+ console.log('wrote ' + file.name)
+ })
+ })
+}
+
+function testfixer (filename) {
+ var firstline = true
+
+ return through(function (line, enc, cb) {
+ line = line.toString()
+
+ if (firstline) {
+ // require buffer explicitly
+ var preamble = 'var Buffer = require(\'../../\').Buffer;\n'
+ if (/use strict/.test(line)) line += '\n' + preamble
+ else line + preamble + '\n' + line
+ firstline = false
+ }
+
+ // use `var` instead of `const`/`let`
+ line = line.replace(/(const|let) /g, 'var ')
+
+ // make `var common = require('common')` work
+ line = line.replace(/(var common = require.*)/g, 'var common = { skip: function () {} };')
+
+ // make `require('../common')` work
+ line = line.replace(/require\('\.\.\/common'\);/g, '')
+
+ // require browser buffer
+ line = line.replace(/(.*)require\('buffer'\)(.*)/g, '$1require(\'../../\')$2')
+
+ // comment out console logs
+ line = line.replace(/(.*console\..*)/g, '// $1')
+
+ // we can't reliably test typed array max-sizes in the browser
+ if (filename === 'test-buffer-big.js') {
+ line = line.replace(/(.*new Int8Array.*RangeError.*)/, '// $1')
+ line = line.replace(/(.*new ArrayBuffer.*RangeError.*)/, '// $1')
+ line = line.replace(/(.*new Float64Array.*RangeError.*)/, '// $1')
+ }
+
+ // https://github.com/nodejs/node/blob/v0.12/test/parallel/test-buffer.js#L1138
+ // unfortunately we can't run this because crypto-browserify doesn't work in old
+ // versions of ie
+ if (filename === 'test-buffer.js') {
+ line = line.replace(/^(\s*)(var crypto = require.*)/, '$1// $2')
+ line = line.replace(/(crypto.createHash.*\))/, '1 /*$1*/')
+ }
+
+ cb(null, line + '\n')
+ })
+}
diff --git a/node_modules/buffer/bin/test.js b/node_modules/buffer/bin/test.js
new file mode 100644
index 0000000..5a86f1b
--- /dev/null
+++ b/node_modules/buffer/bin/test.js
@@ -0,0 +1,41 @@
+#!/usr/bin/env node
+
+var cp = require('child_process')
+var fs = require('fs')
+var path = require('path')
+
+var shouldRunBrowserTests = !process.env.TRAVIS_PULL_REQUEST ||
+ process.env.TRAVIS_PULL_REQUEST === 'false'
+
+var node = cp.spawn('npm', ['run', 'test-node'], { stdio: 'inherit' })
+node.on('close', function (code) {
+ if (code === 0 && shouldRunBrowserTests) {
+ runBrowserTests()
+ } else {
+ process.exit(code)
+ }
+})
+
+function runBrowserTests () {
+ var zuulYmlPath = path.join(__dirname, '..', '.zuul.yml')
+
+ writeES5ZuulYml()
+ cp.spawn('npm', ['run', 'test-browser-es5'], { stdio: 'inherit' })
+ .on('close', function (code) {
+ if (code !== 0) process.exit(code)
+ writeES6ZuulYml()
+ cp.spawn('npm', ['run', 'test-browser-es6'], { stdio: 'inherit' })
+ .on('close', function (code) {
+ process.exit(code)
+ })
+ })
+
+ function writeES5ZuulYml () {
+ fs.writeFileSync(zuulYmlPath, fs.readFileSync(path.join(__dirname, 'zuul-es5.yml')))
+ }
+
+ function writeES6ZuulYml () {
+ fs.writeFileSync(zuulYmlPath, fs.readFileSync(path.join(__dirname, 'zuul-es6.yml')))
+ }
+}
+
diff --git a/node_modules/buffer/bin/update-authors.sh b/node_modules/buffer/bin/update-authors.sh
new file mode 100755
index 0000000..efcbc78
--- /dev/null
+++ b/node_modules/buffer/bin/update-authors.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+# Update AUTHORS.md based on git history.
+
+git log --reverse --format='%aN (%aE)' | perl -we '
+BEGIN {
+ %seen = (), @authors = ();
+}
+while (<>) {
+ next if $seen{$_};
+ next if /(support\@greenkeeper.io)/;
+ next if /(dcousens\@users.noreply.github.com)/;
+ next if /(cmetcalf\@appgeo.com)/;
+ $seen{$_} = push @authors, "- ", $_;
+}
+END {
+ print "# Authors\n\n";
+ print "#### Ordered by first contribution.\n\n";
+ print @authors, "\n";
+ print "#### Generated by bin/update-authors.sh.\n";
+}
+' > AUTHORS.md
diff --git a/node_modules/buffer/bin/zuul-es5.yml b/node_modules/buffer/bin/zuul-es5.yml
new file mode 100644
index 0000000..3673bcc
--- /dev/null
+++ b/node_modules/buffer/bin/zuul-es5.yml
@@ -0,0 +1,14 @@
+ui: tape
+scripts:
+ - ./test/_polyfill.js
+browsers:
+ - name: safari
+ version: latest
+ - name: ie
+ version: 8..latest
+ - name: microsoftedge
+ version: 13..latest
+ - name: android
+ version: 4.4..latest
+ - name: iphone
+ version: latest
diff --git a/node_modules/buffer/bin/zuul-es6.yml b/node_modules/buffer/bin/zuul-es6.yml
new file mode 100644
index 0000000..8054ad6
--- /dev/null
+++ b/node_modules/buffer/bin/zuul-es6.yml
@@ -0,0 +1,6 @@
+ui: tape
+browsers:
+ - name: chrome
+ version: '-1..latest'
+ - name: firefox
+ version: '-1..latest'
diff --git a/node_modules/buffer/index.js b/node_modules/buffer/index.js
new file mode 100644
index 0000000..0fcd80a
--- /dev/null
+++ b/node_modules/buffer/index.js
@@ -0,0 +1,1789 @@
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+/* eslint-disable no-proto */
+
+'use strict'
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+var isArray = require('isarray')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+
+/**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ * === true Use Uint8Array implementation (fastest)
+ * === false Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ * incorrect length in some situations.
+
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
+ ? global.TYPED_ARRAY_SUPPORT
+ : typedArraySupport()
+
+/*
+ * Export kMaxLength after typed array support is determined.
+ */
+exports.kMaxLength = kMaxLength()
+
+function typedArraySupport () {
+ try {
+ var arr = new Uint8Array(1)
+ arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
+ return arr.foo() === 42 && // typed array instances can be augmented
+ typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+ arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+ } catch (e) {
+ return false
+ }
+}
+
+function kMaxLength () {
+ return Buffer.TYPED_ARRAY_SUPPORT
+ ? 0x7fffffff
+ : 0x3fffffff
+}
+
+function createBuffer (that, length) {
+ if (kMaxLength() < length) {
+ throw new RangeError('Invalid typed array length')
+ }
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = new Uint8Array(length)
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ if (that === null) {
+ that = new Buffer(length)
+ }
+ that.length = length
+ }
+
+ return that
+}
+
+/**
+ * The Buffer constructor returns instances of `Uint8Array` that have their
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
+ * returns a single octet.
+ *
+ * The `Uint8Array` prototype remains unmodified.
+ */
+
+function Buffer (arg, encodingOrOffset, length) {
+ if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
+ return new Buffer(arg, encodingOrOffset, length)
+ }
+
+ // Common case.
+ if (typeof arg === 'number') {
+ if (typeof encodingOrOffset === 'string') {
+ throw new Error(
+ 'If encoding is specified then the first argument must be a string'
+ )
+ }
+ return allocUnsafe(this, arg)
+ }
+ return from(this, arg, encodingOrOffset, length)
+}
+
+Buffer.poolSize = 8192 // not used by this implementation
+
+// TODO: Legacy, not needed anymore. Remove in next major version.
+Buffer._augment = function (arr) {
+ arr.__proto__ = Buffer.prototype
+ return arr
+}
+
+function from (that, value, encodingOrOffset, length) {
+ if (typeof value === 'number') {
+ throw new TypeError('"value" argument must not be a number')
+ }
+
+ if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
+ return fromArrayBuffer(that, value, encodingOrOffset, length)
+ }
+
+ if (typeof value === 'string') {
+ return fromString(that, value, encodingOrOffset)
+ }
+
+ return fromObject(that, value)
+}
+
+/**
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
+ * if value is a number.
+ * Buffer.from(str[, encoding])
+ * Buffer.from(array)
+ * Buffer.from(buffer)
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
+ **/
+Buffer.from = function (value, encodingOrOffset, length) {
+ return from(null, value, encodingOrOffset, length)
+}
+
+if (Buffer.TYPED_ARRAY_SUPPORT) {
+ Buffer.prototype.__proto__ = Uint8Array.prototype
+ Buffer.__proto__ = Uint8Array
+ if (typeof Symbol !== 'undefined' && Symbol.species &&
+ Buffer[Symbol.species] === Buffer) {
+ // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true
+ })
+ }
+}
+
+function assertSize (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('"size" argument must be a number')
+ } else if (size < 0) {
+ throw new RangeError('"size" argument must not be negative')
+ }
+}
+
+function alloc (that, size, fill, encoding) {
+ assertSize(size)
+ if (size <= 0) {
+ return createBuffer(that, size)
+ }
+ if (fill !== undefined) {
+ // Only pay attention to encoding if it's a string. This
+ // prevents accidentally sending in a number that would
+ // be interpretted as a start offset.
+ return typeof encoding === 'string'
+ ? createBuffer(that, size).fill(fill, encoding)
+ : createBuffer(that, size).fill(fill)
+ }
+ return createBuffer(that, size)
+}
+
+/**
+ * Creates a new filled Buffer instance.
+ * alloc(size[, fill[, encoding]])
+ **/
+Buffer.alloc = function (size, fill, encoding) {
+ return alloc(null, size, fill, encoding)
+}
+
+function allocUnsafe (that, size) {
+ assertSize(size)
+ that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) {
+ for (var i = 0; i < size; ++i) {
+ that[i] = 0
+ }
+ }
+ return that
+}
+
+/**
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
+ * */
+Buffer.allocUnsafe = function (size) {
+ return allocUnsafe(null, size)
+}
+/**
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
+ */
+Buffer.allocUnsafeSlow = function (size) {
+ return allocUnsafe(null, size)
+}
+
+function fromString (that, string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
+ }
+
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding')
+ }
+
+ var length = byteLength(string, encoding) | 0
+ that = createBuffer(that, length)
+
+ var actual = that.write(string, encoding)
+
+ if (actual !== length) {
+ // Writing a hex string, for example, that contains invalid characters will
+ // cause everything after the first invalid character to be ignored. (e.g.
+ // 'abxxcd' will be treated as 'ab')
+ that = that.slice(0, actual)
+ }
+
+ return that
+}
+
+function fromArrayLike (that, array) {
+ var length = array.length < 0 ? 0 : checked(array.length) | 0
+ that = createBuffer(that, length)
+ for (var i = 0; i < length; i += 1) {
+ that[i] = array[i] & 255
+ }
+ return that
+}
+
+function fromArrayBuffer (that, array, byteOffset, length) {
+ array.byteLength // this throws if `array` is not a valid ArrayBuffer
+
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('\'offset\' is out of bounds')
+ }
+
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('\'length\' is out of bounds')
+ }
+
+ if (byteOffset === undefined && length === undefined) {
+ array = new Uint8Array(array)
+ } else if (length === undefined) {
+ array = new Uint8Array(array, byteOffset)
+ } else {
+ array = new Uint8Array(array, byteOffset, length)
+ }
+
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ // Return an augmented `Uint8Array` instance, for best performance
+ that = array
+ that.__proto__ = Buffer.prototype
+ } else {
+ // Fallback: Return an object instance of the Buffer class
+ that = fromArrayLike(that, array)
+ }
+ return that
+}
+
+function fromObject (that, obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ that = createBuffer(that, len)
+
+ if (that.length === 0) {
+ return that
+ }
+
+ obj.copy(that, 0, 0, len)
+ return that
+ }
+
+ if (obj) {
+ if ((typeof ArrayBuffer !== 'undefined' &&
+ obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
+ if (typeof obj.length !== 'number' || isnan(obj.length)) {
+ return createBuffer(that, 0)
+ }
+ return fromArrayLike(that, obj)
+ }
+
+ if (obj.type === 'Buffer' && isArray(obj.data)) {
+ return fromArrayLike(that, obj.data)
+ }
+ }
+
+ throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
+}
+
+function checked (length) {
+ // Note: cannot use `length < kMaxLength()` here because that fails when
+ // length is NaN (which is otherwise coerced to zero.)
+ if (length >= kMaxLength()) {
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
+ 'size: 0x' + kMaxLength().toString(16) + ' bytes')
+ }
+ return length | 0
+}
+
+function SlowBuffer (length) {
+ if (+length != length) { // eslint-disable-line eqeqeq
+ length = 0
+ }
+ return Buffer.alloc(+length)
+}
+
+Buffer.isBuffer = function isBuffer (b) {
+ return !!(b != null && b._isBuffer)
+}
+
+Buffer.compare = function compare (a, b) {
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
+ throw new TypeError('Arguments must be Buffers')
+ }
+
+ if (a === b) return 0
+
+ var x = a.length
+ var y = b.length
+
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
+ if (a[i] !== b[i]) {
+ x = a[i]
+ y = b[i]
+ break
+ }
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+Buffer.isEncoding = function isEncoding (encoding) {
+ switch (String(encoding).toLowerCase()) {
+ case 'hex':
+ case 'utf8':
+ case 'utf-8':
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ case 'base64':
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return true
+ default:
+ return false
+ }
+}
+
+Buffer.concat = function concat (list, length) {
+ if (!isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+
+ if (list.length === 0) {
+ return Buffer.alloc(0)
+ }
+
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length
+ }
+ }
+
+ var buffer = Buffer.allocUnsafe(length)
+ var pos = 0
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
+ }
+ buf.copy(buffer, pos)
+ pos += buf.length
+ }
+ return buffer
+}
+
+function byteLength (string, encoding) {
+ if (Buffer.isBuffer(string)) {
+ return string.length
+ }
+ if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
+ (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
+ return string.byteLength
+ }
+ if (typeof string !== 'string') {
+ string = '' + string
+ }
+
+ var len = string.length
+ if (len === 0) return 0
+
+ // Use a for loop to avoid recursion
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'ascii':
+ case 'latin1':
+ case 'binary':
+ return len
+ case 'utf8':
+ case 'utf-8':
+ case undefined:
+ return utf8ToBytes(string).length
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return len * 2
+ case 'hex':
+ return len >>> 1
+ case 'base64':
+ return base64ToBytes(string).length
+ default:
+ if (loweredCase) return utf8ToBytes(string).length // assume utf8
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+Buffer.byteLength = byteLength
+
+function slowToString (encoding, start, end) {
+ var loweredCase = false
+
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
+
+ // This behaves neither like String nor Uint8Array in that we set start/end
+ // to their upper/lower bounds if the value passed is out of range.
+ // undefined is handled specially as per ECMA-262 6th Edition,
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
+ if (start === undefined || start < 0) {
+ start = 0
+ }
+ // Return early if start > this.length. Done here to prevent potential uint32
+ // coercion fail below.
+ if (start > this.length) {
+ return ''
+ }
+
+ if (end === undefined || end > this.length) {
+ end = this.length
+ }
+
+ if (end <= 0) {
+ return ''
+ }
+
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+ end >>>= 0
+ start >>>= 0
+
+ if (end <= start) {
+ return ''
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end)
+
+ case 'ascii':
+ return asciiSlice(this, start, end)
+
+ case 'latin1':
+ case 'binary':
+ return latin1Slice(this, start, end)
+
+ case 'base64':
+ return base64Slice(this, start, end)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = (encoding + '').toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
+// Buffer instances.
+Buffer.prototype._isBuffer = true
+
+function swap (b, n, m) {
+ var i = b[n]
+ b[n] = b[m]
+ b[m] = i
+}
+
+Buffer.prototype.swap16 = function swap16 () {
+ var len = this.length
+ if (len % 2 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
+ }
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1)
+ }
+ return this
+}
+
+Buffer.prototype.swap32 = function swap32 () {
+ var len = this.length
+ if (len % 4 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
+ }
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3)
+ swap(this, i + 1, i + 2)
+ }
+ return this
+}
+
+Buffer.prototype.swap64 = function swap64 () {
+ var len = this.length
+ if (len % 8 !== 0) {
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
+ }
+ for (var i = 0; i < len; i += 8) {
+ swap(this, i, i + 7)
+ swap(this, i + 1, i + 6)
+ swap(this, i + 2, i + 5)
+ swap(this, i + 3, i + 4)
+ }
+ return this
+}
+
+Buffer.prototype.toString = function toString () {
+ var length = this.length | 0
+ if (length === 0) return ''
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
+ return slowToString.apply(this, arguments)
+}
+
+Buffer.prototype.equals = function equals (b) {
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+ if (this === b) return true
+ return Buffer.compare(this, b) === 0
+}
+
+Buffer.prototype.inspect = function inspect () {
+ var str = ''
+ var max = exports.INSPECT_MAX_BYTES
+ if (this.length > 0) {
+ str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
+ if (this.length > max) str += ' ... '
+ }
+ return ''
+}
+
+Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError('Argument must be a Buffer')
+ }
+
+ if (start === undefined) {
+ start = 0
+ }
+ if (end === undefined) {
+ end = target ? target.length : 0
+ }
+ if (thisStart === undefined) {
+ thisStart = 0
+ }
+ if (thisEnd === undefined) {
+ thisEnd = this.length
+ }
+
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index')
+ }
+
+ if (thisStart >= thisEnd && start >= end) {
+ return 0
+ }
+ if (thisStart >= thisEnd) {
+ return -1
+ }
+ if (start >= end) {
+ return 1
+ }
+
+ start >>>= 0
+ end >>>= 0
+ thisStart >>>= 0
+ thisEnd >>>= 0
+
+ if (this === target) return 0
+
+ var x = thisEnd - thisStart
+ var y = end - start
+ var len = Math.min(x, y)
+
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
+
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
+
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
+}
+
+// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
+// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
+//
+// Arguments:
+// - buffer - a Buffer to search
+// - val - a string, Buffer, or number
+// - byteOffset - an index into `buffer`; will be clamped to an int32
+// - encoding - an optional encoding, relevant is val is a string
+// - dir - true for indexOf, false for lastIndexOf
+function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
+ // Empty buffer means no match
+ if (buffer.length === 0) return -1
+
+ // Normalize byteOffset
+ if (typeof byteOffset === 'string') {
+ encoding = byteOffset
+ byteOffset = 0
+ } else if (byteOffset > 0x7fffffff) {
+ byteOffset = 0x7fffffff
+ } else if (byteOffset < -0x80000000) {
+ byteOffset = -0x80000000
+ }
+ byteOffset = +byteOffset // Coerce to Number.
+ if (isNaN(byteOffset)) {
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
+ byteOffset = dir ? 0 : (buffer.length - 1)
+ }
+
+ // Normalize byteOffset: negative offsets start from the end of the buffer
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset
+ if (byteOffset >= buffer.length) {
+ if (dir) return -1
+ else byteOffset = buffer.length - 1
+ } else if (byteOffset < 0) {
+ if (dir) byteOffset = 0
+ else return -1
+ }
+
+ // Normalize val
+ if (typeof val === 'string') {
+ val = Buffer.from(val, encoding)
+ }
+
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
+ if (Buffer.isBuffer(val)) {
+ // Special case: looking for empty string/buffer always fails
+ if (val.length === 0) {
+ return -1
+ }
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
+ } else if (typeof val === 'number') {
+ val = val & 0xFF // Search for a byte value [0-255]
+ if (Buffer.TYPED_ARRAY_SUPPORT &&
+ typeof Uint8Array.prototype.indexOf === 'function') {
+ if (dir) {
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
+ } else {
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
+ }
+ }
+ return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
+ }
+
+ throw new TypeError('val must be string, number or Buffer')
+}
+
+function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1
+ var arrLength = arr.length
+ var valLength = val.length
+
+ if (encoding !== undefined) {
+ encoding = String(encoding).toLowerCase()
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
+ encoding === 'utf16le' || encoding === 'utf-16le') {
+ if (arr.length < 2 || val.length < 2) {
+ return -1
+ }
+ indexSize = 2
+ arrLength /= 2
+ valLength /= 2
+ byteOffset /= 2
+ }
+ }
+
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
+
+ var i
+ if (dir) {
+ var foundIndex = -1
+ for (i = byteOffset; i < arrLength; i++) {
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
+ if (foundIndex === -1) foundIndex = i
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
+ } else {
+ if (foundIndex !== -1) i -= i - foundIndex
+ foundIndex = -1
+ }
+ }
+ } else {
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
+ for (i = byteOffset; i >= 0; i--) {
+ var found = true
+ for (var j = 0; j < valLength; j++) {
+ if (read(arr, i + j) !== read(val, j)) {
+ found = false
+ break
+ }
+ }
+ if (found) return i
+ }
+ }
+
+ return -1
+}
+
+Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1
+}
+
+Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
+}
+
+Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
+}
+
+function hexWrite (buf, string, offset, length) {
+ offset = Number(offset) || 0
+ var remaining = buf.length - offset
+ if (!length) {
+ length = remaining
+ } else {
+ length = Number(length)
+ if (length > remaining) {
+ length = remaining
+ }
+ }
+
+ // must be an even number of digits
+ var strLen = string.length
+ if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
+
+ if (length > strLen / 2) {
+ length = strLen / 2
+ }
+ for (var i = 0; i < length; ++i) {
+ var parsed = parseInt(string.substr(i * 2, 2), 16)
+ if (isNaN(parsed)) return i
+ buf[offset + i] = parsed
+ }
+ return i
+}
+
+function utf8Write (buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+function asciiWrite (buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
+}
+
+function latin1Write (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+}
+
+function base64Write (buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
+}
+
+function ucs2Write (buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+Buffer.prototype.write = function write (string, offset, length, encoding) {
+ // Buffer#write(string)
+ if (offset === undefined) {
+ encoding = 'utf8'
+ length = this.length
+ offset = 0
+ // Buffer#write(string, encoding)
+ } else if (length === undefined && typeof offset === 'string') {
+ encoding = offset
+ length = this.length
+ offset = 0
+ // Buffer#write(string, offset[, length][, encoding])
+ } else if (isFinite(offset)) {
+ offset = offset | 0
+ if (isFinite(length)) {
+ length = length | 0
+ if (encoding === undefined) encoding = 'utf8'
+ } else {
+ encoding = length
+ length = undefined
+ }
+ // legacy write(string, encoding, offset, length) - remove in v0.13
+ } else {
+ throw new Error(
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
+ )
+ }
+
+ var remaining = this.length - offset
+ if (length === undefined || length > remaining) length = remaining
+
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+ throw new RangeError('Attempt to write outside buffer bounds')
+ }
+
+ if (!encoding) encoding = 'utf8'
+
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length)
+
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length)
+
+ case 'ascii':
+ return asciiWrite(this, string, offset, length)
+
+ case 'latin1':
+ case 'binary':
+ return latin1Write(this, string, offset, length)
+
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length)
+
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length)
+
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
+ }
+}
+
+Buffer.prototype.toJSON = function toJSON () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
+ }
+}
+
+function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
+ }
+}
+
+function utf8Slice (buf, start, end) {
+ end = Math.min(buf.length, end)
+ var res = []
+
+ var i = start
+ while (i < end) {
+ var firstByte = buf[i]
+ var codePoint = null
+ var bytesPerSequence = (firstByte > 0xEF) ? 4
+ : (firstByte > 0xDF) ? 3
+ : (firstByte > 0xBF) ? 2
+ : 1
+
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint
+
+ switch (bytesPerSequence) {
+ case 1:
+ if (firstByte < 0x80) {
+ codePoint = firstByte
+ }
+ break
+ case 2:
+ secondByte = buf[i + 1]
+ if ((secondByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
+ if (tempCodePoint > 0x7F) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 3:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+ codePoint = tempCodePoint
+ }
+ }
+ break
+ case 4:
+ secondByte = buf[i + 1]
+ thirdByte = buf[i + 2]
+ fourthByte = buf[i + 3]
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+ codePoint = tempCodePoint
+ }
+ }
+ }
+ }
+
+ if (codePoint === null) {
+ // we did not generate a valid codePoint so insert a
+ // replacement char (U+FFFD) and advance only 1 byte
+ codePoint = 0xFFFD
+ bytesPerSequence = 1
+ } else if (codePoint > 0xFFFF) {
+ // encode to utf16 (surrogate pair dance)
+ codePoint -= 0x10000
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800)
+ codePoint = 0xDC00 | codePoint & 0x3FF
+ }
+
+ res.push(codePoint)
+ i += bytesPerSequence
+ }
+
+ return decodeCodePointsArray(res)
+}
+
+// Based on http://stackoverflow.com/a/22747272/680742, the browser with
+// the lowest limit is Chrome, with 0x10000 args.
+// We go 1 magnitude less, for safety
+var MAX_ARGUMENTS_LENGTH = 0x1000
+
+function decodeCodePointsArray (codePoints) {
+ var len = codePoints.length
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+ }
+
+ // Decode in chunks to avoid "call stack size exceeded".
+ var res = ''
+ var i = 0
+ while (i < len) {
+ res += String.fromCharCode.apply(
+ String,
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
+ )
+ }
+ return res
+}
+
+function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i] & 0x7F)
+ }
+ return ret
+}
+
+function latin1Slice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
+
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
+}
+
+function hexSlice (buf, start, end) {
+ var len = buf.length
+
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
+
+ var out = ''
+ for (var i = start; i < end; ++i) {
+ out += toHex(buf[i])
+ }
+ return out
+}
+
+function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
+ }
+ return res
+}
+
+Buffer.prototype.slice = function slice (start, end) {
+ var len = this.length
+ start = ~~start
+ end = end === undefined ? len : ~~end
+
+ if (start < 0) {
+ start += len
+ if (start < 0) start = 0
+ } else if (start > len) {
+ start = len
+ }
+
+ if (end < 0) {
+ end += len
+ if (end < 0) end = 0
+ } else if (end > len) {
+ end = len
+ }
+
+ if (end < start) end = start
+
+ var newBuf
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ newBuf = this.subarray(start, end)
+ newBuf.__proto__ = Buffer.prototype
+ } else {
+ var sliceLen = end - start
+ newBuf = new Buffer(sliceLen, undefined)
+ for (var i = 0; i < sliceLen; ++i) {
+ newBuf[i] = this[i + start]
+ }
+ }
+
+ return newBuf
+}
+
+/*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+function checkOffset (offset, ext, length) {
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
+}
+
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
+ }
+
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
+ }
+
+ return val
+}
+
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
+}
+
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
+}
+
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
+}
+
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
+}
+
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
+}
+
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
+ }
+ mul *= 0x80
+
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+ return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ if (!(this[offset] & 0x80)) return (this[offset])
+ return ((0xff - this[offset] + 1) * -1)
+}
+
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset] | (this[offset + 1] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ var val = this[offset + 1] | (this[offset] << 8)
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+}
+
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+}
+
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, true, 23, 4)
+}
+
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 4, this.length)
+ return ieee754.read(this, offset, false, 23, 4)
+}
+
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, true, 52, 8)
+}
+
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+ if (!noAssert) checkOffset(offset, 8, this.length)
+ return ieee754.read(this, offset, false, 52, 8)
+}
+
+function checkInt (buf, value, offset, ext, max, min) {
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+}
+
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ byteLength = byteLength | 0
+ if (!noAssert) {
+ var maxBytes = Math.pow(2, 8 * byteLength) - 1
+ checkInt(this, value, offset, byteLength, maxBytes, 0)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+function objectWriteUInt16 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
+ buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+ (littleEndian ? i : 1 - i) * 8
+ }
+}
+
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+}
+
+function objectWriteUInt32 (buf, value, offset, littleEndian) {
+ if (value < 0) value = 0xffffffff + value + 1
+ for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
+ buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+ }
+}
+
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset + 3] = (value >>> 24)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 1] = (value >>> 8)
+ this[offset] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = 0
+ var mul = 1
+ var sub = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
+ sub = 1
+ }
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) {
+ var limit = Math.pow(2, 8 * byteLength - 1)
+
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
+
+ var i = byteLength - 1
+ var mul = 1
+ var sub = 0
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
+ sub = 1
+ }
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+ }
+
+ return offset + byteLength
+}
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+ if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+ if (value < 0) value = 0xff + value + 1
+ this[offset] = (value & 0xff)
+ return offset + 1
+}
+
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ } else {
+ objectWriteUInt16(this, value, offset, true)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 8)
+ this[offset + 1] = (value & 0xff)
+ } else {
+ objectWriteUInt16(this, value, offset, false)
+ }
+ return offset + 2
+}
+
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value & 0xff)
+ this[offset + 1] = (value >>> 8)
+ this[offset + 2] = (value >>> 16)
+ this[offset + 3] = (value >>> 24)
+ } else {
+ objectWriteUInt32(this, value, offset, true)
+ }
+ return offset + 4
+}
+
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+ value = +value
+ offset = offset | 0
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+ if (value < 0) value = 0xffffffff + value + 1
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ this[offset] = (value >>> 24)
+ this[offset + 1] = (value >>> 16)
+ this[offset + 2] = (value >>> 8)
+ this[offset + 3] = (value & 0xff)
+ } else {
+ objectWriteUInt32(this, value, offset, false)
+ }
+ return offset + 4
+}
+
+function checkIEEE754 (buf, value, offset, ext, max, min) {
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
+ if (offset < 0) throw new RangeError('Index out of range')
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 23, 4)
+ return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+}
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+ if (!noAssert) {
+ checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+ }
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+ if (!start) start = 0
+ if (!end && end !== 0) end = this.length
+ if (targetStart >= target.length) targetStart = target.length
+ if (!targetStart) targetStart = 0
+ if (end > 0 && end < start) end = start
+
+ // Copy 0 bytes; we're done
+ if (end === start) return 0
+ if (target.length === 0 || this.length === 0) return 0
+
+ // Fatal error conditions
+ if (targetStart < 0) {
+ throw new RangeError('targetStart out of bounds')
+ }
+ if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
+
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
+ }
+
+ var len = end - start
+ var i
+
+ if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
+ // ascending copy from start
+ for (i = 0; i < len; ++i) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else {
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, start + len),
+ targetStart
+ )
+ }
+
+ return len
+}
+
+// Usage:
+// buffer.fill(number[, offset[, end]])
+// buffer.fill(buffer[, offset[, end]])
+// buffer.fill(string[, offset[, end]][, encoding])
+Buffer.prototype.fill = function fill (val, start, end, encoding) {
+ // Handle string cases:
+ if (typeof val === 'string') {
+ if (typeof start === 'string') {
+ encoding = start
+ start = 0
+ end = this.length
+ } else if (typeof end === 'string') {
+ encoding = end
+ end = this.length
+ }
+ if (val.length === 1) {
+ var code = val.charCodeAt(0)
+ if (code < 256) {
+ val = code
+ }
+ }
+ if (encoding !== undefined && typeof encoding !== 'string') {
+ throw new TypeError('encoding must be a string')
+ }
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
+ }
+ } else if (typeof val === 'number') {
+ val = val & 255
+ }
+
+ // Invalid ranges are not set to a default, so can range check early.
+ if (start < 0 || this.length < start || this.length < end) {
+ throw new RangeError('Out of range index')
+ }
+
+ if (end <= start) {
+ return this
+ }
+
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
+
+ if (!val) val = 0
+
+ var i
+ if (typeof val === 'number') {
+ for (i = start; i < end; ++i) {
+ this[i] = val
+ }
+ } else {
+ var bytes = Buffer.isBuffer(val)
+ ? val
+ : utf8ToBytes(new Buffer(val, encoding).toString())
+ var len = bytes.length
+ for (i = 0; i < end - start; ++i) {
+ this[i + start] = bytes[i % len]
+ }
+ }
+
+ return this
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
+
+function base64clean (str) {
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
+ str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+ // Node converts strings with length < 2 to ''
+ if (str.length < 2) return ''
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+ while (str.length % 4 !== 0) {
+ str = str + '='
+ }
+ return str
+}
+
+function stringtrim (str) {
+ if (str.trim) return str.trim()
+ return str.replace(/^\s+|\s+$/g, '')
+}
+
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
+}
+
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
+
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i)
+
+ // is surrogate component
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
+ // last char was a lead
+ if (!leadSurrogate) {
+ // no lead yet
+ if (codePoint > 0xDBFF) {
+ // unexpected trail
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ } else if (i + 1 === length) {
+ // unpaired lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ continue
+ }
+
+ // valid lead
+ leadSurrogate = codePoint
+
+ continue
+ }
+
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
+
+ // valid surrogate pair
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
+ } else if (leadSurrogate) {
+ // valid bmp char, but last char was a lead
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ }
+
+ leadSurrogate = null
+
+ // encode utf8
+ if (codePoint < 0x80) {
+ if ((units -= 1) < 0) break
+ bytes.push(codePoint)
+ } else if (codePoint < 0x800) {
+ if ((units -= 2) < 0) break
+ bytes.push(
+ codePoint >> 0x6 | 0xC0,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x10000) {
+ if ((units -= 3) < 0) break
+ bytes.push(
+ codePoint >> 0xC | 0xE0,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else if (codePoint < 0x110000) {
+ if ((units -= 4) < 0) break
+ bytes.push(
+ codePoint >> 0x12 | 0xF0,
+ codePoint >> 0xC & 0x3F | 0x80,
+ codePoint >> 0x6 & 0x3F | 0x80,
+ codePoint & 0x3F | 0x80
+ )
+ } else {
+ throw new Error('Invalid code point')
+ }
+ }
+
+ return bytes
+}
+
+function asciiToBytes (str) {
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ // Node's code seems to be doing this and not & 0x7F..
+ byteArray.push(str.charCodeAt(i) & 0xFF)
+ }
+ return byteArray
+}
+
+function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break
+
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
+ }
+
+ return byteArray
+}
+
+function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+}
+
+function blitBuffer (src, dst, offset, length) {
+ for (var i = 0; i < length; ++i) {
+ if ((i + offset >= dst.length) || (i >= src.length)) break
+ dst[i + offset] = src[i]
+ }
+ return i
+}
+
+function isnan (val) {
+ return val !== val // eslint-disable-line no-self-compare
+}
diff --git a/node_modules/buffer/package.json b/node_modules/buffer/package.json
new file mode 100644
index 0000000..186a6b1
--- /dev/null
+++ b/node_modules/buffer/package.json
@@ -0,0 +1,77 @@
+{
+ "name": "buffer",
+ "description": "Node.js Buffer API, for the browser",
+ "version": "4.9.1",
+ "author": {
+ "name": "Feross Aboukhadijeh",
+ "email": "feross@feross.org",
+ "url": "http://feross.org"
+ },
+ "bugs": {
+ "url": "https://github.com/feross/buffer/issues"
+ },
+ "contributors": [
+ "Romain Beauxis ",
+ "James Halliday "
+ ],
+ "dependencies": {
+ "base64-js": "^1.0.2",
+ "ieee754": "^1.1.4",
+ "isarray": "^1.0.0"
+ },
+ "devDependencies": {
+ "benchmark": "^2.0.0",
+ "browserify": "^13.0.0",
+ "concat-stream": "^1.4.7",
+ "hyperquest": "^2.0.0",
+ "is-buffer": "^1.1.1",
+ "is-nan": "^1.0.1",
+ "split": "^1.0.0",
+ "standard": "^7.0.0",
+ "tape": "^4.0.0",
+ "through2": "^2.0.0",
+ "zuul": "^3.0.0"
+ },
+ "homepage": "https://github.com/feross/buffer",
+ "jspm": {
+ "map": {
+ "./index.js": {
+ "node": "@node/buffer"
+ }
+ }
+ },
+ "keywords": [
+ "arraybuffer",
+ "browser",
+ "browserify",
+ "buffer",
+ "compatible",
+ "dataview",
+ "uint8array"
+ ],
+ "license": "MIT",
+ "main": "index.js",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/feross/buffer.git"
+ },
+ "scripts": {
+ "perf": "browserify --debug perf/bracket-notation.js > perf/bundle.js && open perf/index.html",
+ "perf-node": "node perf/bracket-notation.js && node perf/concat.js && node perf/copy-big.js && node perf/copy.js && node perf/new-big.js && node perf/new.js && node perf/readDoubleBE.js && node perf/readFloatBE.js && node perf/readUInt32LE.js && node perf/slice.js && node perf/writeFloatBE.js",
+ "size": "browserify -r ./ | uglifyjs -c -m | gzip | wc -c",
+ "test": "standard && node ./bin/test.js",
+ "test-browser-es5": "zuul --ui tape -- test/*.js",
+ "test-browser-es5-local": "zuul --ui tape --local -- test/*.js",
+ "test-browser-es6": "zuul --ui tape -- test/*.js test/node/*.js",
+ "test-browser-es6-local": "zuul --ui tape --local -- test/*.js test/node/*.js",
+ "test-node": "tape test/*.js test/node/*.js && OBJECT_IMPL=true tape test/*.js",
+ "update-authors": "./bin/update-authors.sh"
+ },
+ "standard": {
+ "ignore": [
+ "test/node/*.js",
+ "test/_polyfill.js",
+ "perf/*.js"
+ ]
+ }
+}
diff --git a/node_modules/buffer/test/_polyfill.js b/node_modules/buffer/test/_polyfill.js
new file mode 100644
index 0000000..61f9c18
--- /dev/null
+++ b/node_modules/buffer/test/_polyfill.js
@@ -0,0 +1,150 @@
+if (!Array.prototype.forEach) {
+
+ Array.prototype.forEach = function(callback, thisArg) {
+
+ var T, k;
+
+ if (this == null) {
+ throw new TypeError(' this is null or not defined');
+ }
+
+ // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
+ var O = Object(this);
+
+ // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
+ // 3. Let len be ToUint32(lenValue).
+ var len = O.length >>> 0;
+
+ // 4. If IsCallable(callback) is false, throw a TypeError exception.
+ // See: http://es5.github.com/#x9.11
+ if (typeof callback !== "function") {
+ throw new TypeError(callback + ' is not a function');
+ }
+
+ // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+ if (arguments.length > 1) {
+ T = thisArg;
+ }
+
+ // 6. Let k be 0
+ k = 0;
+
+ // 7. Repeat, while k < len
+ while (k < len) {
+
+ var kValue;
+
+ // a. Let Pk be ToString(k).
+ // This is implicit for LHS operands of the in operator
+ // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
+ // This step can be combined with c
+ // c. If kPresent is true, then
+ if (k in O) {
+
+ // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
+ kValue = O[k];
+
+ // ii. Call the Call internal method of callback with T as the this value and
+ // argument list containing kValue, k, and O.
+ callback.call(T, kValue, k, O);
+ }
+ // d. Increase k by 1.
+ k++;
+ }
+ // 8. return undefined
+ };
+}
+
+if (!Array.isArray) {
+ Array.isArray = function(arg) {
+ return Object.prototype.toString.call(arg) === '[object Array]';
+ };
+}
+
+if (!Array.prototype.map) {
+
+ Array.prototype.map = function(callback, thisArg) {
+
+ var T, A, k;
+
+ if (this == null) {
+ throw new TypeError(' this is null or not defined');
+ }
+
+ // 1. Let O be the result of calling ToObject passing the |this|
+ // value as the argument.
+ var O = Object(this);
+
+ // 2. Let lenValue be the result of calling the Get internal
+ // method of O with the argument "length".
+ // 3. Let len be ToUint32(lenValue).
+ var len = O.length >>> 0;
+
+ // 4. If IsCallable(callback) is false, throw a TypeError exception.
+ // See: http://es5.github.com/#x9.11
+ if (typeof callback !== 'function') {
+ throw new TypeError(callback + ' is not a function');
+ }
+
+ // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+ if (arguments.length > 1) {
+ T = thisArg;
+ }
+
+ // 6. Let A be a new array created as if by the expression new Array(len)
+ // where Array is the standard built-in constructor with that name and
+ // len is the value of len.
+ A = new Array(len);
+
+ // 7. Let k be 0
+ k = 0;
+
+ // 8. Repeat, while k < len
+ while (k < len) {
+
+ var kValue, mappedValue;
+
+ // a. Let Pk be ToString(k).
+ // This is implicit for LHS operands of the in operator
+ // b. Let kPresent be the result of calling the HasProperty internal
+ // method of O with argument Pk.
+ // This step can be combined with c
+ // c. If kPresent is true, then
+ if (k in O) {
+
+ // i. Let kValue be the result of calling the Get internal
+ // method of O with argument Pk.
+ kValue = O[k];
+
+ // ii. Let mappedValue be the result of calling the Call internal
+ // method of callback with T as the this value and argument
+ // list containing kValue, k, and O.
+ mappedValue = callback.call(T, kValue, k, O);
+
+ // iii. Call the DefineOwnProperty internal method of A with arguments
+ // Pk, Property Descriptor
+ // { Value: mappedValue,
+ // Writable: true,
+ // Enumerable: true,
+ // Configurable: true },
+ // and false.
+
+ // In browsers that support Object.defineProperty, use the following:
+ // Object.defineProperty(A, k, {
+ // value: mappedValue,
+ // writable: true,
+ // enumerable: true,
+ // configurable: true
+ // });
+
+ // For best browser support, use the following:
+ A[k] = mappedValue;
+ }
+ // d. Increase k by 1.
+ k++;
+ }
+
+ // 9. return A
+ return A;
+ };
+}
diff --git a/node_modules/buffer/test/base64.js b/node_modules/buffer/test/base64.js
new file mode 100644
index 0000000..e4ecc56
--- /dev/null
+++ b/node_modules/buffer/test/base64.js
@@ -0,0 +1,47 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('base64: ignore whitespace', function (t) {
+ var text = '\n YW9ldQ== '
+ var buf = new B(text, 'base64')
+ t.equal(buf.toString(), 'aoeu')
+ t.end()
+})
+
+test('base64: strings without padding', function (t) {
+ t.equal((new B('YW9ldQ', 'base64').toString()), 'aoeu')
+ t.end()
+})
+
+test('base64: newline in utf8 -- should not be an issue', function (t) {
+ t.equal(
+ new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK', 'base64').toString('utf8'),
+ '---\ntitle: Three dashes marks the spot\ntags:\n'
+ )
+ t.end()
+})
+
+test('base64: newline in base64 -- should get stripped', function (t) {
+ t.equal(
+ new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\nICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'),
+ '---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-'
+ )
+ t.end()
+})
+
+test('base64: tab characters in base64 - should get stripped', function (t) {
+ t.equal(
+ new B('LS0tCnRpdGxlOiBUaHJlZSBkYXNoZXMgbWFya3MgdGhlIHNwb3QKdGFnczoK\t\t\t\tICAtIHlhbWwKICAtIGZyb250LW1hdHRlcgogIC0gZGFzaGVzCmV4cGFuZWQt', 'base64').toString('utf8'),
+ '---\ntitle: Three dashes marks the spot\ntags:\n - yaml\n - front-matter\n - dashes\nexpaned-'
+ )
+ t.end()
+})
+
+test('base64: invalid non-alphanumeric characters -- should be stripped', function (t) {
+ t.equal(
+ new B('!"#$%&\'()*,.:;<=>?@[\\]^`{|}~', 'base64').toString('utf8'),
+ ''
+ )
+ t.end()
+})
diff --git a/node_modules/buffer/test/basic.js b/node_modules/buffer/test/basic.js
new file mode 100644
index 0000000..0368ed9
--- /dev/null
+++ b/node_modules/buffer/test/basic.js
@@ -0,0 +1,85 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('instanceof Buffer', function (t) {
+ var buf = new B([1, 2])
+ t.ok(buf instanceof B)
+ t.end()
+})
+
+test('convert to Uint8Array in modern browsers', function (t) {
+ if (B.TYPED_ARRAY_SUPPORT) {
+ var buf = new B([1, 2])
+ var uint8array = new Uint8Array(buf.buffer)
+ t.ok(uint8array instanceof Uint8Array)
+ t.equal(uint8array[0], 1)
+ t.equal(uint8array[1], 2)
+ } else {
+ t.pass('object impl: skipping test')
+ }
+ t.end()
+})
+
+test('indexes from a string', function (t) {
+ var buf = new B('abc')
+ t.equal(buf[0], 97)
+ t.equal(buf[1], 98)
+ t.equal(buf[2], 99)
+ t.end()
+})
+
+test('indexes from an array', function (t) {
+ var buf = new B([ 97, 98, 99 ])
+ t.equal(buf[0], 97)
+ t.equal(buf[1], 98)
+ t.equal(buf[2], 99)
+ t.end()
+})
+
+test('setting index value should modify buffer contents', function (t) {
+ var buf = new B([ 97, 98, 99 ])
+ t.equal(buf[2], 99)
+ t.equal(buf.toString(), 'abc')
+
+ buf[2] += 10
+ t.equal(buf[2], 109)
+ t.equal(buf.toString(), 'abm')
+ t.end()
+})
+
+test('storing negative number should cast to unsigned', function (t) {
+ var buf = new B(1)
+
+ if (B.TYPED_ARRAY_SUPPORT) {
+ // This does not work with the object implementation -- nothing we can do!
+ buf[0] = -3
+ t.equal(buf[0], 253)
+ }
+
+ buf = new B(1)
+ buf.writeInt8(-3, 0)
+ t.equal(buf[0], 253)
+
+ t.end()
+})
+
+test('test that memory is copied from array-like', function (t) {
+ if (B.TYPED_ARRAY_SUPPORT) {
+ var u = new Uint8Array(4)
+ var b = new B(u)
+ b[0] = 1
+ b[1] = 2
+ b[2] = 3
+ b[3] = 4
+
+ t.equal(u[0], 0)
+ t.equal(u[1], 0)
+ t.equal(u[2], 0)
+ t.equal(u[3], 0)
+ } else {
+ t.pass('object impl: skipping test')
+ }
+
+ t.end()
+})
diff --git a/node_modules/buffer/test/compare.js b/node_modules/buffer/test/compare.js
new file mode 100644
index 0000000..62b478c
--- /dev/null
+++ b/node_modules/buffer/test/compare.js
@@ -0,0 +1,59 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('buffer.compare', function (t) {
+ var b = new B(1).fill('a')
+ var c = new B(1).fill('c')
+ var d = new B(2).fill('aa')
+
+ t.equal(b.compare(c), -1)
+ t.equal(c.compare(d), 1)
+ t.equal(d.compare(b), 1)
+ t.equal(b.compare(d), -1)
+
+ // static method
+ t.equal(B.compare(b, c), -1)
+ t.equal(B.compare(c, d), 1)
+ t.equal(B.compare(d, b), 1)
+ t.equal(B.compare(b, d), -1)
+ t.end()
+})
+
+test('buffer.compare argument validation', function (t) {
+ t.throws(function () {
+ var b = new B(1)
+ B.compare(b, 'abc')
+ })
+
+ t.throws(function () {
+ var b = new B(1)
+ B.compare('abc', b)
+ })
+
+ t.throws(function () {
+ var b = new B(1)
+ b.compare('abc')
+ })
+ t.end()
+})
+
+test('buffer.equals', function (t) {
+ var b = new B(5).fill('abcdf')
+ var c = new B(5).fill('abcdf')
+ var d = new B(5).fill('abcde')
+ var e = new B(6).fill('abcdef')
+
+ t.ok(b.equals(c))
+ t.ok(!c.equals(d))
+ t.ok(!d.equals(e))
+ t.end()
+})
+
+test('buffer.equals argument validation', function (t) {
+ t.throws(function () {
+ var b = new B(1)
+ b.equals('abc')
+ })
+ t.end()
+})
diff --git a/node_modules/buffer/test/constructor.js b/node_modules/buffer/test/constructor.js
new file mode 100644
index 0000000..cec5cdc
--- /dev/null
+++ b/node_modules/buffer/test/constructor.js
@@ -0,0 +1,193 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('new buffer from array', function (t) {
+ t.equal(
+ new B([1, 2, 3]).toString(),
+ '\u0001\u0002\u0003'
+ )
+ t.end()
+})
+
+test('new buffer from array w/ negatives', function (t) {
+ t.equal(
+ new B([-1, -2, -3]).toString('hex'),
+ 'fffefd'
+ )
+ t.end()
+})
+
+test('new buffer from array with mixed signed input', function (t) {
+ t.equal(
+ new B([-255, 255, -128, 128, 512, -512, 511, -511]).toString('hex'),
+ '01ff80800000ff01'
+ )
+ t.end()
+})
+
+test('new buffer from string', function (t) {
+ t.equal(
+ new B('hey', 'utf8').toString(),
+ 'hey'
+ )
+ t.end()
+})
+
+test('new buffer from buffer', function (t) {
+ var b1 = new B('asdf')
+ var b2 = new B(b1)
+ t.equal(b1.toString('hex'), b2.toString('hex'))
+ t.end()
+})
+
+test('new buffer from ArrayBuffer', function (t) {
+ if (typeof ArrayBuffer !== 'undefined') {
+ var arraybuffer = new Uint8Array([0, 1, 2, 3]).buffer
+ var b = new B(arraybuffer)
+ t.equal(b.length, 4)
+ t.equal(b[0], 0)
+ t.equal(b[1], 1)
+ t.equal(b[2], 2)
+ t.equal(b[3], 3)
+ t.equal(b[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from ArrayBuffer, shares memory', function (t) {
+ if (Buffer.TYPED_ARRAY_SUPPORT) {
+ var u = new Uint8Array([0, 1, 2, 3])
+ var arraybuffer = u.buffer
+ var b = new B(arraybuffer)
+ t.equal(b.length, 4)
+ t.equal(b[0], 0)
+ t.equal(b[1], 1)
+ t.equal(b[2], 2)
+ t.equal(b[3], 3)
+ t.equal(b[4], undefined)
+
+ // changing the Uint8Array (and thus the ArrayBuffer), changes the Buffer
+ u[0] = 10
+ t.equal(b[0], 10)
+ u[1] = 11
+ t.equal(b[1], 11)
+ u[2] = 12
+ t.equal(b[2], 12)
+ u[3] = 13
+ t.equal(b[3], 13)
+ }
+ t.end()
+})
+
+test('new buffer from Uint8Array', function (t) {
+ if (typeof Uint8Array !== 'undefined') {
+ var b1 = new Uint8Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Uint16Array', function (t) {
+ if (typeof Uint16Array !== 'undefined') {
+ var b1 = new Uint16Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Uint32Array', function (t) {
+ if (typeof Uint32Array !== 'undefined') {
+ var b1 = new Uint32Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Int16Array', function (t) {
+ if (typeof Int16Array !== 'undefined') {
+ var b1 = new Int16Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Int32Array', function (t) {
+ if (typeof Int32Array !== 'undefined') {
+ var b1 = new Int32Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Float32Array', function (t) {
+ if (typeof Float32Array !== 'undefined') {
+ var b1 = new Float32Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from Float64Array', function (t) {
+ if (typeof Float64Array !== 'undefined') {
+ var b1 = new Float64Array([0, 1, 2, 3])
+ var b2 = new B(b1)
+ t.equal(b1.length, b2.length)
+ t.equal(b1[0], 0)
+ t.equal(b1[1], 1)
+ t.equal(b1[2], 2)
+ t.equal(b1[3], 3)
+ t.equal(b1[4], undefined)
+ }
+ t.end()
+})
+
+test('new buffer from buffer.toJSON() output', function (t) {
+ if (typeof JSON === 'undefined') {
+ // ie6, ie7 lack support
+ t.end()
+ return
+ }
+ var buf = new B('test')
+ var json = JSON.stringify(buf)
+ var obj = JSON.parse(json)
+ var copy = new B(obj)
+ t.ok(buf.equals(copy))
+ t.end()
+})
diff --git a/node_modules/buffer/test/from-string.js b/node_modules/buffer/test/from-string.js
new file mode 100644
index 0000000..e25db26
--- /dev/null
+++ b/node_modules/buffer/test/from-string.js
@@ -0,0 +1,132 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('detect utf16 surrogate pairs', function (t) {
+ var text = '\uD83D\uDE38' + '\uD83D\uDCAD' + '\uD83D\uDC4D'
+ var buf = new B(text)
+ t.equal(text, buf.toString())
+ t.end()
+})
+
+test('detect utf16 surrogate pairs over U+20000 until U+10FFFF', function (t) {
+ var text = '\uD842\uDFB7' + '\uD93D\uDCAD' + '\uDBFF\uDFFF'
+ var buf = new B(text)
+ t.equal(text, buf.toString())
+ t.end()
+})
+
+test('replace orphaned utf16 surrogate lead code point', function (t) {
+ var text = '\uD83D\uDE38' + '\uD83D' + '\uD83D\uDC4D'
+ var buf = new B(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xef, 0xbf, 0xbd, 0xf0, 0x9f, 0x91, 0x8d ]))
+ t.end()
+})
+
+test('replace orphaned utf16 surrogate trail code point', function (t) {
+ var text = '\uD83D\uDE38' + '\uDCAD' + '\uD83D\uDC4D'
+ var buf = new B(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xef, 0xbf, 0xbd, 0xf0, 0x9f, 0x91, 0x8d ]))
+ t.end()
+})
+
+test('do not write partial utf16 code units', function (t) {
+ var f = new B([0, 0, 0, 0, 0])
+ t.equal(f.length, 5)
+ var size = f.write('あいうえお', 'utf16le')
+ t.equal(size, 4)
+ t.deepEqual(f, new B([0x42, 0x30, 0x44, 0x30, 0x00]))
+ t.end()
+})
+
+test('handle partial utf16 code points when encoding to utf8 the way node does', function (t) {
+ var text = '\uD83D\uDE38' + '\uD83D\uDC4D'
+
+ var buf = new B(8)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0xf0, 0x9f, 0x91, 0x8d ]))
+
+ buf = new B(7)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00, 0x00, 0x00 ]))
+
+ buf = new B(6)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00, 0x00 ]))
+
+ buf = new B(5)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8, 0x00 ]))
+
+ buf = new B(4)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0xf0, 0x9f, 0x98, 0xb8 ]))
+
+ buf = new B(3)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x00, 0x00, 0x00 ]))
+
+ buf = new B(2)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x00, 0x00 ]))
+
+ buf = new B(1)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x00 ]))
+
+ t.end()
+})
+
+test('handle invalid utf16 code points when encoding to utf8 the way node does', function (t) {
+ var text = 'a' + '\uDE38\uD83D' + 'b'
+
+ var buf = new B(8)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd, 0x62 ]))
+
+ buf = new B(7)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0xef, 0xbf, 0xbd ]))
+
+ buf = new B(6)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0x00, 0x00 ]))
+
+ buf = new B(5)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd, 0x00 ]))
+
+ buf = new B(4)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0xef, 0xbf, 0xbd ]))
+
+ buf = new B(3)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0x00, 0x00 ]))
+
+ buf = new B(2)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61, 0x00 ]))
+
+ buf = new B(1)
+ buf.fill(0)
+ buf.write(text)
+ t.deepEqual(buf, new B([ 0x61 ]))
+
+ t.end()
+})
diff --git a/node_modules/buffer/test/is-buffer.js b/node_modules/buffer/test/is-buffer.js
new file mode 100644
index 0000000..3744b23
--- /dev/null
+++ b/node_modules/buffer/test/is-buffer.js
@@ -0,0 +1,22 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var isBuffer = require('is-buffer')
+var test = require('tape')
+
+test('is-buffer tests', function (t) {
+ t.ok(isBuffer(new B(4)), 'new Buffer(4)')
+
+ t.notOk(isBuffer(undefined), 'undefined')
+ t.notOk(isBuffer(null), 'null')
+ t.notOk(isBuffer(''), 'empty string')
+ t.notOk(isBuffer(true), 'true')
+ t.notOk(isBuffer(false), 'false')
+ t.notOk(isBuffer(0), '0')
+ t.notOk(isBuffer(1), '1')
+ t.notOk(isBuffer(1.0), '1.0')
+ t.notOk(isBuffer('string'), 'string')
+ t.notOk(isBuffer({}), '{}')
+ t.notOk(isBuffer(function foo () {}), 'function foo () {}')
+
+ t.end()
+})
diff --git a/node_modules/buffer/test/methods.js b/node_modules/buffer/test/methods.js
new file mode 100644
index 0000000..f4bd3f2
--- /dev/null
+++ b/node_modules/buffer/test/methods.js
@@ -0,0 +1,127 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('buffer.toJSON', function (t) {
+ var data = [1, 2, 3, 4]
+ t.deepEqual(
+ new B(data).toJSON(),
+ { type: 'Buffer', data: [ 1, 2, 3, 4 ] }
+ )
+ t.end()
+})
+
+test('buffer.copy', function (t) {
+ // copied from nodejs.org example
+ var buf1 = new B(26)
+ var buf2 = new B(26)
+
+ for (var i = 0; i < 26; i++) {
+ buf1[i] = i + 97 // 97 is ASCII a
+ buf2[i] = 33 // ASCII !
+ }
+
+ buf1.copy(buf2, 8, 16, 20)
+
+ t.equal(
+ buf2.toString('ascii', 0, 25),
+ '!!!!!!!!qrst!!!!!!!!!!!!!'
+ )
+ t.end()
+})
+
+test('test offset returns are correct', function (t) {
+ var b = new B(16)
+ t.equal(4, b.writeUInt32LE(0, 0))
+ t.equal(6, b.writeUInt16LE(0, 4))
+ t.equal(7, b.writeUInt8(0, 6))
+ t.equal(8, b.writeInt8(0, 7))
+ t.equal(16, b.writeDoubleLE(0, 8))
+ t.end()
+})
+
+test('concat() a varying number of buffers', function (t) {
+ var zero = []
+ var one = [ new B('asdf') ]
+ var long = []
+ for (var i = 0; i < 10; i++) {
+ long.push(new B('asdf'))
+ }
+
+ var flatZero = B.concat(zero)
+ var flatOne = B.concat(one)
+ var flatLong = B.concat(long)
+ var flatLongLen = B.concat(long, 40)
+
+ t.equal(flatZero.length, 0)
+ t.equal(flatOne.toString(), 'asdf')
+ t.deepEqual(flatOne, one[0])
+ t.equal(flatLong.toString(), (new Array(10 + 1).join('asdf')))
+ t.equal(flatLongLen.toString(), (new Array(10 + 1).join('asdf')))
+ t.end()
+})
+
+test('fill', function (t) {
+ var b = new B(10)
+ b.fill(2)
+ t.equal(b.toString('hex'), '02020202020202020202')
+ t.end()
+})
+
+test('fill (string)', function (t) {
+ var b = new B(10)
+ b.fill('abc')
+ t.equal(b.toString(), 'abcabcabca')
+ b.fill('է')
+ t.equal(b.toString(), 'էէէէէ')
+ t.end()
+})
+
+test('copy() empty buffer with sourceEnd=0', function (t) {
+ var source = new B([42])
+ var destination = new B([43])
+ source.copy(destination, 0, 0, 0)
+ t.equal(destination.readUInt8(0), 43)
+ t.end()
+})
+
+test('copy() after slice()', function (t) {
+ var source = new B(200)
+ var dest = new B(200)
+ var expected = new B(200)
+ for (var i = 0; i < 200; i++) {
+ source[i] = i
+ dest[i] = 0
+ }
+
+ source.slice(2).copy(dest)
+ source.copy(expected, 0, 2)
+ t.deepEqual(dest, expected)
+ t.end()
+})
+
+test('copy() ascending', function (t) {
+ var b = new B('abcdefghij')
+ b.copy(b, 0, 3, 10)
+ t.equal(b.toString(), 'defghijhij')
+ t.end()
+})
+
+test('copy() descending', function (t) {
+ var b = new B('abcdefghij')
+ b.copy(b, 3, 0, 7)
+ t.equal(b.toString(), 'abcabcdefg')
+ t.end()
+})
+
+test('buffer.slice sets indexes', function (t) {
+ t.equal((new B('hallo')).slice(0, 5).toString(), 'hallo')
+ t.end()
+})
+
+test('buffer.slice out of range', function (t) {
+ t.plan(2)
+ t.equal((new B('hallo')).slice(0, 10).toString(), 'hallo')
+ t.equal((new B('hallo')).slice(10, 2).toString(), '')
+ t.end()
+})
diff --git a/node_modules/buffer/test/node/test-buffer-alloc.js b/node_modules/buffer/test/node/test-buffer-alloc.js
new file mode 100644
index 0000000..b524f51
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-alloc.js
@@ -0,0 +1,1501 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+var common = { skip: function () {} };
+var assert = require('assert');
+
+var Buffer = require('../../').Buffer;
+
+// counter to ensure unique value is always copied
+var cntr = 0;
+
+var b = Buffer.allocUnsafe(1024);
+
+// console.log('b.length == %d', b.length);
+assert.strictEqual(1024, b.length);
+
+b[0] = -1;
+assert.strictEqual(b[0], 255);
+
+for (var i = 0; i < 1024; i++) {
+ b[i] = i % 256;
+}
+
+for (var i = 0; i < 1024; i++) {
+ assert.strictEqual(i % 256, b[i]);
+}
+
+var c = Buffer.allocUnsafe(512);
+// console.log('c.length == %d', c.length);
+assert.strictEqual(512, c.length);
+
+var d = Buffer.from([]);
+assert.strictEqual(0, d.length);
+
+var ui32 = new Uint32Array(4).fill(42);
+var e = Buffer.from(ui32);
+for (var [index, value] of e.entries()) {
+ assert.strictEqual(value, ui32[index]);
+}
+
+// First check Buffer#fill() works as expected.
+
+assert.throws(function() {
+ Buffer.allocUnsafe(8).fill('a', -1);
+});
+
+assert.throws(function() {
+ Buffer.allocUnsafe(8).fill('a', 0, 9);
+});
+
+// Make sure this doesn't hang indefinitely.
+Buffer.allocUnsafe(8).fill('');
+Buffer.alloc(8, '');
+
+{
+ var buf = Buffer.alloc(64, 10);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(buf[i], 10);
+
+ buf.fill(11, 0, buf.length >> 1);
+ for (var i = 0; i < buf.length >> 1; i++)
+ assert.equal(buf[i], 11);
+ for (var i = (buf.length >> 1) + 1; i < buf.length; i++)
+ assert.equal(buf[i], 10);
+
+ buf.fill('h');
+ for (var i = 0; i < buf.length; i++)
+ assert.equal('h'.charCodeAt(0), buf[i]);
+
+ buf.fill(0);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+
+ buf.fill(null);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+
+ buf.fill(1, 16, 32);
+ for (var i = 0; i < 16; i++)
+ assert.equal(0, buf[i]);
+ for (var i = 16; i < 32; i++)
+ assert.equal(1, buf[i]);
+ for (var i = 32; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+}
+
+{
+ var buf = Buffer.alloc(10, 'abc');
+ assert.equal(buf.toString(), 'abcabcabca');
+ buf.fill('է');
+ assert.equal(buf.toString(), 'էէէէէ');
+}
+
+{
+ // copy 512 bytes, from 0 to 512.
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 512);
+// console.log('copied %d bytes from b into c', copied);
+ assert.strictEqual(512, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy c into b, without specifying sourceEnd
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = c.copy(b, 0, 0);
+// console.log('copied %d bytes from c into b w/o sourceEnd', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(c[i], b[i]);
+ }
+}
+
+{
+ // copy c into b, without specifying sourceStart
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = c.copy(b, 0);
+// console.log('copied %d bytes from c into b w/o sourceStart', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(c[i], b[i]);
+ }
+}
+
+{
+ // copy longer buffer b to shorter c without targetStart
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c);
+// console.log('copied %d bytes from b into c w/o targetStart', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy starting near end of b to c
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2));
+// console.log('copied %d bytes from end of b into beginning of c', copied);
+ assert.strictEqual(Math.floor(c.length / 2), copied);
+ for (var i = 0; i < Math.floor(c.length / 2); i++) {
+ assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]);
+ }
+ for (var i = Math.floor(c.length / 2) + 1; i < c.length; i++) {
+ assert.strictEqual(c[c.length - 1], c[i]);
+ }
+}
+
+{
+ // try to copy 513 bytes, and check we don't overrun c
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 513);
+// console.log('copied %d bytes from b trying to overrun c', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy 768 bytes from b into b
+ b.fill(++cntr);
+ b.fill(++cntr, 256);
+ var copied = b.copy(b, 0, 256, 1024);
+// console.log('copied %d bytes from b into b', copied);
+ assert.strictEqual(768, copied);
+ for (var i = 0; i < b.length; i++) {
+ assert.strictEqual(cntr, b[i]);
+ }
+}
+
+// copy string longer than buffer length (failure will segfault)
+var bb = Buffer.allocUnsafe(10);
+bb.fill('hello crazy world');
+
+
+// try to copy from before the beginning of b
+assert.doesNotThrow(() => { b.copy(c, 0, 100, 10); });
+
+// copy throws at negative sourceStart
+assert.throws(function() {
+ Buffer.allocUnsafe(5).copy(Buffer.allocUnsafe(5), 0, -1);
+}, RangeError);
+
+{
+ // check sourceEnd resets to targetEnd if former is greater than the latter
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 1025);
+// console.log('copied %d bytes from b into c', copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+// throw with negative sourceEnd
+// console.log('test copy at negative sourceEnd');
+assert.throws(function() {
+ b.copy(c, 0, 0, -1);
+}, RangeError);
+
+// when sourceStart is greater than sourceEnd, zero copied
+assert.equal(b.copy(c, 0, 100, 10), 0);
+
+// when targetStart > targetLength, zero copied
+assert.equal(b.copy(c, 512, 0, 10), 0);
+
+var caught_error;
+
+// invalid encoding for Buffer.toString
+caught_error = null;
+try {
+ b.toString('invalid');
+} catch (err) {
+ caught_error = err;
+}
+assert.strictEqual('Unknown encoding: invalid', caught_error.message);
+
+// invalid encoding for Buffer.write
+caught_error = null;
+try {
+ b.write('test string', 0, 5, 'invalid');
+} catch (err) {
+ caught_error = err;
+}
+assert.strictEqual('Unknown encoding: invalid', caught_error.message);
+
+// try to create 0-length buffers
+Buffer.from('');
+Buffer.from('', 'ascii');
+Buffer.from('', 'latin1');
+Buffer.alloc(0);
+Buffer.allocUnsafe(0);
+
+// try to write a 0-length string beyond the end of b
+assert.throws(function() {
+ b.write('', 2048);
+}, RangeError);
+
+// throw when writing to negative offset
+assert.throws(function() {
+ b.write('a', -1);
+}, RangeError);
+
+// throw when writing past bounds from the pool
+assert.throws(function() {
+ b.write('a', 2048);
+}, RangeError);
+
+// throw when writing to negative offset
+assert.throws(function() {
+ b.write('a', -1);
+}, RangeError);
+
+// try to copy 0 bytes worth of data into an empty buffer
+b.copy(Buffer.alloc(0), 0, 0, 0);
+
+// try to copy 0 bytes past the end of the target buffer
+b.copy(Buffer.alloc(0), 1, 1, 1);
+b.copy(Buffer.alloc(1), 1, 1, 1);
+
+// try to copy 0 bytes from past the end of the source buffer
+b.copy(Buffer.alloc(1), 0, 2048, 2048);
+
+var rangeBuffer = Buffer.from('abc');
+
+// if start >= buffer's length, empty string will be returned
+assert.equal(rangeBuffer.toString('ascii', 3), '');
+assert.equal(rangeBuffer.toString('ascii', +Infinity), '');
+assert.equal(rangeBuffer.toString('ascii', 3.14, 3), '');
+assert.equal(rangeBuffer.toString('ascii', 'Infinity', 3), '');
+
+// if end <= 0, empty string will be returned
+assert.equal(rangeBuffer.toString('ascii', 1, 0), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -1.2), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -100), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -Infinity), '');
+
+// if start < 0, start will be taken as zero
+assert.equal(rangeBuffer.toString('ascii', -1, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', -1.99, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', -Infinity, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc');
+
+// if start is an invalid integer, start will be taken as zero
+assert.equal(rangeBuffer.toString('ascii', 'node.js', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', {}, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', [], 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', NaN, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', null, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', undefined, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', false, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '', 3), 'abc');
+
+// but, if start is an integer when coerced, then it will be coerced and used.
+assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '1', 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '3', 3), '');
+assert.equal(rangeBuffer.toString('ascii', Number(3), 3), '');
+assert.equal(rangeBuffer.toString('ascii', '3.14', 3), '');
+assert.equal(rangeBuffer.toString('ascii', '1.99', 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 1.99, 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', true, 3), 'bc');
+
+// if end > buffer's length, end will be taken as buffer's length
+assert.equal(rangeBuffer.toString('ascii', 0, 5), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, 6.99), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, Infinity), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '5'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '6.99'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, 'Infinity'), 'abc');
+
+// if end is an invalid integer, end will be taken as buffer's length
+assert.equal(rangeBuffer.toString('ascii', 0, 'node.js'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, {}), '');
+assert.equal(rangeBuffer.toString('ascii', 0, NaN), '');
+assert.equal(rangeBuffer.toString('ascii', 0, undefined), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, null), '');
+assert.equal(rangeBuffer.toString('ascii', 0, []), '');
+assert.equal(rangeBuffer.toString('ascii', 0, false), '');
+assert.equal(rangeBuffer.toString('ascii', 0, ''), '');
+
+// but, if end is an integer when coerced, then it will be coerced and used.
+assert.equal(rangeBuffer.toString('ascii', 0, '-1'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, '1'), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, '-Infinity'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, '3'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, Number(3)), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '3.14'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '1.99'), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, '-1.99'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, 1.99), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, true), 'a');
+
+// try toString() with a object as a encoding
+assert.equal(rangeBuffer.toString({toString: function() {
+ return 'ascii';
+}}), 'abc');
+
+// testing for smart defaults and ability to pass string values as offset
+var writeTest = Buffer.from('abcdes');
+writeTest.write('n', 'ascii');
+writeTest.write('o', '1', 'ascii');
+writeTest.write('d', '2', 'ascii');
+writeTest.write('e', 3, 'ascii');
+writeTest.write('j', 4, 'ascii');
+assert.equal(writeTest.toString(), 'nodejs');
+
+// ASCII slice test
+{
+ var asciiString = 'hello world';
+
+ for (var i = 0; i < asciiString.length; i++) {
+ b[i] = asciiString.charCodeAt(i);
+ }
+ var asciiSlice = b.toString('ascii', 0, asciiString.length);
+ assert.equal(asciiString, asciiSlice);
+}
+
+{
+ var asciiString = 'hello world';
+ var offset = 100;
+
+ var written = b.write(asciiString, offset, 'ascii');
+ assert.equal(asciiString.length, written);
+ var asciiSlice = b.toString('ascii', offset, offset + asciiString.length);
+ assert.equal(asciiString, asciiSlice);
+}
+
+{
+ var asciiString = 'hello world';
+ var offset = 100;
+
+ var sliceA = b.slice(offset, offset + asciiString.length);
+ var sliceB = b.slice(offset, offset + asciiString.length);
+ for (var i = 0; i < asciiString.length; i++) {
+ assert.equal(sliceA[i], sliceB[i]);
+ }
+}
+
+// UTF-8 slice test
+
+var utf8String = '¡hέlló wôrld!';
+var offset = 100;
+
+b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8');
+var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String));
+assert.equal(utf8String, utf8Slice);
+
+var written = b.write(utf8String, offset, 'utf8');
+assert.equal(Buffer.byteLength(utf8String), written);
+utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String));
+assert.equal(utf8String, utf8Slice);
+
+var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String));
+var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String));
+for (var i = 0; i < Buffer.byteLength(utf8String); i++) {
+ assert.equal(sliceA[i], sliceB[i]);
+}
+
+{
+ var slice = b.slice(100, 150);
+ assert.equal(50, slice.length);
+ for (var i = 0; i < 50; i++) {
+ assert.equal(b[100 + i], slice[i]);
+ }
+}
+
+{
+ // make sure only top level parent propagates from allocPool
+ var b = Buffer.allocUnsafe(5);
+ var c = b.slice(0, 4);
+ var d = c.slice(0, 2);
+ assert.equal(b.parent, c.parent);
+ assert.equal(b.parent, d.parent);
+}
+
+{
+ // also from a non-pooled instance
+ var b = Buffer.allocUnsafeSlow(5);
+ var c = b.slice(0, 4);
+ var d = c.slice(0, 2);
+ assert.equal(c.parent, d.parent);
+}
+
+{
+ // Bug regression test
+ var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語
+ var buffer = Buffer.allocUnsafe(32);
+ var size = buffer.write(testValue, 0, 'utf8');
+// console.log('bytes written to buffer: ' + size);
+ var slice = buffer.toString('utf8', 0, size);
+ assert.equal(slice, testValue);
+}
+
+{
+ // Test triple slice
+ var a = Buffer.allocUnsafe(8);
+ for (var i = 0; i < 8; i++) a[i] = i;
+ var b = a.slice(4, 8);
+ assert.equal(4, b[0]);
+ assert.equal(5, b[1]);
+ assert.equal(6, b[2]);
+ assert.equal(7, b[3]);
+ var c = b.slice(2, 4);
+ assert.equal(6, c[0]);
+ assert.equal(7, c[1]);
+}
+
+{
+ var d = Buffer.from([23, 42, 255]);
+ assert.equal(d.length, 3);
+ assert.equal(d[0], 23);
+ assert.equal(d[1], 42);
+ assert.equal(d[2], 255);
+ assert.deepStrictEqual(d, Buffer.from(d));
+}
+
+{
+ var e = Buffer.from('über');
+// console.error('uber: \'%s\'', e.toString());
+ assert.deepStrictEqual(e, Buffer.from([195, 188, 98, 101, 114]));
+}
+
+{
+ var f = Buffer.from('über', 'ascii');
+// console.error('f.length: %d (should be 4)', f.length);
+ assert.deepStrictEqual(f, Buffer.from([252, 98, 101, 114]));
+}
+
+['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ {
+ var f = Buffer.from('über', encoding);
+// console.error('f.length: %d (should be 8)', f.length);
+ assert.deepStrictEqual(f, Buffer.from([252, 0, 98, 0, 101, 0, 114, 0]));
+ }
+
+ {
+ var f = Buffer.from('привет', encoding);
+// console.error('f.length: %d (should be 12)', f.length);
+ assert.deepStrictEqual(f,
+ Buffer.from([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]));
+ assert.equal(f.toString(encoding), 'привет');
+ }
+
+ {
+ var f = Buffer.from([0, 0, 0, 0, 0]);
+ assert.equal(f.length, 5);
+ var size = f.write('あいうえお', encoding);
+// console.error('bytes written to buffer: %d (should be 4)', size);
+ assert.equal(size, 4);
+ assert.deepStrictEqual(f, Buffer.from([0x42, 0x30, 0x44, 0x30, 0x00]));
+ }
+});
+
+{
+ var f = Buffer.from('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D)
+ assert.equal(f.length, 4);
+ assert.deepStrictEqual(f, Buffer.from('3DD84DDC', 'hex'));
+}
+
+
+var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4};
+var g = Buffer.from(arrayIsh);
+assert.deepStrictEqual(g, Buffer.from([0, 1, 2, 3]));
+var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4};
+g = Buffer.from(strArrayIsh);
+assert.deepStrictEqual(g, Buffer.from([0, 1, 2, 3]));
+
+
+//
+// Test toString('base64')
+//
+assert.equal('TWFu', (Buffer.from('Man')).toString('base64'));
+
+{
+ // test that regular and URL-safe base64 both work
+ var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff];
+ assert.deepStrictEqual(Buffer.from('//++/++/++//', 'base64'),
+ Buffer.from(expected));
+ assert.deepStrictEqual(Buffer.from('__--_--_--__', 'base64'),
+ Buffer.from(expected));
+}
+
+{
+ // big example
+ var quote = 'Man is distinguished, not only by his reason, but by this ' +
+ 'singular passion from other animals, which is a lust ' +
+ 'of the mind, that by a perseverance of delight in the ' +
+ 'continued and indefatigable generation of knowledge, ' +
+ 'exceeds the short vehemence of any carnal pleasure.';
+ var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb' +
+ '24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlci' +
+ 'BhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQ' +
+ 'gYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu' +
+ 'dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZ' +
+ 'GdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm' +
+ '5hbCBwbGVhc3VyZS4=';
+ assert.equal(expected, (Buffer.from(quote)).toString('base64'));
+
+ var b = Buffer.allocUnsafe(1024);
+ var bytesWritten = b.write(expected, 0, 'base64');
+ assert.equal(quote.length, bytesWritten);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder ignores whitespace
+ var expectedWhite = expected.slice(0, 60) + ' \n' +
+ expected.slice(60, 120) + ' \n' +
+ expected.slice(120, 180) + ' \n' +
+ expected.slice(180, 240) + ' \n' +
+ expected.slice(240, 300) + '\n' +
+ expected.slice(300, 360) + '\n';
+ b = Buffer.allocUnsafe(1024);
+ bytesWritten = b.write(expectedWhite, 0, 'base64');
+ assert.equal(quote.length, bytesWritten);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder on the constructor works
+ // even in the presence of whitespace.
+ b = Buffer.from(expectedWhite, 'base64');
+ assert.equal(quote.length, b.length);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder ignores illegal chars
+ var expectedIllegal = expected.slice(0, 60) + ' \x80' +
+ expected.slice(60, 120) + ' \xff' +
+ expected.slice(120, 180) + ' \x00' +
+ expected.slice(180, 240) + ' \x98' +
+ expected.slice(240, 300) + '\x03' +
+ expected.slice(300, 360);
+ b = Buffer.from(expectedIllegal, 'base64');
+ assert.equal(quote.length, b.length);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+}
+
+assert.equal(Buffer.from('', 'base64').toString(), '');
+assert.equal(Buffer.from('K', 'base64').toString(), '');
+
+// multiple-of-4 with padding
+assert.equal(Buffer.from('Kg==', 'base64').toString(), '*');
+assert.equal(Buffer.from('Kio=', 'base64').toString(), '**');
+assert.equal(Buffer.from('Kioq', 'base64').toString(), '***');
+assert.equal(Buffer.from('KioqKg==', 'base64').toString(), '****');
+assert.equal(Buffer.from('KioqKio=', 'base64').toString(), '*****');
+assert.equal(Buffer.from('KioqKioq', 'base64').toString(), '******');
+assert.equal(Buffer.from('KioqKioqKg==', 'base64').toString(), '*******');
+assert.equal(Buffer.from('KioqKioqKio=', 'base64').toString(), '********');
+assert.equal(Buffer.from('KioqKioqKioq', 'base64').toString(), '*********');
+assert.equal(Buffer.from('KioqKioqKioqKg==', 'base64').toString(),
+ '**********');
+assert.equal(Buffer.from('KioqKioqKioqKio=', 'base64').toString(),
+ '***********');
+assert.equal(Buffer.from('KioqKioqKioqKioq', 'base64').toString(),
+ '************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKg==', 'base64').toString(),
+ '*************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKio=', 'base64').toString(),
+ '**************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioq', 'base64').toString(),
+ '***************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKg==', 'base64').toString(),
+ '****************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKio=', 'base64').toString(),
+ '*****************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioq', 'base64').toString(),
+ '******************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(),
+ '*******************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(),
+ '********************');
+
+// no padding, not a multiple of 4
+assert.equal(Buffer.from('Kg', 'base64').toString(), '*');
+assert.equal(Buffer.from('Kio', 'base64').toString(), '**');
+assert.equal(Buffer.from('KioqKg', 'base64').toString(), '****');
+assert.equal(Buffer.from('KioqKio', 'base64').toString(), '*****');
+assert.equal(Buffer.from('KioqKioqKg', 'base64').toString(), '*******');
+assert.equal(Buffer.from('KioqKioqKio', 'base64').toString(), '********');
+assert.equal(Buffer.from('KioqKioqKioqKg', 'base64').toString(), '**********');
+assert.equal(Buffer.from('KioqKioqKioqKio', 'base64').toString(),
+ '***********');
+assert.equal(Buffer.from('KioqKioqKioqKioqKg', 'base64').toString(),
+ '*************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKio', 'base64').toString(),
+ '**************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKg', 'base64').toString(),
+ '****************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKio', 'base64').toString(),
+ '*****************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(),
+ '*******************');
+assert.equal(Buffer.from('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(),
+ '********************');
+
+// handle padding graciously, multiple-of-4 or not
+assert.equal(
+ Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', 'base64').length,
+ 32
+);
+assert.equal(
+ Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', 'base64').length,
+ 32
+);
+assert.equal(
+ Buffer.from('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', 'base64').length,
+ 32
+);
+assert.equal(
+ Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', 'base64').length,
+ 31
+);
+assert.equal(
+ Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64').length,
+ 31
+);
+assert.equal(
+ Buffer.from('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length,
+ 31
+);
+
+// This string encodes single '.' character in UTF-16
+var dot = Buffer.from('//4uAA==', 'base64');
+assert.equal(dot[0], 0xff);
+assert.equal(dot[1], 0xfe);
+assert.equal(dot[2], 0x2e);
+assert.equal(dot[3], 0x00);
+assert.equal(dot.toString('base64'), '//4uAA==');
+
+{
+ // Writing base64 at a position > 0 should not mangle the result.
+ //
+ // https://github.com/joyent/node/issues/402
+ var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh'];
+ var b = Buffer.allocUnsafe(64);
+ var pos = 0;
+
+ for (var i = 0; i < segments.length; ++i) {
+ pos += b.write(segments[i], pos, 'base64');
+ }
+ assert.equal(b.toString('latin1', 0, pos), 'Madness?! This is node.js!');
+}
+
+// Regression test for https://github.com/nodejs/node/issues/3496.
+// assert.equal(Buffer.from('=bad'.repeat(1e4), 'base64').length, 0);
+
+{
+ // Creating buffers larger than pool size.
+ var l = Buffer.poolSize + 5;
+ var s = '';
+ for (var i = 0; i < l; i++) {
+ s += 'h';
+ }
+
+ var b = Buffer.from(s);
+
+ for (var i = 0; i < l; i++) {
+ assert.equal('h'.charCodeAt(0), b[i]);
+ }
+
+ var sb = b.toString();
+ assert.equal(sb.length, s.length);
+ assert.equal(sb, s);
+}
+
+{
+ // Single argument slice
+ var b = Buffer.from('abcde');
+ assert.equal('bcde', b.slice(1).toString());
+}
+
+// slice(0,0).length === 0
+assert.equal(0, Buffer.from('hello').slice(0, 0).length);
+
+// test hex toString
+// console.log('Create hex string from buffer');
+var hexb = Buffer.allocUnsafe(256);
+for (var i = 0; i < 256; i++) {
+ hexb[i] = i;
+}
+var hexStr = hexb.toString('hex');
+assert.equal(hexStr,
+ '000102030405060708090a0b0c0d0e0f' +
+ '101112131415161718191a1b1c1d1e1f' +
+ '202122232425262728292a2b2c2d2e2f' +
+ '303132333435363738393a3b3c3d3e3f' +
+ '404142434445464748494a4b4c4d4e4f' +
+ '505152535455565758595a5b5c5d5e5f' +
+ '606162636465666768696a6b6c6d6e6f' +
+ '707172737475767778797a7b7c7d7e7f' +
+ '808182838485868788898a8b8c8d8e8f' +
+ '909192939495969798999a9b9c9d9e9f' +
+ 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' +
+ 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' +
+ 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' +
+ 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' +
+ 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' +
+ 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff');
+
+// console.log('Create buffer from hex string');
+var hexb2 = Buffer.from(hexStr, 'hex');
+for (var i = 0; i < 256; i++) {
+ assert.equal(hexb2[i], hexb[i]);
+}
+
+{
+ // test an invalid slice end.
+// console.log('Try to slice off the end of the buffer');
+ var b = Buffer.from([1, 2, 3, 4, 5]);
+ var b2 = b.toString('hex', 1, 10000);
+ var b3 = b.toString('hex', 1, 5);
+ var b4 = b.toString('hex', 1);
+ assert.equal(b2, b3);
+ assert.equal(b2, b4);
+}
+
+function buildBuffer(data) {
+ if (Array.isArray(data)) {
+ var buffer = Buffer.allocUnsafe(data.length);
+ data.forEach(function(v, k) {
+ buffer[k] = v;
+ });
+ return buffer;
+ }
+ return null;
+}
+
+var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]);
+
+// console.log(x.inspect());
+assert.equal('', x.inspect());
+
+{
+ var z = x.slice(4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(5, z.length);
+ assert.equal(0x6f, z[0]);
+ assert.equal(0xa3, z[1]);
+ assert.equal(0x62, z[2]);
+ assert.equal(0x61, z[3]);
+ assert.equal(0x72, z[4]);
+}
+
+{
+ var z = x.slice(0);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(z.length, x.length);
+}
+
+{
+ var z = x.slice(0, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(4, z.length);
+ assert.equal(0x81, z[0]);
+ assert.equal(0xa3, z[1]);
+}
+
+{
+ var z = x.slice(0, 9);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(9, z.length);
+}
+
+{
+ var z = x.slice(1, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(3, z.length);
+ assert.equal(0xa3, z[0]);
+}
+
+{
+ var z = x.slice(2, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(2, z.length);
+ assert.equal(0x66, z[0]);
+ assert.equal(0x6f, z[1]);
+}
+
+assert.equal(0, Buffer.from('hello').slice(0, 0).length);
+
+['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ var b = Buffer.allocUnsafe(10);
+ b.write('あいうえお', encoding);
+ assert.equal(b.toString(encoding), 'あいうえお');
+});
+
+{
+ // Binary encoding should write only one byte per character.
+ var b = Buffer.from([0xde, 0xad, 0xbe, 0xef]);
+ var s = String.fromCharCode(0xffff);
+ b.write(s, 0, 'latin1');
+ assert.equal(0xff, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+ s = String.fromCharCode(0xaaee);
+ b.write(s, 0, 'latin1');
+ assert.equal(0xee, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+}
+
+{
+ // #1210 Test UTF-8 string includes null character
+ var buf = Buffer.from('\0');
+ assert.equal(buf.length, 1);
+ buf = Buffer.from('\0\0');
+ assert.equal(buf.length, 2);
+}
+
+{
+ var buf = Buffer.allocUnsafe(2);
+ var written = buf.write(''); // 0byte
+ assert.equal(written, 0);
+ written = buf.write('\0'); // 1byte (v8 adds null terminator)
+ assert.equal(written, 1);
+ written = buf.write('a\0'); // 1byte * 2
+ assert.equal(written, 2);
+ written = buf.write('あ'); // 3bytes
+ assert.equal(written, 0);
+ written = buf.write('\0あ'); // 1byte + 3bytes
+ assert.equal(written, 1);
+ written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes
+ assert.equal(written, 2);
+}
+
+{
+ var buf = Buffer.allocUnsafe(10);
+ written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator)
+ assert.equal(written, 9);
+ written = buf.write('あいう\0'); // 3bytes * 3 + 1byte
+ assert.equal(written, 10);
+}
+
+{
+ // #243 Test write() with maxLength
+ var buf = Buffer.allocUnsafe(4);
+ buf.fill(0xFF);
+ var written = buf.write('abcd', 1, 2, 'utf8');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0xFF);
+
+ buf.fill(0xFF);
+ written = buf.write('abcd', 1, 4);
+// console.log(buf);
+ assert.equal(written, 3);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0x63);
+
+ buf.fill(0xFF);
+ written = buf.write('abcd', 1, 2, 'utf8');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0xFF);
+
+ buf.fill(0xFF);
+ written = buf.write('abcdef', 1, 2, 'hex');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0xAB);
+ assert.equal(buf[2], 0xCD);
+ assert.equal(buf[3], 0xFF);
+
+ ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ buf.fill(0xFF);
+ written = buf.write('abcd', 0, 2, encoding);
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0x61);
+ assert.equal(buf[1], 0x00);
+ assert.equal(buf[2], 0xFF);
+ assert.equal(buf[3], 0xFF);
+ });
+}
+
+{
+ // test offset returns are correct
+ var b = Buffer.allocUnsafe(16);
+ assert.equal(4, b.writeUInt32LE(0, 0));
+ assert.equal(6, b.writeUInt16LE(0, 4));
+ assert.equal(7, b.writeUInt8(0, 6));
+ assert.equal(8, b.writeInt8(0, 7));
+ assert.equal(16, b.writeDoubleLE(0, 8));
+}
+
+{
+ // test unmatched surrogates not producing invalid utf8 output
+ // ef bf bd = utf-8 representation of unicode replacement character
+ // see https://codereview.chromium.org/121173009/
+ var buf = Buffer.from('ab\ud800cd', 'utf8');
+ assert.equal(buf[0], 0x61);
+ assert.equal(buf[1], 0x62);
+ assert.equal(buf[2], 0xef);
+ assert.equal(buf[3], 0xbf);
+ assert.equal(buf[4], 0xbd);
+ assert.equal(buf[5], 0x63);
+ assert.equal(buf[6], 0x64);
+}
+
+{
+ // test for buffer overrun
+ var buf = Buffer.from([0, 0, 0, 0, 0]); // length: 5
+ var sub = buf.slice(0, 4); // length: 4
+ written = sub.write('12345', 'latin1');
+ assert.equal(written, 4);
+ assert.equal(buf[4], 0);
+}
+
+// Check for fractional length args, junk length args, etc.
+// https://github.com/joyent/node/issues/1758
+
+// Call .fill() first, stops valgrind warning about uninitialized memory reads.
+Buffer.allocUnsafe(3.3).fill().toString();
+ // throws bad argument error in commit 43cb4ec
+Buffer.alloc(3.3).fill().toString();
+assert.equal(Buffer.allocUnsafe(NaN).length, 0);
+assert.equal(Buffer.allocUnsafe(3.3).length, 3);
+assert.equal(Buffer.from({length: 3.3}).length, 3);
+assert.equal(Buffer.from({length: 'BAM'}).length, 0);
+
+// Make sure that strings are not coerced to numbers.
+assert.equal(Buffer.from('99').length, 2);
+assert.equal(Buffer.from('13.37').length, 5);
+
+// Ensure that the length argument is respected.
+'ascii utf8 hex base64 latin1'.split(' ').forEach(function(enc) {
+ assert.equal(Buffer.allocUnsafe(1).write('aaaaaa', 0, 1, enc), 1);
+});
+
+{
+ // Regression test, guard against buffer overrun in the base64 decoder.
+ var a = Buffer.allocUnsafe(3);
+ var b = Buffer.from('xxx');
+ a.write('aaaaaaaa', 'base64');
+ assert.equal(b.toString(), 'xxx');
+}
+
+// issue GH-3416
+Buffer.from(Buffer.allocUnsafe(0), 0, 0);
+
+[ 'hex',
+ 'utf8',
+ 'utf-8',
+ 'ascii',
+ 'latin1',
+ 'binary',
+ 'base64',
+ 'ucs2',
+ 'ucs-2',
+ 'utf16le',
+ 'utf-16le' ].forEach(function(enc) {
+ assert.equal(Buffer.isEncoding(enc), true);
+ });
+
+[ 'utf9',
+ 'utf-7',
+ 'Unicode-FTW',
+ 'new gnu gun',
+ false,
+ NaN,
+ {},
+ Infinity,
+ [],
+ 1,
+ 0,
+ -1 ].forEach(function(enc) {
+ assert.equal(Buffer.isEncoding(enc), false);
+ });
+
+
+// GH-5110
+{
+ var buffer = Buffer.from('test');
+ var string = JSON.stringify(buffer);
+
+ assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}');
+
+ assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) {
+ return value && value.type === 'Buffer'
+ ? Buffer.from(value.data)
+ : value;
+ }));
+}
+
+// issue GH-7849
+{
+ var buf = Buffer.from('test');
+ var json = JSON.stringify(buf);
+ var obj = JSON.parse(json);
+ var copy = Buffer.from(obj);
+
+ assert(buf.equals(copy));
+}
+
+// issue GH-4331
+assert.throws(function() {
+ Buffer.allocUnsafe(0xFFFFFFFF);
+}, RangeError);
+assert.throws(function() {
+ Buffer.allocUnsafe(0xFFFFFFFFF);
+}, RangeError);
+
+
+// attempt to overflow buffers, similar to previous bug in array buffers
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.readFloatLE(0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.writeFloatLE(0.0, 0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.readFloatLE(0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.writeFloatLE(0.0, 0xffffffff);
+}, RangeError);
+
+
+// ensure negative values can't get past offset
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.readFloatLE(-1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.writeFloatLE(0.0, -1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.readFloatLE(-1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer.allocUnsafe(8);
+ buf.writeFloatLE(0.0, -1);
+}, RangeError);
+
+// offset checks
+{
+ var buf = Buffer.allocUnsafe(0);
+
+ assert.throws(function() { buf.readUInt8(0); }, RangeError);
+ assert.throws(function() { buf.readInt8(0); }, RangeError);
+}
+
+{
+ var buf = Buffer.from([0xFF]);
+
+ assert.equal(buf.readUInt8(0), 255);
+ assert.equal(buf.readInt8(0), -1);
+}
+
+[16, 32].forEach(function(bits) {
+ var buf = Buffer.allocUnsafe(bits / 8 - 1);
+
+ assert.throws(function() { buf['readUInt' + bits + 'BE'](0); },
+ RangeError,
+ 'readUInt' + bits + 'BE');
+
+ assert.throws(function() { buf['readUInt' + bits + 'LE'](0); },
+ RangeError,
+ 'readUInt' + bits + 'LE');
+
+ assert.throws(function() { buf['readInt' + bits + 'BE'](0); },
+ RangeError,
+ 'readInt' + bits + 'BE()');
+
+ assert.throws(function() { buf['readInt' + bits + 'LE'](0); },
+ RangeError,
+ 'readInt' + bits + 'LE()');
+});
+
+[16, 32].forEach(function(bits) {
+ var buf = Buffer.from([0xFF, 0xFF, 0xFF, 0xFF]);
+
+ assert.equal(buf['readUInt' + bits + 'BE'](0),
+ (0xFFFFFFFF >>> (32 - bits)));
+
+ assert.equal(buf['readUInt' + bits + 'LE'](0),
+ (0xFFFFFFFF >>> (32 - bits)));
+
+ assert.equal(buf['readInt' + bits + 'BE'](0),
+ (0xFFFFFFFF >> (32 - bits)));
+
+ assert.equal(buf['readInt' + bits + 'LE'](0),
+ (0xFFFFFFFF >> (32 - bits)));
+});
+
+// test for common read(U)IntLE/BE
+{
+ var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
+
+ assert.strictEqual(buf.readUIntLE(0, 1), 0x01);
+ assert.strictEqual(buf.readUIntBE(0, 1), 0x01);
+ assert.strictEqual(buf.readUIntLE(0, 3), 0x030201);
+ assert.strictEqual(buf.readUIntBE(0, 3), 0x010203);
+ assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201);
+ assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405);
+ assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201);
+ assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506);
+ assert.strictEqual(buf.readIntLE(0, 1), 0x01);
+ assert.strictEqual(buf.readIntBE(0, 1), 0x01);
+ assert.strictEqual(buf.readIntLE(0, 3), 0x030201);
+ assert.strictEqual(buf.readIntBE(0, 3), 0x010203);
+ assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201);
+ assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405);
+ assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201);
+ assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506);
+}
+
+// test for common write(U)IntLE/BE
+{
+ var buf = Buffer.allocUnsafe(3);
+ buf.writeUIntLE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
+ assert.equal(buf.readUIntLE(0, 3), 0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeUIntBE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
+ assert.equal(buf.readUIntBE(0, 3), 0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntLE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
+ assert.equal(buf.readIntLE(0, 3), 0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntBE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
+ assert.equal(buf.readIntBE(0, 3), 0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntLE(-0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]);
+ assert.equal(buf.readIntLE(0, 3), -0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntBE(-0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]);
+ assert.equal(buf.readIntBE(0, 3), -0x123456);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntLE(-0x123400, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]);
+ assert.equal(buf.readIntLE(0, 3), -0x123400);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntBE(-0x123400, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]);
+ assert.equal(buf.readIntBE(0, 3), -0x123400);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntLE(-0x120000, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0x00, 0xee]);
+ assert.equal(buf.readIntLE(0, 3), -0x120000);
+
+ buf = Buffer.allocUnsafe(3);
+ buf.writeIntBE(-0x120000, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xee, 0x00, 0x00]);
+ assert.equal(buf.readIntBE(0, 3), -0x120000);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeUIntLE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
+ assert.equal(buf.readUIntLE(0, 5), 0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeUIntBE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
+ assert.equal(buf.readUIntBE(0, 5), 0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntLE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
+ assert.equal(buf.readIntLE(0, 5), 0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntBE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
+ assert.equal(buf.readIntBE(0, 5), 0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntLE(-0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]);
+ assert.equal(buf.readIntLE(0, 5), -0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntBE(-0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]);
+ assert.equal(buf.readIntBE(0, 5), -0x1234567890);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntLE(-0x0012000000, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]);
+ assert.equal(buf.readIntLE(0, 5), -0x0012000000);
+
+ buf = Buffer.allocUnsafe(5);
+ buf.writeIntBE(-0x0012000000, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]);
+ assert.equal(buf.readIntBE(0, 5), -0x0012000000);
+}
+
+// test Buffer slice
+{
+ var buf = Buffer.from('0123456789');
+ assert.equal(buf.slice(-10, 10), '0123456789');
+ assert.equal(buf.slice(-20, 10), '0123456789');
+ assert.equal(buf.slice(-20, -10), '');
+ assert.equal(buf.slice(), '0123456789');
+ assert.equal(buf.slice(0), '0123456789');
+ assert.equal(buf.slice(0, 0), '');
+ assert.equal(buf.slice(undefined), '0123456789');
+ assert.equal(buf.slice('foobar'), '0123456789');
+ assert.equal(buf.slice(undefined, undefined), '0123456789');
+
+ assert.equal(buf.slice(2), '23456789');
+ assert.equal(buf.slice(5), '56789');
+ assert.equal(buf.slice(10), '');
+ assert.equal(buf.slice(5, 8), '567');
+ assert.equal(buf.slice(8, -1), '8');
+ assert.equal(buf.slice(-10), '0123456789');
+ assert.equal(buf.slice(0, -9), '0');
+ assert.equal(buf.slice(0, -10), '');
+ assert.equal(buf.slice(0, -1), '012345678');
+ assert.equal(buf.slice(2, -2), '234567');
+ assert.equal(buf.slice(0, 65536), '0123456789');
+ assert.equal(buf.slice(65536, 0), '');
+ assert.equal(buf.slice(-5, -8), '');
+ assert.equal(buf.slice(-5, -3), '56');
+ assert.equal(buf.slice(-10, 10), '0123456789');
+ for (var i = 0, s = buf.toString(); i < buf.length; ++i) {
+ assert.equal(buf.slice(i), s.slice(i));
+ assert.equal(buf.slice(0, i), s.slice(0, i));
+ assert.equal(buf.slice(-i), s.slice(-i));
+ assert.equal(buf.slice(0, -i), s.slice(0, -i));
+ }
+
+ var utf16Buf = Buffer.from('0123456789', 'utf16le');
+ // assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le'));
+
+ assert.equal(buf.slice('0', '1'), '0');
+ assert.equal(buf.slice('-5', '10'), '56789');
+ assert.equal(buf.slice('-10', '10'), '0123456789');
+ assert.equal(buf.slice('-10', '-5'), '01234');
+ assert.equal(buf.slice('-10', '-0'), '');
+ assert.equal(buf.slice('111'), '');
+ assert.equal(buf.slice('0', '-111'), '');
+
+ // try to slice a zero length Buffer
+ // see https://github.com/joyent/node/issues/5881
+ Buffer.alloc(0).slice(0, 1);
+}
+
+// Regression test for #5482: should throw but not assert in C++ land.
+assert.throws(function() {
+ Buffer.from('', 'buffer');
+}, TypeError);
+
+// Regression test for #6111. Constructing a buffer from another buffer
+// should a) work, and b) not corrupt the source buffer.
+{
+ var a = [0];
+ for (var i = 0; i < 7; ++i) a = a.concat(a);
+ a = a.map(function(_, i) { return i; });
+ var b = Buffer.from(a);
+ var c = Buffer.from(b);
+ assert.strictEqual(b.length, a.length);
+ assert.strictEqual(c.length, a.length);
+ for (var i = 0, k = a.length; i < k; ++i) {
+ assert.strictEqual(a[i], i);
+ assert.strictEqual(b[i], i);
+ assert.strictEqual(c[i], i);
+ }
+}
+
+
+assert.throws(function() {
+ Buffer.allocUnsafe((-1 >>> 0) + 1);
+}, RangeError);
+
+assert.throws(function() {
+ Buffer.allocUnsafeSlow((-1 >>> 0) + 1);
+}, RangeError);
+
+if (common.hasCrypto) {
+ // Test truncation after decode
+ var crypto = require('crypto');
+
+ var b1 = Buffer.from('YW55=======', 'base64');
+ var b2 = Buffer.from('YW55', 'base64');
+
+ assert.equal(
+ crypto.createHash('sha1').update(b1).digest('hex'),
+ crypto.createHash('sha1').update(b2).digest('hex')
+ );
+} else {
+ common.skip('missing crypto');
+}
+
+// Test Compare
+{
+ var b = Buffer.alloc(1, 'a');
+ var c = Buffer.alloc(1, 'c');
+ var d = Buffer.alloc(2, 'aa');
+
+ assert.equal(b.compare(c), -1);
+ assert.equal(c.compare(d), 1);
+ assert.equal(d.compare(b), 1);
+ assert.equal(b.compare(d), -1);
+ assert.equal(b.compare(b), 0);
+
+ assert.equal(Buffer.compare(b, c), -1);
+ assert.equal(Buffer.compare(c, d), 1);
+ assert.equal(Buffer.compare(d, b), 1);
+ assert.equal(Buffer.compare(b, d), -1);
+ assert.equal(Buffer.compare(c, c), 0);
+
+ assert.equal(Buffer.compare(Buffer.alloc(0), Buffer.alloc(0)), 0);
+ assert.equal(Buffer.compare(Buffer.alloc(0), Buffer.alloc(1)), -1);
+ assert.equal(Buffer.compare(Buffer.alloc(1), Buffer.alloc(0)), 1);
+}
+
+assert.throws(function() {
+ var b = Buffer.allocUnsafe(1);
+ Buffer.compare(b, 'abc');
+});
+
+assert.throws(function() {
+ var b = Buffer.allocUnsafe(1);
+ Buffer.compare('abc', b);
+});
+
+assert.throws(function() {
+ var b = Buffer.allocUnsafe(1);
+ b.compare('abc');
+});
+
+// Test Equals
+{
+ var b = Buffer.alloc(5, 'abcdf');
+ var c = Buffer.alloc(5, 'abcdf');
+ var d = Buffer.alloc(5, 'abcde');
+ var e = Buffer.alloc(6, 'abcdef');
+
+ assert.ok(b.equals(c));
+ assert.ok(!c.equals(d));
+ assert.ok(!d.equals(e));
+ assert.ok(d.equals(d));
+}
+
+assert.throws(function() {
+ var b = Buffer.allocUnsafe(1);
+ b.equals('abc');
+});
+
+// Regression test for https://github.com/nodejs/node/issues/649.
+assert.throws(() => { Buffer.allocUnsafe(1422561062959).toString('utf8');});
+
+var ps = Buffer.poolSize;
+Buffer.poolSize = 0;
+assert.equal(Buffer.allocUnsafe(1).parent, undefined);
+Buffer.poolSize = ps;
+
+// Test Buffer.copy() segfault
+assert.throws(function() {
+ Buffer.allocUnsafe(10).copy();
+});
+
+var regErrorMsg = new RegExp('First argument must be a string, Buffer, ' +
+ 'ArrayBuffer, Array, or array-like object.');
+
+assert.throws(function() {
+ Buffer.from();
+}, regErrorMsg);
+
+assert.throws(function() {
+ Buffer.from(null);
+}, regErrorMsg);
+
+
+// Test that ParseArrayIndex handles full uint32
+assert.throws(function() {
+ Buffer.from(new ArrayBuffer(0), -1 >>> 0);
+}, /RangeError: 'offset' is out of bounds/);
+
+// ParseArrayIndex() should reject values that don't fit in a 32 bits size_t.
+assert.throws(() => {
+ var a = Buffer(1).fill(0);
+ var b = Buffer(1).fill(0);
+ a.copy(b, 0, 0x100000000, 0x100000001);
+}), /out of range index/;
+
+// Unpooled buffer (replaces SlowBuffer)
+var ubuf = Buffer.allocUnsafeSlow(10);
+assert(ubuf);
+assert(ubuf.buffer);
+assert.equal(ubuf.buffer.byteLength, 10);
+
+// Regression test
+assert.doesNotThrow(() => {
+ Buffer.from(new ArrayBuffer());
+});
+
+assert.throws(() => Buffer.alloc(-Buffer.poolSize),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer.alloc(-100),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer.allocUnsafe(-Buffer.poolSize),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer.allocUnsafe(-100),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer.allocUnsafeSlow(-Buffer.poolSize),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer.allocUnsafeSlow(-100),
+ '"size" argument must not be negative');
+
+assert.throws(() => Buffer.alloc({ valueOf: () => 1 }),
+ /"size" argument must be a number/);
+assert.throws(() => Buffer.alloc({ valueOf: () => -1 }),
+ /"size" argument must be a number/);
+
diff --git a/node_modules/buffer/test/node/test-buffer-arraybuffer.js b/node_modules/buffer/test/node/test-buffer-arraybuffer.js
new file mode 100644
index 0000000..a418752
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-arraybuffer.js
@@ -0,0 +1,112 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+var Buffer = require('../../').Buffer;
+var LENGTH = 16;
+
+var ab = new ArrayBuffer(LENGTH);
+var dv = new DataView(ab);
+var ui = new Uint8Array(ab);
+var buf = Buffer.from(ab);
+
+
+assert.ok(buf instanceof Buffer);
+// For backwards compatibility of old .parent property test that if buf is not
+// a slice then .parent should be undefined.
+assert.equal(buf.parent, undefined);
+assert.equal(buf.buffer, ab);
+assert.equal(buf.length, ab.byteLength);
+
+
+buf.fill(0xC);
+for (var i = 0; i < LENGTH; i++) {
+ assert.equal(ui[i], 0xC);
+ ui[i] = 0xF;
+ assert.equal(buf[i], 0xF);
+}
+
+buf.writeUInt32LE(0xF00, 0);
+buf.writeUInt32BE(0xB47, 4);
+buf.writeDoubleLE(3.1415, 8);
+
+assert.equal(dv.getUint32(0, true), 0xF00);
+assert.equal(dv.getUint32(4), 0xB47);
+assert.equal(dv.getFloat64(8, true), 3.1415);
+
+
+// Now test protecting users from doing stupid things
+
+assert.throws(function() {
+ function AB() { }
+ Object.setPrototypeOf(AB, ArrayBuffer);
+ Object.setPrototypeOf(AB.prototype, ArrayBuffer.prototype);
+ Buffer.from(new AB());
+}, TypeError);
+
+// write{Double,Float}{LE,BE} with noAssert should not crash, cf. #3766
+var b = Buffer.allocUnsafe(1);
+b.writeFloatLE(11.11, 0, true);
+b.writeFloatBE(11.11, 0, true);
+b.writeDoubleLE(11.11, 0, true);
+b.writeDoubleBE(11.11, 0, true);
+
+// Test the byteOffset and length arguments
+{
+ var ab = new Uint8Array(5);
+ ab[0] = 1;
+ ab[1] = 2;
+ ab[2] = 3;
+ ab[3] = 4;
+ ab[4] = 5;
+ var buf = Buffer.from(ab.buffer, 1, 3);
+ assert.equal(buf.length, 3);
+ assert.equal(buf[0], 2);
+ assert.equal(buf[1], 3);
+ assert.equal(buf[2], 4);
+ buf[0] = 9;
+ assert.equal(ab[1], 9);
+
+ assert.throws(() => Buffer.from(ab.buffer, 6), (err) => {
+ assert(err instanceof RangeError);
+ assert(/'offset' is out of bounds/.test(err.message));
+ return true;
+ });
+ assert.throws(() => Buffer.from(ab.buffer, 3, 6), (err) => {
+ assert(err instanceof RangeError);
+ assert(/'length' is out of bounds/.test(err.message));
+ return true;
+ });
+}
+
+// Test the deprecated Buffer() version also
+{
+ var ab = new Uint8Array(5);
+ ab[0] = 1;
+ ab[1] = 2;
+ ab[2] = 3;
+ ab[3] = 4;
+ ab[4] = 5;
+ var buf = Buffer(ab.buffer, 1, 3);
+ assert.equal(buf.length, 3);
+ assert.equal(buf[0], 2);
+ assert.equal(buf[1], 3);
+ assert.equal(buf[2], 4);
+ buf[0] = 9;
+ assert.equal(ab[1], 9);
+
+ assert.throws(() => Buffer(ab.buffer, 6), (err) => {
+ assert(err instanceof RangeError);
+ assert(/'offset' is out of bounds/.test(err.message));
+ return true;
+ });
+ assert.throws(() => Buffer(ab.buffer, 3, 6), (err) => {
+ assert(err instanceof RangeError);
+ assert(/'length' is out of bounds/.test(err.message));
+ return true;
+ });
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-ascii.js b/node_modules/buffer/test/node/test-buffer-ascii.js
new file mode 100644
index 0000000..4a06098
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-ascii.js
@@ -0,0 +1,28 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+// ASCII conversion in node.js simply masks off the high bits,
+// it doesn't do transliteration.
+assert.equal(Buffer.from('hérité').toString('ascii'), 'hC)ritC)');
+
+// 71 characters, 78 bytes. The ’ character is a triple-byte sequence.
+var input = 'C’est, graphiquement, la réunion d’un accent aigu ' +
+ 'et d’un accent grave.';
+
+var expected = 'Cb\u0000\u0019est, graphiquement, la rC)union ' +
+ 'db\u0000\u0019un accent aigu et db\u0000\u0019un ' +
+ 'accent grave.';
+
+var buf = Buffer.from(input);
+
+for (var i = 0; i < expected.length; ++i) {
+ assert.equal(buf.slice(i).toString('ascii'), expected.slice(i));
+
+ // Skip remainder of multi-byte sequence.
+ if (input.charCodeAt(i) > 65535) ++i;
+ if (input.charCodeAt(i) > 127) ++i;
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-bad-overload.js b/node_modules/buffer/test/node/test-buffer-bad-overload.js
new file mode 100644
index 0000000..282227d
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-bad-overload.js
@@ -0,0 +1,18 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+assert.doesNotThrow(function() {
+ Buffer.allocUnsafe(10);
+});
+
+assert.throws(function() {
+ Buffer.from(10, 'hex');
+});
+
+assert.doesNotThrow(function() {
+ Buffer.from('deadbeaf', 'hex');
+});
+
diff --git a/node_modules/buffer/test/node/test-buffer-badhex.js b/node_modules/buffer/test/node/test-buffer-badhex.js
new file mode 100644
index 0000000..fd7851d
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-badhex.js
@@ -0,0 +1,46 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+var Buffer = require('../../').Buffer;
+
+// Test hex strings and bad hex strings
+{
+ var buf1 = Buffer.alloc(4);
+ assert.strictEqual(buf1.length, 4);
+ assert.deepStrictEqual(buf1, new Buffer([0, 0, 0, 0]));
+ assert.strictEqual(buf1.write('abcdxx', 0, 'hex'), 2);
+ assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0x00, 0x00]));
+ assert.strictEqual(buf1.toString('hex'), 'abcd0000');
+ assert.strictEqual(buf1.write('abcdef01', 0, 'hex'), 4);
+ assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0xef, 0x01]));
+ assert.strictEqual(buf1.toString('hex'), 'abcdef01');
+
+ var buf2 = Buffer.from(buf1.toString('hex'), 'hex');
+ assert.strictEqual(buf1.toString('hex'), buf2.toString('hex'));
+
+ var buf3 = Buffer.alloc(5);
+ assert.strictEqual(buf3.write('abcdxx', 1, 'hex'), 2);
+ assert.strictEqual(buf3.toString('hex'), '00abcd0000');
+
+ var buf4 = Buffer.alloc(4);
+ assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
+ assert.strictEqual(buf4.write('xxabcd', 0, 'hex'), 0);
+ assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
+ assert.strictEqual(buf4.write('xxab', 1, 'hex'), 0);
+ assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0]));
+ assert.strictEqual(buf4.write('cdxxab', 0, 'hex'), 1);
+ assert.deepStrictEqual(buf4, new Buffer([0xcd, 0, 0, 0]));
+
+ var buf5 = Buffer.alloc(256);
+ for (var i = 0; i < 256; i++)
+ buf5[i] = i;
+
+ var hex = buf5.toString('hex');
+ assert.deepStrictEqual(Buffer.from(hex, 'hex'), buf5);
+
+ var badHex = hex.slice(0, 256) + 'xx' + hex.slice(256, 510);
+ assert.deepStrictEqual(Buffer.from(badHex, 'hex'), buf5.slice(0, 128));
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-bytelength.js b/node_modules/buffer/test/node/test-buffer-bytelength.js
new file mode 100644
index 0000000..8d7dc35
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-bytelength.js
@@ -0,0 +1,90 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+var Buffer = require('../../').Buffer;
+var SlowBuffer = require('../../').SlowBuffer;
+
+// coerce values to string
+assert.equal(Buffer.byteLength(32, 'latin1'), 2);
+assert.equal(Buffer.byteLength(NaN, 'utf8'), 3);
+assert.equal(Buffer.byteLength({}, 'latin1'), 15);
+assert.equal(Buffer.byteLength(), 9);
+
+var buff = new Buffer(10);
+assert(ArrayBuffer.isView(buff));
+var slowbuff = new SlowBuffer(10);
+assert(ArrayBuffer.isView(slowbuff));
+
+// buffer
+var incomplete = Buffer.from([0xe4, 0xb8, 0xad, 0xe6, 0x96]);
+assert.equal(Buffer.byteLength(incomplete), 5);
+var ascii = Buffer.from('abc');
+assert.equal(Buffer.byteLength(ascii), 3);
+
+// ArrayBuffer
+var buffer = new ArrayBuffer(8);
+assert.equal(Buffer.byteLength(buffer), 8);
+
+// TypedArray
+var int8 = new Int8Array(8);
+assert.equal(Buffer.byteLength(int8), 8);
+var uint8 = new Uint8Array(8);
+assert.equal(Buffer.byteLength(uint8), 8);
+var uintc8 = new Uint8ClampedArray(2);
+assert.equal(Buffer.byteLength(uintc8), 2);
+var int16 = new Int16Array(8);
+assert.equal(Buffer.byteLength(int16), 16);
+var uint16 = new Uint16Array(8);
+assert.equal(Buffer.byteLength(uint16), 16);
+var int32 = new Int32Array(8);
+assert.equal(Buffer.byteLength(int32), 32);
+var uint32 = new Uint32Array(8);
+assert.equal(Buffer.byteLength(uint32), 32);
+var float32 = new Float32Array(8);
+assert.equal(Buffer.byteLength(float32), 32);
+var float64 = new Float64Array(8);
+assert.equal(Buffer.byteLength(float64), 64);
+
+// DataView
+var dv = new DataView(new ArrayBuffer(2));
+assert.equal(Buffer.byteLength(dv), 2);
+
+// special case: zero length string
+assert.equal(Buffer.byteLength('', 'ascii'), 0);
+assert.equal(Buffer.byteLength('', 'HeX'), 0);
+
+// utf8
+assert.equal(Buffer.byteLength('∑éllö wørl∂!', 'utf-8'), 19);
+assert.equal(Buffer.byteLength('κλμνξο', 'utf8'), 12);
+assert.equal(Buffer.byteLength('挵挶挷挸挹', 'utf-8'), 15);
+assert.equal(Buffer.byteLength('𠝹𠱓𠱸', 'UTF8'), 12);
+// without an encoding, utf8 should be assumed
+assert.equal(Buffer.byteLength('hey there'), 9);
+assert.equal(Buffer.byteLength('𠱸挶νξ#xx :)'), 17);
+assert.equal(Buffer.byteLength('hello world', ''), 11);
+// it should also be assumed with unrecognized encoding
+assert.equal(Buffer.byteLength('hello world', 'abc'), 11);
+assert.equal(Buffer.byteLength('ßœ∑≈', 'unkn0wn enc0ding'), 10);
+
+// base64
+assert.equal(Buffer.byteLength('aGVsbG8gd29ybGQ=', 'base64'), 11);
+assert.equal(Buffer.byteLength('bm9kZS5qcyByb2NrcyE=', 'base64'), 14);
+assert.equal(Buffer.byteLength('aGkk', 'base64'), 3);
+assert.equal(Buffer.byteLength('bHNrZGZsa3NqZmtsc2xrZmFqc2RsZmtqcw==',
+ 'base64'), 25);
+// special padding
+assert.equal(Buffer.byteLength('aaa=', 'base64'), 2);
+assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3);
+
+assert.equal(Buffer.byteLength('Il était tué'), 14);
+assert.equal(Buffer.byteLength('Il était tué', 'utf8'), 14);
+assert.equal(Buffer.byteLength('Il était tué', 'ascii'), 12);
+assert.equal(Buffer.byteLength('Il était tué', 'latin1'), 12);
+assert.equal(Buffer.byteLength('Il était tué', 'binary'), 12);
+['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ assert.equal(24, Buffer.byteLength('Il était tué', encoding));
+});
+
diff --git a/node_modules/buffer/test/node/test-buffer-compare-offset.js b/node_modules/buffer/test/node/test-buffer-compare-offset.js
new file mode 100644
index 0000000..f1984ed
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-compare-offset.js
@@ -0,0 +1,66 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+var a = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
+var b = Buffer.from([5, 6, 7, 8, 9, 0, 1, 2, 3, 4]);
+
+assert.equal(-1, a.compare(b));
+
+// Equivalent to a.compare(b).
+assert.equal(-1, a.compare(b, 0));
+assert.equal(-1, a.compare(b, '0'));
+
+// Equivalent to a.compare(b).
+assert.equal(-1, a.compare(b, 0, undefined, 0));
+
+// Zero-length targer, return 1
+assert.equal(1, a.compare(b, 0, 0, 0));
+assert.equal(1, a.compare(b, '0', '0', '0'));
+
+// Equivalent to Buffer.compare(a, b.slice(6, 10))
+assert.equal(1, a.compare(b, 6, 10));
+
+// Zero-length source, return -1
+assert.equal(-1, a.compare(b, 6, 10, 0, 0));
+
+// Equivalent to Buffer.compare(a.slice(4), b.slice(0, 5))
+assert.equal(1, a.compare(b, 0, 5, 4));
+
+// Equivalent to Buffer.compare(a.slice(1), b.slice(5))
+assert.equal(1, a.compare(b, 5, undefined, 1));
+
+// Equivalent to Buffer.compare(a.slice(2), b.slice(2, 4))
+assert.equal(-1, a.compare(b, 2, 4, 2));
+
+// Equivalent to Buffer.compare(a.slice(4), b.slice(0, 7))
+assert.equal(-1, a.compare(b, 0, 7, 4));
+
+// Equivalent to Buffer.compare(a.slice(4, 6), b.slice(0, 7));
+assert.equal(-1, a.compare(b, 0, 7, 4, 6));
+
+// zero length target
+assert.equal(1, a.compare(b, 0, null));
+
+// coerces to targetEnd == 5
+assert.equal(-1, a.compare(b, 0, {valueOf: () => 5}));
+
+// zero length target
+assert.equal(1, a.compare(b, Infinity, -Infinity));
+
+// zero length target because default for targetEnd <= targetSource
+assert.equal(1, a.compare(b, '0xff'));
+
+var oor = /out of range index/;
+
+assert.throws(() => a.compare(b, 0, 100, 0), oor);
+assert.throws(() => a.compare(b, 0, 1, 0, 100), oor);
+assert.throws(() => a.compare(b, -1), oor);
+assert.throws(() => a.compare(b, 0, '0xff'), oor);
+assert.throws(() => a.compare(b, 0, Infinity), oor);
+assert.throws(() => a.compare(b, -Infinity, Infinity), oor);
+assert.throws(() => a.compare(), /Argument must be a Buffer/);
+
diff --git a/node_modules/buffer/test/node/test-buffer-concat.js b/node_modules/buffer/test/node/test-buffer-concat.js
new file mode 100644
index 0000000..c0dc4da
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-concat.js
@@ -0,0 +1,40 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+var zero = [];
+var one = [ Buffer.from('asdf') ];
+var long = [];
+for (var i = 0; i < 10; i++) long.push(Buffer.from('asdf'));
+
+var flatZero = Buffer.concat(zero);
+var flatOne = Buffer.concat(one);
+var flatLong = Buffer.concat(long);
+var flatLongLen = Buffer.concat(long, 40);
+
+assert(flatZero.length === 0);
+assert(flatOne.toString() === 'asdf');
+// A special case where concat used to return the first item,
+// if the length is one. This check is to make sure that we don't do that.
+assert(flatOne !== one[0]);
+assert(flatLong.toString() === (new Array(10 + 1).join('asdf')));
+assert(flatLongLen.toString() === (new Array(10 + 1).join('asdf')));
+
+assertWrongList();
+assertWrongList(null);
+assertWrongList(Buffer.from('hello'));
+assertWrongList([42]);
+assertWrongList(['hello', 'world']);
+assertWrongList(['hello', Buffer.from('world')]);
+
+function assertWrongList(value) {
+ assert.throws(function() {
+ Buffer.concat(value);
+ }, function(err) {
+ return err instanceof TypeError &&
+ err.message === '"list" argument must be an Array of Buffers';
+ });
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-fill.js b/node_modules/buffer/test/node/test-buffer-fill.js
new file mode 100644
index 0000000..7138094
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-fill.js
@@ -0,0 +1,272 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+var os = require('os');
+var SIZE = 28;
+
+var buf1 = Buffer.allocUnsafe(SIZE);
+var buf2 = Buffer.allocUnsafe(SIZE);
+
+
+// Default encoding
+testBufs('abc');
+testBufs('\u0222aa');
+testBufs('a\u0234b\u0235c\u0236');
+testBufs('abc', 4);
+testBufs('abc', 5);
+testBufs('abc', SIZE);
+testBufs('\u0222aa', 2);
+testBufs('\u0222aa', 8);
+testBufs('a\u0234b\u0235c\u0236', 4);
+testBufs('a\u0234b\u0235c\u0236', 12);
+testBufs('abc', 4, -1);
+testBufs('abc', 4, 1);
+testBufs('abc', 5, 1);
+testBufs('\u0222aa', 2, -1);
+testBufs('\u0222aa', 8, 1);
+testBufs('a\u0234b\u0235c\u0236', 4, -1);
+testBufs('a\u0234b\u0235c\u0236', 4, 1);
+testBufs('a\u0234b\u0235c\u0236', 12, 1);
+
+
+// UTF8
+testBufs('abc', 'utf8');
+testBufs('\u0222aa', 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 'utf8');
+testBufs('abc', 4, 'utf8');
+testBufs('abc', 5, 'utf8');
+testBufs('abc', SIZE, 'utf8');
+testBufs('\u0222aa', 2, 'utf8');
+testBufs('\u0222aa', 8, 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 4, 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 12, 'utf8');
+testBufs('abc', 4, -1, 'utf8');
+testBufs('abc', 4, 1, 'utf8');
+testBufs('abc', 5, 1, 'utf8');
+testBufs('\u0222aa', 2, -1, 'utf8');
+testBufs('\u0222aa', 8, 1, 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 4, -1, 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 4, 1, 'utf8');
+testBufs('a\u0234b\u0235c\u0236', 12, 1, 'utf8');
+assert.equal(Buffer.allocUnsafe(1).fill(0).fill('\u0222')[0], 0xc8);
+
+
+// BINARY
+testBufs('abc', 'binary');
+testBufs('\u0222aa', 'binary');
+testBufs('a\u0234b\u0235c\u0236', 'binary');
+testBufs('abc', 4, 'binary');
+testBufs('abc', 5, 'binary');
+testBufs('abc', SIZE, 'binary');
+testBufs('\u0222aa', 2, 'binary');
+testBufs('\u0222aa', 8, 'binary');
+testBufs('a\u0234b\u0235c\u0236', 4, 'binary');
+testBufs('a\u0234b\u0235c\u0236', 12, 'binary');
+testBufs('abc', 4, -1, 'binary');
+testBufs('abc', 4, 1, 'binary');
+testBufs('abc', 5, 1, 'binary');
+testBufs('\u0222aa', 2, -1, 'binary');
+testBufs('\u0222aa', 8, 1, 'binary');
+testBufs('a\u0234b\u0235c\u0236', 4, -1, 'binary');
+testBufs('a\u0234b\u0235c\u0236', 4, 1, 'binary');
+testBufs('a\u0234b\u0235c\u0236', 12, 1, 'binary');
+
+
+// LATIN1
+testBufs('abc', 'latin1');
+testBufs('\u0222aa', 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 'latin1');
+testBufs('abc', 4, 'latin1');
+testBufs('abc', 5, 'latin1');
+testBufs('abc', SIZE, 'latin1');
+testBufs('\u0222aa', 2, 'latin1');
+testBufs('\u0222aa', 8, 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 4, 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 12, 'latin1');
+testBufs('abc', 4, -1, 'latin1');
+testBufs('abc', 4, 1, 'latin1');
+testBufs('abc', 5, 1, 'latin1');
+testBufs('\u0222aa', 2, -1, 'latin1');
+testBufs('\u0222aa', 8, 1, 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 4, -1, 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 4, 1, 'latin1');
+testBufs('a\u0234b\u0235c\u0236', 12, 1, 'latin1');
+
+
+// UCS2
+testBufs('abc', 'ucs2');
+testBufs('\u0222aa', 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 'ucs2');
+testBufs('abc', 4, 'ucs2');
+testBufs('abc', SIZE, 'ucs2');
+testBufs('\u0222aa', 2, 'ucs2');
+testBufs('\u0222aa', 8, 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 4, 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 12, 'ucs2');
+testBufs('abc', 4, -1, 'ucs2');
+testBufs('abc', 4, 1, 'ucs2');
+testBufs('abc', 5, 1, 'ucs2');
+testBufs('\u0222aa', 2, -1, 'ucs2');
+testBufs('\u0222aa', 8, 1, 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 4, -1, 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 4, 1, 'ucs2');
+testBufs('a\u0234b\u0235c\u0236', 12, 1, 'ucs2');
+assert.equal(Buffer.allocUnsafe(1).fill('\u0222', 'ucs2')[0],
+ os.endianness() === 'LE' ? 0x22 : 0x02);
+
+
+// HEX
+testBufs('616263', 'hex');
+testBufs('c8a26161', 'hex');
+testBufs('61c8b462c8b563c8b6', 'hex');
+testBufs('616263', 4, 'hex');
+testBufs('616263', 5, 'hex');
+testBufs('616263', SIZE, 'hex');
+testBufs('c8a26161', 2, 'hex');
+testBufs('c8a26161', 8, 'hex');
+testBufs('61c8b462c8b563c8b6', 4, 'hex');
+testBufs('61c8b462c8b563c8b6', 12, 'hex');
+testBufs('616263', 4, -1, 'hex');
+testBufs('616263', 4, 1, 'hex');
+testBufs('616263', 5, 1, 'hex');
+testBufs('c8a26161', 2, -1, 'hex');
+testBufs('c8a26161', 8, 1, 'hex');
+testBufs('61c8b462c8b563c8b6', 4, -1, 'hex');
+testBufs('61c8b462c8b563c8b6', 4, 1, 'hex');
+testBufs('61c8b462c8b563c8b6', 12, 1, 'hex');
+// Make sure this operation doesn't go on forever
+buf1.fill('yKJh', 'hex');
+assert.throws(() => buf1.fill('\u0222', 'hex'));
+
+
+// BASE64
+testBufs('YWJj', 'ucs2');
+testBufs('yKJhYQ==', 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 'ucs2');
+testBufs('YWJj', 4, 'ucs2');
+testBufs('YWJj', SIZE, 'ucs2');
+testBufs('yKJhYQ==', 2, 'ucs2');
+testBufs('yKJhYQ==', 8, 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 4, 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 12, 'ucs2');
+testBufs('YWJj', 4, -1, 'ucs2');
+testBufs('YWJj', 4, 1, 'ucs2');
+testBufs('YWJj', 5, 1, 'ucs2');
+testBufs('yKJhYQ==', 2, -1, 'ucs2');
+testBufs('yKJhYQ==', 8, 1, 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 4, -1, 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 4, 1, 'ucs2');
+testBufs('Yci0Ysi1Y8i2', 12, 1, 'ucs2');
+
+
+// Buffer
+function deepStrictEqualValues(buf, arr) {
+ for (var [index, value] of buf.entries()) {
+ assert.deepStrictEqual(value, arr[index]);
+ }
+}
+
+
+var buf2Fill = Buffer.allocUnsafe(1).fill(2);
+deepStrictEqualValues(genBuffer(4, [buf2Fill]), [2, 2, 2, 2]);
+deepStrictEqualValues(genBuffer(4, [buf2Fill, 1]), [0, 2, 2, 2]);
+deepStrictEqualValues(genBuffer(4, [buf2Fill, 1, 3]), [0, 2, 2, 0]);
+deepStrictEqualValues(genBuffer(4, [buf2Fill, 1, 1]), [0, 0, 0, 0]);
+deepStrictEqualValues(genBuffer(4, [buf2Fill, 1, -1]), [0, 0, 0, 0]);
+var hexBufFill = Buffer.allocUnsafe(2).fill(0).fill('0102', 'hex');
+deepStrictEqualValues(genBuffer(4, [hexBufFill]), [1, 2, 1, 2]);
+deepStrictEqualValues(genBuffer(4, [hexBufFill, 1]), [0, 1, 2, 1]);
+deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, 3]), [0, 1, 2, 0]);
+deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, 1]), [0, 0, 0, 0]);
+deepStrictEqualValues(genBuffer(4, [hexBufFill, 1, -1]), [0, 0, 0, 0]);
+
+
+// Check exceptions
+assert.throws(() => buf1.fill(0, -1));
+assert.throws(() => buf1.fill(0, 0, buf1.length + 1));
+assert.throws(() => buf1.fill('', -1));
+assert.throws(() => buf1.fill('', 0, buf1.length + 1));
+assert.throws(() => buf1.fill('a', 0, buf1.length, 'node rocks!'));
+assert.throws(() => buf1.fill('a', 0, 0, NaN));
+assert.throws(() => buf1.fill('a', 0, 0, null));
+assert.throws(() => buf1.fill('a', 0, 0, 'foo'));
+
+
+function genBuffer(size, args) {
+ var b = Buffer.allocUnsafe(size);
+ return b.fill(0).fill.apply(b, args);
+}
+
+
+function bufReset() {
+ buf1.fill(0);
+ buf2.fill(0);
+}
+
+
+// This is mostly accurate. Except write() won't write partial bytes to the
+// string while fill() blindly copies bytes into memory. To account for that an
+// error will be thrown if not all the data can be written, and the SIZE has
+// been massaged to work with the input characters.
+function writeToFill(string, offset, end, encoding) {
+ if (typeof offset === 'string') {
+ encoding = offset;
+ offset = 0;
+ end = buf2.length;
+ } else if (typeof end === 'string') {
+ encoding = end;
+ end = buf2.length;
+ } else if (end === undefined) {
+ end = buf2.length;
+ }
+
+ if (offset < 0 || end > buf2.length)
+ throw new RangeError('Out of range index');
+
+ if (end <= offset)
+ return buf2;
+
+ offset >>>= 0;
+ end >>>= 0;
+ assert(offset <= buf2.length);
+
+ // Convert "end" to "length" (which write understands).
+ var length = end - offset < 0 ? 0 : end - offset;
+
+ var wasZero = false;
+ do {
+ var written = buf2.write(string, offset, length, encoding);
+ offset += written;
+ // Safety check in case write falls into infinite loop.
+ if (written === 0) {
+ if (wasZero)
+ throw new Error('Could not write all data to Buffer');
+ else
+ wasZero = true;
+ }
+ } while (offset < buf2.length);
+
+ // Correction for UCS2 operations.
+ if (os.endianness() === 'BE' && encoding === 'ucs2') {
+ for (var i = 0; i < buf2.length; i += 2) {
+ var tmp = buf2[i];
+ buf2[i] = buf2[i + 1];
+ buf2[i + 1] = tmp;
+ }
+ }
+
+ return buf2;
+}
+
+
+function testBufs(string, offset, length, encoding) {
+ bufReset();
+ buf1.fill.apply(buf1, arguments);
+ // Swap bytes on BE archs for ucs2 encoding.
+ assert.deepStrictEqual(buf1.fill.apply(buf1, arguments),
+ writeToFill.apply(null, arguments));
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-includes.js b/node_modules/buffer/test/node/test-buffer-includes.js
new file mode 100644
index 0000000..2096a34
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-includes.js
@@ -0,0 +1,305 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+var Buffer = require('../../').Buffer;
+
+var b = Buffer.from('abcdef');
+var buf_a = Buffer.from('a');
+var buf_bc = Buffer.from('bc');
+var buf_f = Buffer.from('f');
+var buf_z = Buffer.from('z');
+var buf_empty = Buffer.from('');
+
+assert(b.includes('a'));
+assert(!b.includes('a', 1));
+assert(!b.includes('a', -1));
+assert(!b.includes('a', -4));
+assert(b.includes('a', -b.length));
+assert(b.includes('a', NaN));
+assert(b.includes('a', -Infinity));
+assert(!b.includes('a', Infinity));
+assert(b.includes('bc'));
+assert(!b.includes('bc', 2));
+assert(!b.includes('bc', -1));
+assert(!b.includes('bc', -3));
+assert(b.includes('bc', -5));
+assert(b.includes('bc', NaN));
+assert(b.includes('bc', -Infinity));
+assert(!b.includes('bc', Infinity));
+assert(b.includes('f'), b.length - 1);
+assert(!b.includes('z'));
+assert(!b.includes(''));
+assert(!b.includes('', 1));
+assert(!b.includes('', b.length + 1));
+assert(!b.includes('', Infinity));
+assert(b.includes(buf_a));
+assert(!b.includes(buf_a, 1));
+assert(!b.includes(buf_a, -1));
+assert(!b.includes(buf_a, -4));
+assert(b.includes(buf_a, -b.length));
+assert(b.includes(buf_a, NaN));
+assert(b.includes(buf_a, -Infinity));
+assert(!b.includes(buf_a, Infinity));
+assert(b.includes(buf_bc));
+assert(!b.includes(buf_bc, 2));
+assert(!b.includes(buf_bc, -1));
+assert(!b.includes(buf_bc, -3));
+assert(b.includes(buf_bc, -5));
+assert(b.includes(buf_bc, NaN));
+assert(b.includes(buf_bc, -Infinity));
+assert(!b.includes(buf_bc, Infinity));
+assert(b.includes(buf_f), b.length - 1);
+assert(!b.includes(buf_z));
+assert(!b.includes(buf_empty));
+assert(!b.includes(buf_empty, 1));
+assert(!b.includes(buf_empty, b.length + 1));
+assert(!b.includes(buf_empty, Infinity));
+assert(b.includes(0x61));
+assert(!b.includes(0x61, 1));
+assert(!b.includes(0x61, -1));
+assert(!b.includes(0x61, -4));
+assert(b.includes(0x61, -b.length));
+assert(b.includes(0x61, NaN));
+assert(b.includes(0x61, -Infinity));
+assert(!b.includes(0x61, Infinity));
+assert(!b.includes(0x0));
+
+// test offsets
+assert(b.includes('d', 2));
+assert(b.includes('f', 5));
+assert(b.includes('f', -1));
+assert(!b.includes('f', 6));
+
+assert(b.includes(Buffer.from('d'), 2));
+assert(b.includes(Buffer.from('f'), 5));
+assert(b.includes(Buffer.from('f'), -1));
+assert(!b.includes(Buffer.from('f'), 6));
+
+assert(!Buffer.from('ff').includes(Buffer.from('f'), 1, 'ucs2'));
+
+// test hex encoding
+assert.strictEqual(
+ Buffer.from(b.toString('hex'), 'hex')
+ .includes('64', 0, 'hex'),
+ true
+);
+assert.strictEqual(
+ Buffer.from(b.toString('hex'), 'hex')
+ .includes(Buffer.from('64', 'hex'), 0, 'hex'),
+ true
+);
+
+// test base64 encoding
+assert.strictEqual(
+ Buffer.from(b.toString('base64'), 'base64')
+ .includes('ZA==', 0, 'base64'),
+ true
+);
+assert.strictEqual(
+ Buffer.from(b.toString('base64'), 'base64')
+ .includes(Buffer.from('ZA==', 'base64'), 0, 'base64'),
+ true
+);
+
+// test ascii encoding
+assert.strictEqual(
+ Buffer.from(b.toString('ascii'), 'ascii')
+ .includes('d', 0, 'ascii'),
+ true
+);
+assert.strictEqual(
+ Buffer.from(b.toString('ascii'), 'ascii')
+ .includes(Buffer.from('d', 'ascii'), 0, 'ascii'),
+ true
+);
+
+// test latin1 encoding
+assert.strictEqual(
+ Buffer.from(b.toString('latin1'), 'latin1')
+ .includes('d', 0, 'latin1'),
+ true
+);
+assert.strictEqual(
+ Buffer.from(b.toString('latin1'), 'latin1')
+ .includes(Buffer.from('d', 'latin1'), 0, 'latin1'),
+ true
+);
+
+// test binary encoding
+assert.strictEqual(
+ Buffer.from(b.toString('binary'), 'binary')
+ .includes('d', 0, 'binary'),
+ true
+);
+assert.strictEqual(
+ Buffer.from(b.toString('binary'), 'binary')
+ .includes(Buffer.from('d', 'binary'), 0, 'binary'),
+ true
+);
+
+
+// test usc2 encoding
+var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
+
+assert(twoByteString.includes('\u0395', 4, 'ucs2'));
+assert(twoByteString.includes('\u03a3', -4, 'ucs2'));
+assert(twoByteString.includes('\u03a3', -6, 'ucs2'));
+assert(twoByteString.includes(
+ Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2'));
+assert(!twoByteString.includes('\u03a3', -2, 'ucs2'));
+
+var mixedByteStringUcs2 =
+ Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
+assert(mixedByteStringUcs2.includes('bc', 0, 'ucs2'));
+assert(mixedByteStringUcs2.includes('\u03a3', 0, 'ucs2'));
+assert(!mixedByteStringUcs2.includes('\u0396', 0, 'ucs2'));
+
+assert(
+ 6, mixedByteStringUcs2.includes(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
+assert(
+ 10, mixedByteStringUcs2.includes(Buffer.from('\u03a3', 'ucs2'),
+ 0, 'ucs2'));
+assert(
+ -1, mixedByteStringUcs2.includes(Buffer.from('\u0396', 'ucs2'),
+ 0, 'ucs2'));
+
+twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
+
+// Test single char pattern
+assert(twoByteString.includes('\u039a', 0, 'ucs2'));
+assert(twoByteString.includes('\u0391', 0, 'ucs2'), 'Alpha');
+assert(twoByteString.includes('\u03a3', 0, 'ucs2'), 'First Sigma');
+assert(twoByteString.includes('\u03a3', 6, 'ucs2'), 'Second Sigma');
+assert(twoByteString.includes('\u0395', 0, 'ucs2'), 'Epsilon');
+assert(!twoByteString.includes('\u0392', 0, 'ucs2'), 'Not beta');
+
+// Test multi-char pattern
+assert(twoByteString.includes('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha');
+assert(twoByteString.includes('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma');
+assert(twoByteString.includes('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma');
+assert(twoByteString.includes('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
+
+var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
+assert(mixedByteStringUtf8.includes('bc'));
+assert(mixedByteStringUtf8.includes('bc', 5));
+assert(mixedByteStringUtf8.includes('bc', -8));
+assert(mixedByteStringUtf8.includes('\u03a3'));
+assert(!mixedByteStringUtf8.includes('\u0396'));
+
+
+// Test complex string includes algorithms. Only trigger for long strings.
+// Long string that isn't a simple repeat of a shorter string.
+var longString = 'A';
+for (var i = 66; i < 76; i++) { // from 'B' to 'K'
+ longString = longString + String.fromCharCode(i) + longString;
+}
+
+var longBufferString = Buffer.from(longString);
+
+// pattern of 15 chars, repeated every 16 chars in long
+var pattern = 'ABACABADABACABA';
+for (var i = 0; i < longBufferString.length - pattern.length; i += 7) {
+ var includes = longBufferString.includes(pattern, i);
+ assert(includes, 'Long ABACABA...-string at index ' + i);
+}
+assert(longBufferString.includes('AJABACA'), 'Long AJABACA, First J');
+assert(longBufferString.includes('AJABACA', 511), 'Long AJABACA, Second J');
+
+pattern = 'JABACABADABACABA';
+assert(longBufferString.includes(pattern), 'Long JABACABA..., First J');
+assert(longBufferString.includes(pattern, 512), 'Long JABACABA..., Second J');
+
+// Search for a non-ASCII string in a pure ASCII string.
+var asciiString = Buffer.from(
+ 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
+assert(!asciiString.includes('\x2061'));
+assert(asciiString.includes('leb', 0));
+
+// Search in string containing many non-ASCII chars.
+var allCodePoints = [];
+for (var i = 0; i < 65536; i++) allCodePoints[i] = i;
+var allCharsString = String.fromCharCode.apply(String, allCodePoints);
+var allCharsBufferUtf8 = Buffer.from(allCharsString);
+var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2');
+
+// Search for string long enough to trigger complex search with ASCII pattern
+// and UC16 subject.
+assert(!allCharsBufferUtf8.includes('notfound'));
+assert(!allCharsBufferUcs2.includes('notfound'));
+
+// Find substrings in Utf8.
+var lengths = [1, 3, 15]; // Single char, simple and complex.
+var indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b];
+for (var lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
+ for (var i = 0; i < indices.length; i++) {
+ var index = indices[i];
+ var length = lengths[lengthIndex];
+
+ if (index + length > 0x7F) {
+ length = 2 * length;
+ }
+
+ if (index + length > 0x7FF) {
+ length = 3 * length;
+ }
+
+ if (index + length > 0xFFFF) {
+ length = 4 * length;
+ }
+
+ var patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length);
+ assert(index, allCharsBufferUtf8.includes(patternBufferUtf8));
+
+ var patternStringUtf8 = patternBufferUtf8.toString();
+ assert(index, allCharsBufferUtf8.includes(patternStringUtf8));
+ }
+}
+
+// Find substrings in Usc2.
+lengths = [2, 4, 16]; // Single char, simple and complex.
+indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0];
+for (var lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
+ for (var i = 0; i < indices.length; i++) {
+ var index = indices[i] * 2;
+ var length = lengths[lengthIndex];
+
+ var patternBufferUcs2 =
+ allCharsBufferUcs2.slice(index, index + length);
+ assert(
+ index, allCharsBufferUcs2.includes(patternBufferUcs2, 0, 'ucs2'));
+
+ var patternStringUcs2 = patternBufferUcs2.toString('ucs2');
+ assert(
+ index, allCharsBufferUcs2.includes(patternStringUcs2, 0, 'ucs2'));
+ }
+}
+
+assert.throws(function() {
+ b.includes(function() { });
+});
+assert.throws(function() {
+ b.includes({});
+});
+assert.throws(function() {
+ b.includes([]);
+});
+
+// test truncation of Number arguments to uint8
+{
+ var buf = Buffer.from('this is a test');
+ assert.ok(buf.includes(0x6973));
+ assert.ok(buf.includes(0x697320));
+ assert.ok(buf.includes(0x69732069));
+ assert.ok(buf.includes(0x697374657374));
+ assert.ok(buf.includes(0x69737374));
+ assert.ok(buf.includes(0x69737465));
+ assert.ok(buf.includes(0x69737465));
+ assert.ok(buf.includes(-140));
+ assert.ok(buf.includes(-152));
+ assert.ok(!buf.includes(0xff));
+ assert.ok(!buf.includes(0xffff));
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-indexof.js b/node_modules/buffer/test/node/test-buffer-indexof.js
new file mode 100644
index 0000000..24502c3
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-indexof.js
@@ -0,0 +1,523 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+var Buffer = require('../../').Buffer;
+
+var b = Buffer.from('abcdef');
+var buf_a = Buffer.from('a');
+var buf_bc = Buffer.from('bc');
+var buf_f = Buffer.from('f');
+var buf_z = Buffer.from('z');
+var buf_empty = Buffer.from('');
+
+assert.equal(b.indexOf('a'), 0);
+assert.equal(b.indexOf('a', 1), -1);
+assert.equal(b.indexOf('a', -1), -1);
+assert.equal(b.indexOf('a', -4), -1);
+assert.equal(b.indexOf('a', -b.length), 0);
+assert.equal(b.indexOf('a', NaN), 0);
+assert.equal(b.indexOf('a', -Infinity), 0);
+assert.equal(b.indexOf('a', Infinity), -1);
+assert.equal(b.indexOf('bc'), 1);
+assert.equal(b.indexOf('bc', 2), -1);
+assert.equal(b.indexOf('bc', -1), -1);
+assert.equal(b.indexOf('bc', -3), -1);
+assert.equal(b.indexOf('bc', -5), 1);
+assert.equal(b.indexOf('bc', NaN), 1);
+assert.equal(b.indexOf('bc', -Infinity), 1);
+assert.equal(b.indexOf('bc', Infinity), -1);
+assert.equal(b.indexOf('f'), b.length - 1);
+assert.equal(b.indexOf('z'), -1);
+assert.equal(b.indexOf(''), -1);
+assert.equal(b.indexOf('', 1), -1);
+assert.equal(b.indexOf('', b.length + 1), -1);
+assert.equal(b.indexOf('', Infinity), -1);
+assert.equal(b.indexOf(buf_a), 0);
+assert.equal(b.indexOf(buf_a, 1), -1);
+assert.equal(b.indexOf(buf_a, -1), -1);
+assert.equal(b.indexOf(buf_a, -4), -1);
+assert.equal(b.indexOf(buf_a, -b.length), 0);
+assert.equal(b.indexOf(buf_a, NaN), 0);
+assert.equal(b.indexOf(buf_a, -Infinity), 0);
+assert.equal(b.indexOf(buf_a, Infinity), -1);
+assert.equal(b.indexOf(buf_bc), 1);
+assert.equal(b.indexOf(buf_bc, 2), -1);
+assert.equal(b.indexOf(buf_bc, -1), -1);
+assert.equal(b.indexOf(buf_bc, -3), -1);
+assert.equal(b.indexOf(buf_bc, -5), 1);
+assert.equal(b.indexOf(buf_bc, NaN), 1);
+assert.equal(b.indexOf(buf_bc, -Infinity), 1);
+assert.equal(b.indexOf(buf_bc, Infinity), -1);
+assert.equal(b.indexOf(buf_f), b.length - 1);
+assert.equal(b.indexOf(buf_z), -1);
+assert.equal(b.indexOf(buf_empty), -1);
+assert.equal(b.indexOf(buf_empty, 1), -1);
+assert.equal(b.indexOf(buf_empty, b.length + 1), -1);
+assert.equal(b.indexOf(buf_empty, Infinity), -1);
+assert.equal(b.indexOf(0x61), 0);
+assert.equal(b.indexOf(0x61, 1), -1);
+assert.equal(b.indexOf(0x61, -1), -1);
+assert.equal(b.indexOf(0x61, -4), -1);
+assert.equal(b.indexOf(0x61, -b.length), 0);
+assert.equal(b.indexOf(0x61, NaN), 0);
+assert.equal(b.indexOf(0x61, -Infinity), 0);
+assert.equal(b.indexOf(0x61, Infinity), -1);
+assert.equal(b.indexOf(0x0), -1);
+
+// test offsets
+assert.equal(b.indexOf('d', 2), 3);
+assert.equal(b.indexOf('f', 5), 5);
+assert.equal(b.indexOf('f', -1), 5);
+assert.equal(b.indexOf('f', 6), -1);
+
+assert.equal(b.indexOf(Buffer.from('d'), 2), 3);
+assert.equal(b.indexOf(Buffer.from('f'), 5), 5);
+assert.equal(b.indexOf(Buffer.from('f'), -1), 5);
+assert.equal(b.indexOf(Buffer.from('f'), 6), -1);
+
+assert.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1);
+
+// test hex encoding
+assert.strictEqual(
+ Buffer.from(b.toString('hex'), 'hex')
+ .indexOf('64', 0, 'hex'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from(b.toString('hex'), 'hex')
+ .indexOf(Buffer.from('64', 'hex'), 0, 'hex'),
+ 3
+);
+
+// test base64 encoding
+assert.strictEqual(
+ Buffer.from(b.toString('base64'), 'base64')
+ .indexOf('ZA==', 0, 'base64'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from(b.toString('base64'), 'base64')
+ .indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'),
+ 3
+);
+
+// test ascii encoding
+assert.strictEqual(
+ Buffer.from(b.toString('ascii'), 'ascii')
+ .indexOf('d', 0, 'ascii'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from(b.toString('ascii'), 'ascii')
+ .indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'),
+ 3
+);
+
+// test latin1 encoding
+assert.strictEqual(
+ Buffer.from(b.toString('latin1'), 'latin1')
+ .indexOf('d', 0, 'latin1'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from(b.toString('latin1'), 'latin1')
+ .indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from('aa\u00e8aa', 'latin1')
+ .indexOf('\u00e8', 'latin1'),
+ 2
+);
+assert.strictEqual(
+ Buffer.from('\u00e8', 'latin1')
+ .indexOf('\u00e8', 'latin1'),
+ 0
+);
+assert.strictEqual(
+ Buffer.from('\u00e8', 'latin1')
+ .indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'),
+ 0
+);
+
+// test binary encoding
+assert.strictEqual(
+ Buffer.from(b.toString('binary'), 'binary')
+ .indexOf('d', 0, 'binary'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from(b.toString('binary'), 'binary')
+ .indexOf(Buffer.from('d', 'binary'), 0, 'binary'),
+ 3
+);
+assert.strictEqual(
+ Buffer.from('aa\u00e8aa', 'binary')
+ .indexOf('\u00e8', 'binary'),
+ 2
+);
+assert.strictEqual(
+ Buffer.from('\u00e8', 'binary')
+ .indexOf('\u00e8', 'binary'),
+ 0
+);
+assert.strictEqual(
+ Buffer.from('\u00e8', 'binary')
+ .indexOf(Buffer.from('\u00e8', 'binary'), 'binary'),
+ 0
+);
+
+
+// test optional offset with passed encoding
+assert.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4);
+assert.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4);
+
+{
+ // test usc2 encoding
+ var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
+
+ assert.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2'));
+ assert.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2'));
+ assert.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2'));
+ assert.equal(4, twoByteString.indexOf(
+ Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2'));
+ assert.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2'));
+}
+
+var mixedByteStringUcs2 =
+ Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
+assert.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2'));
+assert.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2'));
+assert.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2'));
+
+assert.equal(
+ 6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
+assert.equal(
+ 10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2'));
+assert.equal(
+ -1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2'));
+
+{
+ var twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
+
+ // Test single char pattern
+ assert.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2'));
+ assert.equal(2, twoByteString.indexOf('\u0391', 0, 'ucs2'), 'Alpha');
+ assert.equal(4, twoByteString.indexOf('\u03a3', 0, 'ucs2'), 'First Sigma');
+ assert.equal(6, twoByteString.indexOf('\u03a3', 6, 'ucs2'), 'Second Sigma');
+ assert.equal(8, twoByteString.indexOf('\u0395', 0, 'ucs2'), 'Epsilon');
+ assert.equal(-1, twoByteString.indexOf('\u0392', 0, 'ucs2'), 'Not beta');
+
+ // Test multi-char pattern
+ assert.equal(
+ 0, twoByteString.indexOf('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha');
+ assert.equal(
+ 2, twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma');
+ assert.equal(
+ 4, twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma');
+ assert.equal(
+ 6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
+}
+
+var mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
+assert.equal(5, mixedByteStringUtf8.indexOf('bc'));
+assert.equal(5, mixedByteStringUtf8.indexOf('bc', 5));
+assert.equal(5, mixedByteStringUtf8.indexOf('bc', -8));
+assert.equal(7, mixedByteStringUtf8.indexOf('\u03a3'));
+assert.equal(-1, mixedByteStringUtf8.indexOf('\u0396'));
+
+
+// Test complex string indexOf algorithms. Only trigger for long strings.
+// Long string that isn't a simple repeat of a shorter string.
+var longString = 'A';
+for (var i = 66; i < 76; i++) { // from 'B' to 'K'
+ longString = longString + String.fromCharCode(i) + longString;
+}
+
+var longBufferString = Buffer.from(longString);
+
+// pattern of 15 chars, repeated every 16 chars in long
+var pattern = 'ABACABADABACABA';
+for (var i = 0; i < longBufferString.length - pattern.length; i += 7) {
+ var index = longBufferString.indexOf(pattern, i);
+ assert.equal((i + 15) & ~0xf, index, 'Long ABACABA...-string at index ' + i);
+}
+assert.equal(510, longBufferString.indexOf('AJABACA'), 'Long AJABACA, First J');
+assert.equal(
+ 1534, longBufferString.indexOf('AJABACA', 511), 'Long AJABACA, Second J');
+
+pattern = 'JABACABADABACABA';
+assert.equal(
+ 511, longBufferString.indexOf(pattern), 'Long JABACABA..., First J');
+assert.equal(
+ 1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J');
+
+// Search for a non-ASCII string in a pure ASCII string.
+var asciiString = Buffer.from(
+ 'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
+assert.equal(-1, asciiString.indexOf('\x2061'));
+assert.equal(3, asciiString.indexOf('leb', 0));
+
+// Search in string containing many non-ASCII chars.
+var allCodePoints = [];
+for (var i = 0; i < 65536; i++) allCodePoints[i] = i;
+var allCharsString = String.fromCharCode.apply(String, allCodePoints);
+var allCharsBufferUtf8 = Buffer.from(allCharsString);
+var allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2');
+
+// Search for string long enough to trigger complex search with ASCII pattern
+// and UC16 subject.
+assert.equal(-1, allCharsBufferUtf8.indexOf('notfound'));
+assert.equal(-1, allCharsBufferUcs2.indexOf('notfound'));
+
+// Needle is longer than haystack, but only because it's encoded as UTF-16
+assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1);
+
+assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0);
+assert.strictEqual(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1);
+
+// Haystack has odd length, but the needle is UCS2.
+// assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
+
+{
+ // Find substrings in Utf8.
+ var lengths = [1, 3, 15]; // Single char, simple and complex.
+ var indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b];
+ for (var lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
+ for (var i = 0; i < indices.length; i++) {
+ var index = indices[i];
+ var length = lengths[lengthIndex];
+
+ if (index + length > 0x7F) {
+ length = 2 * length;
+ }
+
+ if (index + length > 0x7FF) {
+ length = 3 * length;
+ }
+
+ if (index + length > 0xFFFF) {
+ length = 4 * length;
+ }
+
+ var patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length);
+ assert.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8));
+
+ var patternStringUtf8 = patternBufferUtf8.toString();
+ assert.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8));
+ }
+ }
+}
+
+{
+ // Find substrings in Usc2.
+ var lengths = [2, 4, 16]; // Single char, simple and complex.
+ var indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0];
+ for (var lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
+ for (var i = 0; i < indices.length; i++) {
+ var index = indices[i] * 2;
+ var length = lengths[lengthIndex];
+
+ var patternBufferUcs2 =
+ allCharsBufferUcs2.slice(index, index + length);
+ assert.equal(
+ index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2'));
+
+ var patternStringUcs2 = patternBufferUcs2.toString('ucs2');
+ assert.equal(
+ index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2'));
+ }
+ }
+}
+
+assert.throws(function() {
+ b.indexOf(function() { });
+});
+assert.throws(function() {
+ b.indexOf({});
+});
+assert.throws(function() {
+ b.indexOf([]);
+});
+
+// All code for handling encodings is shared between Buffer.indexOf and
+// Buffer.lastIndexOf, so only testing the separate lastIndexOf semantics.
+
+// Test lastIndexOf basic functionality; Buffer b contains 'abcdef'.
+// lastIndexOf string:
+assert.equal(b.lastIndexOf('a'), 0);
+assert.equal(b.lastIndexOf('a', 1), 0);
+assert.equal(b.lastIndexOf('b', 1), 1);
+assert.equal(b.lastIndexOf('c', 1), -1);
+assert.equal(b.lastIndexOf('a', -1), 0);
+assert.equal(b.lastIndexOf('a', -4), 0);
+assert.equal(b.lastIndexOf('a', -b.length), 0);
+assert.equal(b.lastIndexOf('a', -b.length - 1), -1);
+assert.equal(b.lastIndexOf('a', NaN), 0);
+assert.equal(b.lastIndexOf('a', -Infinity), -1);
+assert.equal(b.lastIndexOf('a', Infinity), 0);
+// lastIndexOf Buffer:
+assert.equal(b.lastIndexOf(buf_a), 0);
+assert.equal(b.lastIndexOf(buf_a, 1), 0);
+assert.equal(b.lastIndexOf(buf_a, -1), 0);
+assert.equal(b.lastIndexOf(buf_a, -4), 0);
+assert.equal(b.lastIndexOf(buf_a, -b.length), 0);
+assert.equal(b.lastIndexOf(buf_a, -b.length - 1), -1);
+assert.equal(b.lastIndexOf(buf_a, NaN), 0);
+assert.equal(b.lastIndexOf(buf_a, -Infinity), -1);
+assert.equal(b.lastIndexOf(buf_a, Infinity), 0);
+assert.equal(b.lastIndexOf(buf_bc), 1);
+assert.equal(b.lastIndexOf(buf_bc, 2), 1);
+assert.equal(b.lastIndexOf(buf_bc, -1), 1);
+assert.equal(b.lastIndexOf(buf_bc, -3), 1);
+assert.equal(b.lastIndexOf(buf_bc, -5), 1);
+assert.equal(b.lastIndexOf(buf_bc, -6), -1);
+assert.equal(b.lastIndexOf(buf_bc, NaN), 1);
+assert.equal(b.lastIndexOf(buf_bc, -Infinity), -1);
+assert.equal(b.lastIndexOf(buf_bc, Infinity), 1);
+assert.equal(b.lastIndexOf(buf_f), b.length - 1);
+assert.equal(b.lastIndexOf(buf_z), -1);
+assert.equal(b.lastIndexOf(buf_empty), -1);
+assert.equal(b.lastIndexOf(buf_empty, 1), -1);
+assert.equal(b.lastIndexOf(buf_empty, b.length + 1), -1);
+assert.equal(b.lastIndexOf(buf_empty, Infinity), -1);
+// lastIndexOf number:
+assert.equal(b.lastIndexOf(0x61), 0);
+assert.equal(b.lastIndexOf(0x61, 1), 0);
+assert.equal(b.lastIndexOf(0x61, -1), 0);
+assert.equal(b.lastIndexOf(0x61, -4), 0);
+assert.equal(b.lastIndexOf(0x61, -b.length), 0);
+assert.equal(b.lastIndexOf(0x61, -b.length - 1), -1);
+assert.equal(b.lastIndexOf(0x61, NaN), 0);
+assert.equal(b.lastIndexOf(0x61, -Infinity), -1);
+assert.equal(b.lastIndexOf(0x61, Infinity), 0);
+assert.equal(b.lastIndexOf(0x0), -1);
+
+// Test weird offset arguments.
+// Behaviour should match String.lastIndexOf:
+assert.equal(b.lastIndexOf('b', 0), -1);
+assert.equal(b.lastIndexOf('b', undefined), 1);
+assert.equal(b.lastIndexOf('b', null), -1);
+assert.equal(b.lastIndexOf('b', {}), 1);
+assert.equal(b.lastIndexOf('b', []), -1);
+assert.equal(b.lastIndexOf('b', [2]), 1);
+
+// Test needles longer than the haystack.
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'ucs2'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'utf8'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'latin1'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'binary'), -1);
+assert.strictEqual(b.lastIndexOf(Buffer.from('aaaaaaaaaaaaaaa')), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 2, 'ucs2'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 3, 'utf8'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 5, 'latin1'), -1);
+assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 5, 'binary'), -1);
+assert.strictEqual(b.lastIndexOf(Buffer.from('aaaaaaaaaaaaaaa'), 7), -1);
+
+// 你好 expands to a total of 6 bytes using UTF-8 and 4 bytes using UTF-16
+assert.strictEqual(buf_bc.lastIndexOf('你好', 'ucs2'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 'utf8'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 'latin1'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 'binary'), -1);
+assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好')), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 2, 'ucs2'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 3, 'utf8'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'latin1'), -1);
+assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'binary'), -1);
+assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1);
+
+// Test lastIndexOf on a longer buffer:
+var bufferString = new Buffer('a man a plan a canal panama');
+assert.equal(15, bufferString.lastIndexOf('canal'));
+assert.equal(21, bufferString.lastIndexOf('panama'));
+assert.equal(0, bufferString.lastIndexOf('a man a plan a canal panama'));
+assert.equal(-1, bufferString.lastIndexOf('a man a plan a canal mexico'));
+assert.equal(-1, bufferString.lastIndexOf('a man a plan a canal mexico city'));
+assert.equal(-1, bufferString.lastIndexOf(Buffer.from('a'.repeat(1000))));
+assert.equal(0, bufferString.lastIndexOf('a man a plan', 4));
+assert.equal(13, bufferString.lastIndexOf('a '));
+assert.equal(13, bufferString.lastIndexOf('a ', 13));
+assert.equal(6, bufferString.lastIndexOf('a ', 12));
+assert.equal(0, bufferString.lastIndexOf('a ', 5));
+assert.equal(13, bufferString.lastIndexOf('a ', -1));
+assert.equal(0, bufferString.lastIndexOf('a ', -27));
+assert.equal(-1, bufferString.lastIndexOf('a ', -28));
+
+// Test lastIndexOf for the case that the first character can be found,
+// but in a part of the buffer that does not make search to search
+// due do length constraints.
+var abInUCS2 = Buffer.from('ab', 'ucs2');
+assert.strictEqual(-1, Buffer.from('µaaaa¶bbbb', 'latin1').lastIndexOf('µ'));
+assert.strictEqual(-1, Buffer.from('µaaaa¶bbbb', 'binary').lastIndexOf('µ'));
+assert.strictEqual(-1, Buffer.from('bc').lastIndexOf('ab'));
+assert.strictEqual(-1, Buffer.from('abc').lastIndexOf('qa'));
+assert.strictEqual(-1, Buffer.from('abcdef').lastIndexOf('qabc'));
+assert.strictEqual(-1, Buffer.from('bc').lastIndexOf(Buffer.from('ab')));
+assert.strictEqual(-1, Buffer.from('bc', 'ucs2').lastIndexOf('ab', 'ucs2'));
+assert.strictEqual(-1, Buffer.from('bc', 'ucs2').lastIndexOf(abInUCS2));
+
+assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab'));
+assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 1));
+assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 2));
+assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 3));
+
+// The above tests test the LINEAR and SINGLE-CHAR strategies.
+// Now, we test the BOYER-MOORE-HORSPOOL strategy.
+// Test lastIndexOf on a long buffer w multiple matches:
+pattern = 'JABACABADABACABA';
+assert.equal(1535, longBufferString.lastIndexOf(pattern));
+assert.equal(1535, longBufferString.lastIndexOf(pattern, 1535));
+assert.equal(511, longBufferString.lastIndexOf(pattern, 1534));
+
+// Finally, give it a really long input to trigger fallback from BMH to
+// regular BOYER-MOORE (which has better worst-case complexity).
+
+// Generate a really long Thue-Morse sequence of 'yolo' and 'swag',
+// "yolo swag swag yolo swag yolo yolo swag" ..., goes on for about 5MB.
+// This is hard to search because it all looks similar, but never repeats.
+
+// countBits returns the number of bits in the binary reprsentation of n.
+function countBits(n) {
+ for (var count = 0; n > 0; count++) {
+ n = n & (n - 1); // remove top bit
+ }
+ return count;
+}
+var parts = [];
+for (var i = 0; i < 1000000; i++) {
+ parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag');
+}
+var reallyLong = new Buffer(parts.join(' '));
+assert.equal('yolo swag swag yolo', reallyLong.slice(0, 19).toString());
+
+// Expensive reverse searches. Stress test lastIndexOf:
+pattern = reallyLong.slice(0, 100000); // First 1/50th of the pattern.
+assert.equal(4751360, reallyLong.lastIndexOf(pattern));
+assert.equal(3932160, reallyLong.lastIndexOf(pattern, 4000000));
+assert.equal(2949120, reallyLong.lastIndexOf(pattern, 3000000));
+pattern = reallyLong.slice(100000, 200000); // Second 1/50th.
+assert.equal(4728480, reallyLong.lastIndexOf(pattern));
+pattern = reallyLong.slice(0, 1000000); // First 1/5th.
+assert.equal(3932160, reallyLong.lastIndexOf(pattern));
+pattern = reallyLong.slice(0, 2000000); // first 2/5ths.
+assert.equal(0, reallyLong.lastIndexOf(pattern));
+
+// test truncation of Number arguments to uint8
+{
+ var buf = Buffer.from('this is a test');
+ assert.strictEqual(buf.indexOf(0x6973), 3);
+ assert.strictEqual(buf.indexOf(0x697320), 4);
+ assert.strictEqual(buf.indexOf(0x69732069), 2);
+ assert.strictEqual(buf.indexOf(0x697374657374), 0);
+ assert.strictEqual(buf.indexOf(0x69737374), 0);
+ assert.strictEqual(buf.indexOf(0x69737465), 11);
+ assert.strictEqual(buf.indexOf(0x69737465), 11);
+ assert.strictEqual(buf.indexOf(-140), 0);
+ assert.strictEqual(buf.indexOf(-152), 1);
+ assert.strictEqual(buf.indexOf(0xff), -1);
+ assert.strictEqual(buf.indexOf(0xffff), -1);
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-inheritance.js b/node_modules/buffer/test/node/test-buffer-inheritance.js
new file mode 100644
index 0000000..711d9f2
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-inheritance.js
@@ -0,0 +1,42 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+
+function T(n) {
+ var ui8 = new Uint8Array(n);
+ Object.setPrototypeOf(ui8, T.prototype);
+ return ui8;
+}
+Object.setPrototypeOf(T.prototype, Buffer.prototype);
+Object.setPrototypeOf(T, Buffer);
+
+T.prototype.sum = function sum() {
+ var cntr = 0;
+ for (var i = 0; i < this.length; i++)
+ cntr += this[i];
+ return cntr;
+};
+
+
+var vals = [new T(4), T(4)];
+
+vals.forEach(function(t) {
+ assert.equal(t.constructor, T);
+ assert.equal(Object.getPrototypeOf(t), T.prototype);
+ assert.equal(Object.getPrototypeOf(Object.getPrototypeOf(t)),
+ Buffer.prototype);
+
+ t.fill(5);
+ var cntr = 0;
+ for (var i = 0; i < t.length; i++)
+ cntr += t[i];
+ assert.equal(t.length * 5, cntr);
+
+ // Check this does not throw
+ t.toString();
+});
+
diff --git a/node_modules/buffer/test/node/test-buffer-inspect.js b/node_modules/buffer/test/node/test-buffer-inspect.js
new file mode 100644
index 0000000..d0ed590
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-inspect.js
@@ -0,0 +1,41 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+var util = require('util');
+
+var buffer = require('../../');
+
+buffer.INSPECT_MAX_BYTES = 2;
+
+var b = Buffer.allocUnsafe(4);
+b.fill('1234');
+
+var s = buffer.SlowBuffer(4);
+s.fill('1234');
+
+var expected = '';
+
+assert.strictEqual(util.inspect(b), expected);
+assert.strictEqual(util.inspect(s), expected);
+
+b = Buffer.allocUnsafe(2);
+b.fill('12');
+
+s = buffer.SlowBuffer(2);
+s.fill('12');
+
+expected = '';
+
+assert.strictEqual(util.inspect(b), expected);
+assert.strictEqual(util.inspect(s), expected);
+
+buffer.INSPECT_MAX_BYTES = Infinity;
+
+assert.doesNotThrow(function() {
+ assert.strictEqual(util.inspect(b), expected);
+ assert.strictEqual(util.inspect(s), expected);
+});
+
diff --git a/node_modules/buffer/test/node/test-buffer-iterator.js b/node_modules/buffer/test/node/test-buffer-iterator.js
new file mode 100644
index 0000000..f27709f
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-iterator.js
@@ -0,0 +1,65 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+var assert = require('assert');
+
+var buffer = Buffer.from([1, 2, 3, 4, 5]);
+var arr;
+var b;
+
+// buffers should be iterable
+
+arr = [];
+
+for (b of buffer)
+ arr.push(b);
+
+assert.deepStrictEqual(arr, [1, 2, 3, 4, 5]);
+
+
+// buffer iterators should be iterable
+
+arr = [];
+
+for (b of buffer[Symbol.iterator]())
+ arr.push(b);
+
+assert.deepStrictEqual(arr, [1, 2, 3, 4, 5]);
+
+
+// buffer#values() should return iterator for values
+
+arr = [];
+
+for (b of buffer.values())
+ arr.push(b);
+
+assert.deepStrictEqual(arr, [1, 2, 3, 4, 5]);
+
+
+// buffer#keys() should return iterator for keys
+
+arr = [];
+
+for (b of buffer.keys())
+ arr.push(b);
+
+assert.deepStrictEqual(arr, [0, 1, 2, 3, 4]);
+
+
+// buffer#entries() should return iterator for entries
+
+arr = [];
+
+for (b of buffer.entries())
+ arr.push(b);
+
+assert.deepStrictEqual(arr, [
+ [0, 1],
+ [1, 2],
+ [2, 3],
+ [3, 4],
+ [4, 5]
+]);
+
diff --git a/node_modules/buffer/test/node/test-buffer-safe-unsafe.js b/node_modules/buffer/test/node/test-buffer-safe-unsafe.js
new file mode 100644
index 0000000..22ba29e
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-safe-unsafe.js
@@ -0,0 +1,27 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+var safe = Buffer.alloc(10);
+
+function isZeroFilled(buf) {
+ for (var n = 0; n < buf.length; n++)
+ if (buf[n] !== 0) return false;
+ return true;
+}
+
+assert(isZeroFilled(safe));
+
+// Test that unsafe allocations doesn't affect subsequent safe allocations
+Buffer.allocUnsafe(10);
+assert(isZeroFilled(new Float64Array(10)));
+
+new Buffer(10);
+assert(isZeroFilled(new Float64Array(10)));
+
+Buffer.allocUnsafe(10);
+assert(isZeroFilled(Buffer.alloc(10)));
+
diff --git a/node_modules/buffer/test/node/test-buffer-slow.js b/node_modules/buffer/test/node/test-buffer-slow.js
new file mode 100644
index 0000000..65cea21
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-slow.js
@@ -0,0 +1,63 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+var buffer = require('../../');
+var Buffer = buffer.Buffer;
+var SlowBuffer = buffer.SlowBuffer;
+
+var ones = [1, 1, 1, 1];
+
+// should create a Buffer
+var sb = SlowBuffer(4);
+assert(sb instanceof Buffer);
+assert.strictEqual(sb.length, 4);
+sb.fill(1);
+for (var [key, value] of sb.entries()) {
+ assert.deepStrictEqual(value, ones[key]);
+}
+
+// underlying ArrayBuffer should have the same length
+assert.strictEqual(sb.buffer.byteLength, 4);
+
+// should work without new
+sb = SlowBuffer(4);
+assert(sb instanceof Buffer);
+assert.strictEqual(sb.length, 4);
+sb.fill(1);
+for (var [key, value] of sb.entries()) {
+ assert.deepStrictEqual(value, ones[key]);
+}
+
+// should work with edge cases
+assert.strictEqual(SlowBuffer(0).length, 0);
+try {
+ assert.strictEqual(
+ SlowBuffer(buffer.kMaxLength).length, buffer.kMaxLength);
+} catch (e) {
+ assert.equal(e.message, 'Array buffer allocation failed');
+}
+
+// should work with number-coercible values
+assert.strictEqual(SlowBuffer('6').length, 6);
+assert.strictEqual(SlowBuffer(true).length, 1);
+
+// should create zero-length buffer if parameter is not a number
+assert.strictEqual(SlowBuffer().length, 0);
+assert.strictEqual(SlowBuffer(NaN).length, 0);
+assert.strictEqual(SlowBuffer({}).length, 0);
+assert.strictEqual(SlowBuffer('string').length, 0);
+
+// should throw with invalid length
+assert.throws(function() {
+ SlowBuffer(Infinity);
+}, 'invalid Buffer length');
+assert.throws(function() {
+ SlowBuffer(-1);
+}, 'invalid Buffer length');
+assert.throws(function() {
+ SlowBuffer(buffer.kMaxLength + 1);
+}, 'invalid Buffer length');
+
diff --git a/node_modules/buffer/test/node/test-buffer-swap.js b/node_modules/buffer/test/node/test-buffer-swap.js
new file mode 100644
index 0000000..2ec1a7a
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-swap.js
@@ -0,0 +1,141 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+// Test buffers small enough to use the JS implementation
+var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
+ 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10]);
+
+assert.strictEqual(buf, buf.swap16());
+assert.deepStrictEqual(buf, Buffer.from([0x02, 0x01, 0x04, 0x03, 0x06, 0x05,
+ 0x08, 0x07, 0x0a, 0x09, 0x0c, 0x0b,
+ 0x0e, 0x0d, 0x10, 0x0f]));
+buf.swap16(); // restore
+
+assert.strictEqual(buf, buf.swap32());
+assert.deepStrictEqual(buf, Buffer.from([0x04, 0x03, 0x02, 0x01, 0x08, 0x07,
+ 0x06, 0x05, 0x0c, 0x0b, 0x0a, 0x09,
+ 0x10, 0x0f, 0x0e, 0x0d]));
+buf.swap32(); // restore
+
+assert.strictEqual(buf, buf.swap64());
+assert.deepStrictEqual(buf, Buffer.from([0x08, 0x07, 0x06, 0x05, 0x04, 0x03,
+ 0x02, 0x01, 0x10, 0x0f, 0x0e, 0x0d,
+ 0x0c, 0x0b, 0x0a, 0x09]));
+
+// Operates in-place
+var buf3 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7]);
+buf3.slice(1, 5).swap32();
+assert.deepStrictEqual(buf3, Buffer.from([0x1, 0x5, 0x4, 0x3, 0x2, 0x6, 0x7]));
+
+buf3.slice(1, 5).swap16();
+assert.deepStrictEqual(buf3, Buffer.from([0x1, 0x4, 0x5, 0x2, 0x3, 0x6, 0x7]));
+
+var buf3_64 = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10]);
+buf3_64.slice(2, 18).swap64();
+assert.deepStrictEqual(buf3_64, Buffer.from([0x01, 0x02, 0x0a, 0x09, 0x08, 0x07,
+ 0x06, 0x05, 0x04, 0x03, 0x02, 0x01,
+ 0x10, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b,
+ 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
+ 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
+ 0x0f, 0x10]));
+
+// Force use of native code (Buffer size above threshold limit for js impl)
+var buf4A = new Uint32Array(256).fill(0x04030201);
+var buf4 = Buffer.from(buf4A.buffer, buf4A.byteOffset);
+var buf5A = new Uint32Array(256).fill(0x03040102);
+var buf5 = Buffer.from(buf5A.buffer, buf5A.byteOffset);
+
+buf4.swap16();
+assert.deepStrictEqual(buf4, buf5);
+
+var buf6A = new Uint32Array(256).fill(0x04030201);
+var buf6 = Buffer.from(buf6A.buffer);
+var bu7A = new Uint32Array(256).fill(0x01020304);
+var buf7 = Buffer.from(bu7A.buffer, bu7A.byteOffset);
+
+buf6.swap32();
+assert.deepStrictEqual(buf6, buf7);
+
+var buf8A = new Uint8Array(256 * 8);
+var buf9A = new Uint8Array(256 * 8);
+for (var i = 0; i < buf8A.length; i++) {
+ buf8A[i] = i % 8;
+ buf9A[buf9A.length - i - 1] = i % 8;
+}
+var buf8 = Buffer.from(buf8A.buffer, buf8A.byteOffset);
+var buf9 = Buffer.from(buf9A.buffer, buf9A.byteOffset);
+
+buf8.swap64();
+assert.deepStrictEqual(buf8, buf9);
+
+// Test native code with buffers that are not memory-aligned
+var buf10A = new Uint8Array(256 * 8);
+var buf11A = new Uint8Array(256 * 8 - 2);
+for (var i = 0; i < buf10A.length; i++) {
+ buf10A[i] = i % 2;
+}
+for (var i = 1; i < buf11A.length; i++) {
+ buf11A[buf11A.length - i] = (i + 1) % 2;
+}
+var buf10 = Buffer.from(buf10A.buffer, buf10A.byteOffset);
+// 0|1 0|1 0|1...
+var buf11 = Buffer.from(buf11A.buffer, buf11A.byteOffset);
+// 0|0 1|0 1|0...
+
+buf10.slice(1, buf10.length - 1).swap16();
+assert.deepStrictEqual(buf10.slice(0, buf11.length), buf11);
+
+
+var buf12A = new Uint8Array(256 * 8);
+var buf13A = new Uint8Array(256 * 8 - 4);
+for (var i = 0; i < buf12A.length; i++) {
+ buf12A[i] = i % 4;
+}
+for (var i = 1; i < buf13A.length; i++) {
+ buf13A[buf13A.length - i] = (i + 1) % 4;
+}
+var buf12 = Buffer.from(buf12A.buffer, buf12A.byteOffset);
+// 0|1 2 3 0|1 2 3...
+var buf13 = Buffer.from(buf13A.buffer, buf13A.byteOffset);
+// 0|0 3 2 1|0 3 2...
+
+buf12.slice(1, buf12.length - 3).swap32();
+assert.deepStrictEqual(buf12.slice(0, buf13.length), buf13);
+
+
+var buf14A = new Uint8Array(256 * 8);
+var buf15A = new Uint8Array(256 * 8 - 8);
+for (var i = 0; i < buf14A.length; i++) {
+ buf14A[i] = i % 8;
+}
+for (var i = 1; i < buf15A.length; i++) {
+ buf15A[buf15A.length - i] = (i + 1) % 8;
+}
+var buf14 = Buffer.from(buf14A.buffer, buf14A.byteOffset);
+// 0|1 2 3 4 5 6 7 0|1 2 3 4...
+var buf15 = Buffer.from(buf15A.buffer, buf15A.byteOffset);
+// 0|0 7 6 5 4 3 2 1|0 7 6 5...
+
+buf14.slice(1, buf14.length - 7).swap64();
+assert.deepStrictEqual(buf14.slice(0, buf15.length), buf15);
+
+// Length assertions
+var re16 = /Buffer size must be a multiple of 16-bits/;
+var re32 = /Buffer size must be a multiple of 32-bits/;
+var re64 = /Buffer size must be a multiple of 64-bits/;
+
+assert.throws(() => Buffer.from(buf3).swap16(), re16);
+assert.throws(() => Buffer.alloc(1025).swap16(), re16);
+assert.throws(() => Buffer.from(buf3).swap32(), re32);
+assert.throws(() => buf3.slice(1, 3).swap32(), re32);
+assert.throws(() => Buffer.alloc(1025).swap32(), re32);
+assert.throws(() => buf3.slice(1, 3).swap64(), re64);
+assert.throws(() => Buffer.alloc(1025).swap64(), re64);
+
diff --git a/node_modules/buffer/test/node/test-buffer-zero-fill-cli.js b/node_modules/buffer/test/node/test-buffer-zero-fill-cli.js
new file mode 100644
index 0000000..744b334
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-zero-fill-cli.js
@@ -0,0 +1,35 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+// Flags: --zero-fill-buffers
+
+// when using --zero-fill-buffers, every Buffer and SlowBuffer
+// instance must be zero filled upon creation
+
+
+var SlowBuffer = require('../../').SlowBuffer;
+var assert = require('assert');
+
+function isZeroFilled(buf) {
+ for (var n = 0; n < buf.length; n++)
+ if (buf[n] > 0) return false;
+ return true;
+}
+
+// This can be somewhat unreliable because the
+// allocated memory might just already happen to
+// contain all zeroes. The test is run multiple
+// times to improve the reliability.
+for (var i = 0; i < 50; i++) {
+ var bufs = [
+ Buffer.alloc(20),
+ Buffer.allocUnsafe(20),
+ SlowBuffer(20),
+ Buffer(20),
+ new SlowBuffer(20)
+ ];
+ for (var buf of bufs) {
+ assert(isZeroFilled(buf));
+ }
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer-zero-fill-reset.js b/node_modules/buffer/test/node/test-buffer-zero-fill-reset.js
new file mode 100644
index 0000000..b21a6b2
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer-zero-fill-reset.js
@@ -0,0 +1,22 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+
+
+var assert = require('assert');
+
+
+function testUint8Array(ui) {
+ var length = ui.length;
+ for (var i = 0; i < length; i++)
+ if (ui[i] !== 0) return false;
+ return true;
+}
+
+
+for (var i = 0; i < 100; i++) {
+ Buffer.alloc(0);
+ var ui = new Uint8Array(65);
+ assert.ok(testUint8Array(ui), 'Uint8Array is not zero-filled');
+}
+
diff --git a/node_modules/buffer/test/node/test-buffer.js b/node_modules/buffer/test/node/test-buffer.js
new file mode 100644
index 0000000..2e94de2
--- /dev/null
+++ b/node_modules/buffer/test/node/test-buffer.js
@@ -0,0 +1,1534 @@
+'use strict';
+var Buffer = require('../../').Buffer;
+
+var common = { skip: function () {} };
+var assert = require('assert');
+
+var Buffer = require('../../').Buffer;
+var SlowBuffer = require('../../').SlowBuffer;
+
+// counter to ensure unique value is always copied
+var cntr = 0;
+
+var b = Buffer(1024); // safe constructor
+
+// console.log('b.length == %d', b.length);
+assert.strictEqual(1024, b.length);
+
+b[0] = -1;
+assert.strictEqual(b[0], 255);
+
+for (var i = 0; i < 1024; i++) {
+ b[i] = i % 256;
+}
+
+for (var i = 0; i < 1024; i++) {
+ assert.strictEqual(i % 256, b[i]);
+}
+
+var c = Buffer(512);
+// console.log('c.length == %d', c.length);
+assert.strictEqual(512, c.length);
+
+var d = new Buffer([]);
+assert.strictEqual(0, d.length);
+
+var ui32 = new Uint32Array(4).fill(42);
+var e = Buffer(ui32);
+for (var [key, value] of e.entries()) {
+ assert.deepStrictEqual(value, ui32[key]);
+}
+
+// First check Buffer#fill() works as expected.
+
+assert.throws(function() {
+ Buffer(8).fill('a', -1);
+});
+
+assert.throws(function() {
+ Buffer(8).fill('a', 0, 9);
+});
+
+// Make sure this doesn't hang indefinitely.
+Buffer(8).fill('');
+
+{
+ var buf = new Buffer(64);
+ buf.fill(10);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(buf[i], 10);
+
+ buf.fill(11, 0, buf.length >> 1);
+ for (var i = 0; i < buf.length >> 1; i++)
+ assert.equal(buf[i], 11);
+ for (var i = (buf.length >> 1) + 1; i < buf.length; i++)
+ assert.equal(buf[i], 10);
+
+ buf.fill('h');
+ for (var i = 0; i < buf.length; i++)
+ assert.equal('h'.charCodeAt(0), buf[i]);
+
+ buf.fill(0);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+
+ buf.fill(null);
+ for (var i = 0; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+
+ buf.fill(1, 16, 32);
+ for (var i = 0; i < 16; i++)
+ assert.equal(0, buf[i]);
+ for (var i = 16; i < 32; i++)
+ assert.equal(1, buf[i]);
+ for (var i = 32; i < buf.length; i++)
+ assert.equal(0, buf[i]);
+}
+
+{
+ var buf = new Buffer(10);
+ buf.fill('abc');
+ assert.equal(buf.toString(), 'abcabcabca');
+ buf.fill('է');
+ assert.equal(buf.toString(), 'էէէէէ');
+}
+
+{
+ // copy 512 bytes, from 0 to 512.
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 512);
+// console.log('copied %d bytes from b into c', copied);
+ assert.strictEqual(512, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy c into b, without specifying sourceEnd
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = c.copy(b, 0, 0);
+// console.log('copied %d bytes from c into b w/o sourceEnd', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(c[i], b[i]);
+ }
+}
+
+{
+ // copy c into b, without specifying sourceStart
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = c.copy(b, 0);
+// console.log('copied %d bytes from c into b w/o sourceStart', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(c[i], b[i]);
+ }
+}
+
+{
+ // copy longer buffer b to shorter c without targetStart
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c);
+// console.log('copied %d bytes from b into c w/o targetStart', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy starting near end of b to c
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, b.length - Math.floor(c.length / 2));
+// console.log('copied %d bytes from end of b into beginning of c', copied);
+ assert.strictEqual(Math.floor(c.length / 2), copied);
+ for (var i = 0; i < Math.floor(c.length / 2); i++) {
+ assert.strictEqual(b[b.length - Math.floor(c.length / 2) + i], c[i]);
+ }
+ for (var i = Math.floor(c.length / 2) + 1; i < c.length; i++) {
+ assert.strictEqual(c[c.length - 1], c[i]);
+ }
+}
+
+{
+ // try to copy 513 bytes, and check we don't overrun c
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 513);
+// console.log('copied %d bytes from b trying to overrun c', copied);
+ assert.strictEqual(c.length, copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+{
+ // copy 768 bytes from b into b
+ b.fill(++cntr);
+ b.fill(++cntr, 256);
+ var copied = b.copy(b, 0, 256, 1024);
+// console.log('copied %d bytes from b into b', copied);
+ assert.strictEqual(768, copied);
+ for (var i = 0; i < b.length; i++) {
+ assert.strictEqual(cntr, b[i]);
+ }
+}
+
+// copy string longer than buffer length (failure will segfault)
+var bb = Buffer(10);
+bb.fill('hello crazy world');
+
+
+// try to copy from before the beginning of b
+assert.doesNotThrow(() => { b.copy(c, 0, 100, 10); });
+
+// copy throws at negative sourceStart
+assert.throws(function() {
+ Buffer(5).copy(Buffer(5), 0, -1);
+}, RangeError);
+
+{
+ // check sourceEnd resets to targetEnd if former is greater than the latter
+ b.fill(++cntr);
+ c.fill(++cntr);
+ var copied = b.copy(c, 0, 0, 1025);
+// console.log('copied %d bytes from b into c', copied);
+ for (var i = 0; i < c.length; i++) {
+ assert.strictEqual(b[i], c[i]);
+ }
+}
+
+// throw with negative sourceEnd
+// console.log('test copy at negative sourceEnd');
+assert.throws(function() {
+ b.copy(c, 0, 0, -1);
+}, RangeError);
+
+// when sourceStart is greater than sourceEnd, zero copied
+assert.equal(b.copy(c, 0, 100, 10), 0);
+
+// when targetStart > targetLength, zero copied
+assert.equal(b.copy(c, 512, 0, 10), 0);
+
+var caught_error;
+
+// invalid encoding for Buffer.toString
+caught_error = null;
+try {
+ b.toString('invalid');
+} catch (err) {
+ caught_error = err;
+}
+assert.strictEqual('Unknown encoding: invalid', caught_error.message);
+
+// invalid encoding for Buffer.write
+caught_error = null;
+try {
+ b.write('test string', 0, 5, 'invalid');
+} catch (err) {
+ caught_error = err;
+}
+assert.strictEqual('Unknown encoding: invalid', caught_error.message);
+
+// try to create 0-length buffers
+new Buffer('');
+new Buffer('', 'ascii');
+new Buffer('', 'latin1');
+new Buffer('', 'binary');
+Buffer(0);
+
+// try to write a 0-length string beyond the end of b
+assert.throws(function() {
+ b.write('', 2048);
+}, RangeError);
+
+// throw when writing to negative offset
+assert.throws(function() {
+ b.write('a', -1);
+}, RangeError);
+
+// throw when writing past bounds from the pool
+assert.throws(function() {
+ b.write('a', 2048);
+}, RangeError);
+
+// throw when writing to negative offset
+assert.throws(function() {
+ b.write('a', -1);
+}, RangeError);
+
+// try to copy 0 bytes worth of data into an empty buffer
+b.copy(Buffer(0), 0, 0, 0);
+
+// try to copy 0 bytes past the end of the target buffer
+b.copy(Buffer(0), 1, 1, 1);
+b.copy(Buffer(1), 1, 1, 1);
+
+// try to copy 0 bytes from past the end of the source buffer
+b.copy(Buffer(1), 0, 2048, 2048);
+
+var rangeBuffer = new Buffer('abc');
+
+// if start >= buffer's length, empty string will be returned
+assert.equal(rangeBuffer.toString('ascii', 3), '');
+assert.equal(rangeBuffer.toString('ascii', +Infinity), '');
+assert.equal(rangeBuffer.toString('ascii', 3.14, 3), '');
+assert.equal(rangeBuffer.toString('ascii', 'Infinity', 3), '');
+
+// if end <= 0, empty string will be returned
+assert.equal(rangeBuffer.toString('ascii', 1, 0), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -1.2), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -100), '');
+assert.equal(rangeBuffer.toString('ascii', 1, -Infinity), '');
+
+// if start < 0, start will be taken as zero
+assert.equal(rangeBuffer.toString('ascii', -1, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', -1.99, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', -Infinity, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc');
+
+// if start is an invalid integer, start will be taken as zero
+assert.equal(rangeBuffer.toString('ascii', 'node.js', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', {}, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', [], 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', NaN, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', null, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', undefined, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', false, 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '', 3), 'abc');
+
+// but, if start is an integer when coerced, then it will be coerced and used.
+assert.equal(rangeBuffer.toString('ascii', '-1', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '1', 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', '-Infinity', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', '3', 3), '');
+assert.equal(rangeBuffer.toString('ascii', Number(3), 3), '');
+assert.equal(rangeBuffer.toString('ascii', '3.14', 3), '');
+assert.equal(rangeBuffer.toString('ascii', '1.99', 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', '-1.99', 3), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 1.99, 3), 'bc');
+assert.equal(rangeBuffer.toString('ascii', true, 3), 'bc');
+
+// if end > buffer's length, end will be taken as buffer's length
+assert.equal(rangeBuffer.toString('ascii', 0, 5), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, 6.99), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, Infinity), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '5'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '6.99'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, 'Infinity'), 'abc');
+
+// if end is an invalid integer, end will be taken as buffer's length
+assert.equal(rangeBuffer.toString('ascii', 0, 'node.js'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, {}), '');
+assert.equal(rangeBuffer.toString('ascii', 0, NaN), '');
+assert.equal(rangeBuffer.toString('ascii', 0, undefined), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, null), '');
+assert.equal(rangeBuffer.toString('ascii', 0, []), '');
+assert.equal(rangeBuffer.toString('ascii', 0, false), '');
+assert.equal(rangeBuffer.toString('ascii', 0, ''), '');
+
+// but, if end is an integer when coerced, then it will be coerced and used.
+assert.equal(rangeBuffer.toString('ascii', 0, '-1'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, '1'), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, '-Infinity'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, '3'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, Number(3)), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '3.14'), 'abc');
+assert.equal(rangeBuffer.toString('ascii', 0, '1.99'), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, '-1.99'), '');
+assert.equal(rangeBuffer.toString('ascii', 0, 1.99), 'a');
+assert.equal(rangeBuffer.toString('ascii', 0, true), 'a');
+
+// try toString() with a object as a encoding
+assert.equal(rangeBuffer.toString({toString: function() {
+ return 'ascii';
+}}), 'abc');
+
+// testing for smart defaults and ability to pass string values as offset
+var writeTest = new Buffer('abcdes');
+writeTest.write('n', 'ascii');
+writeTest.write('o', '1', 'ascii');
+writeTest.write('d', '2', 'ascii');
+writeTest.write('e', 3, 'ascii');
+writeTest.write('j', 4, 'ascii');
+assert.equal(writeTest.toString(), 'nodejs');
+
+// ASCII slice test
+{
+ var asciiString = 'hello world';
+
+ for (var i = 0; i < asciiString.length; i++) {
+ b[i] = asciiString.charCodeAt(i);
+ }
+ var asciiSlice = b.toString('ascii', 0, asciiString.length);
+ assert.equal(asciiString, asciiSlice);
+}
+
+{
+ var asciiString = 'hello world';
+ var offset = 100;
+
+ var written = b.write(asciiString, offset, 'ascii');
+ assert.equal(asciiString.length, written);
+ var asciiSlice = b.toString('ascii', offset, offset + asciiString.length);
+ assert.equal(asciiString, asciiSlice);
+}
+
+{
+ var asciiString = 'hello world';
+ var offset = 100;
+
+ var sliceA = b.slice(offset, offset + asciiString.length);
+ var sliceB = b.slice(offset, offset + asciiString.length);
+ for (var i = 0; i < asciiString.length; i++) {
+ assert.equal(sliceA[i], sliceB[i]);
+ }
+}
+
+// UTF-8 slice test
+
+var utf8String = '¡hέlló wôrld!';
+var offset = 100;
+
+b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8');
+var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String));
+assert.equal(utf8String, utf8Slice);
+
+var written = b.write(utf8String, offset, 'utf8');
+assert.equal(Buffer.byteLength(utf8String), written);
+utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String));
+assert.equal(utf8String, utf8Slice);
+
+var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String));
+var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String));
+for (var i = 0; i < Buffer.byteLength(utf8String); i++) {
+ assert.equal(sliceA[i], sliceB[i]);
+}
+
+{
+ var slice = b.slice(100, 150);
+ assert.equal(50, slice.length);
+ for (var i = 0; i < 50; i++) {
+ assert.equal(b[100 + i], slice[i]);
+ }
+}
+
+{
+ // make sure only top level parent propagates from allocPool
+ var b = new Buffer(5);
+ var c = b.slice(0, 4);
+ var d = c.slice(0, 2);
+ assert.equal(b.parent, c.parent);
+ assert.equal(b.parent, d.parent);
+}
+
+{
+ // also from a non-pooled instance
+ var b = new SlowBuffer(5);
+ var c = b.slice(0, 4);
+ var d = c.slice(0, 2);
+ assert.equal(c.parent, d.parent);
+}
+
+{
+ // Bug regression test
+ var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語
+ var buffer = new Buffer(32);
+ var size = buffer.write(testValue, 0, 'utf8');
+// console.log('bytes written to buffer: ' + size);
+ var slice = buffer.toString('utf8', 0, size);
+ assert.equal(slice, testValue);
+}
+
+{
+ // Test triple slice
+ var a = new Buffer(8);
+ for (var i = 0; i < 8; i++) a[i] = i;
+ var b = a.slice(4, 8);
+ assert.equal(4, b[0]);
+ assert.equal(5, b[1]);
+ assert.equal(6, b[2]);
+ assert.equal(7, b[3]);
+ var c = b.slice(2, 4);
+ assert.equal(6, c[0]);
+ assert.equal(7, c[1]);
+}
+
+{
+ var d = new Buffer([23, 42, 255]);
+ assert.equal(d.length, 3);
+ assert.equal(d[0], 23);
+ assert.equal(d[1], 42);
+ assert.equal(d[2], 255);
+ assert.deepStrictEqual(d, new Buffer(d));
+}
+
+{
+ var e = new Buffer('über');
+// console.error('uber: \'%s\'', e.toString());
+ assert.deepStrictEqual(e, new Buffer([195, 188, 98, 101, 114]));
+}
+
+{
+ var f = new Buffer('über', 'ascii');
+// console.error('f.length: %d (should be 4)', f.length);
+ assert.deepStrictEqual(f, new Buffer([252, 98, 101, 114]));
+}
+
+['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ {
+ var f = new Buffer('über', encoding);
+// console.error('f.length: %d (should be 8)', f.length);
+ assert.deepStrictEqual(f, new Buffer([252, 0, 98, 0, 101, 0, 114, 0]));
+ }
+
+ {
+ var f = new Buffer('привет', encoding);
+// console.error('f.length: %d (should be 12)', f.length);
+ var expected = new Buffer([63, 4, 64, 4, 56, 4, 50, 4, 53, 4, 66, 4]);
+ assert.deepStrictEqual(f, expected);
+ assert.equal(f.toString(encoding), 'привет');
+ }
+
+ {
+ var f = new Buffer([0, 0, 0, 0, 0]);
+ assert.equal(f.length, 5);
+ var size = f.write('あいうえお', encoding);
+// console.error('bytes written to buffer: %d (should be 4)', size);
+ assert.equal(size, 4);
+ assert.deepStrictEqual(f, new Buffer([0x42, 0x30, 0x44, 0x30, 0x00]));
+ }
+});
+
+{
+ var f = new Buffer('\uD83D\uDC4D', 'utf-16le'); // THUMBS UP SIGN (U+1F44D)
+ assert.equal(f.length, 4);
+ assert.deepStrictEqual(f, new Buffer('3DD84DDC', 'hex'));
+}
+
+
+var arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4};
+var g = new Buffer(arrayIsh);
+assert.deepStrictEqual(g, new Buffer([0, 1, 2, 3]));
+var strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4};
+g = new Buffer(strArrayIsh);
+assert.deepStrictEqual(g, new Buffer([0, 1, 2, 3]));
+
+
+//
+// Test toString('base64')
+//
+assert.equal('TWFu', (new Buffer('Man')).toString('base64'));
+
+{
+ // test that regular and URL-safe base64 both work
+ var expected = [0xff, 0xff, 0xbe, 0xff, 0xef, 0xbf, 0xfb, 0xef, 0xff];
+ assert.deepStrictEqual(Buffer('//++/++/++//', 'base64'), Buffer(expected));
+ assert.deepStrictEqual(Buffer('__--_--_--__', 'base64'), Buffer(expected));
+}
+
+{
+ // big example
+ var quote = 'Man is distinguished, not only by his reason, but by this ' +
+ 'singular passion from other animals, which is a lust ' +
+ 'of the mind, that by a perseverance of delight in the ' +
+ 'continued and indefatigable generation of knowledge, ' +
+ 'exceeds the short vehemence of any carnal pleasure.';
+ var expected = 'TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb' +
+ '24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlci' +
+ 'BhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQ' +
+ 'gYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu' +
+ 'dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZ' +
+ 'GdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm' +
+ '5hbCBwbGVhc3VyZS4=';
+ assert.equal(expected, (new Buffer(quote)).toString('base64'));
+
+ var b = new Buffer(1024);
+ var bytesWritten = b.write(expected, 0, 'base64');
+ assert.equal(quote.length, bytesWritten);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder ignores whitespace
+ var expectedWhite = expected.slice(0, 60) + ' \n' +
+ expected.slice(60, 120) + ' \n' +
+ expected.slice(120, 180) + ' \n' +
+ expected.slice(180, 240) + ' \n' +
+ expected.slice(240, 300) + '\n' +
+ expected.slice(300, 360) + '\n';
+ b = new Buffer(1024);
+ bytesWritten = b.write(expectedWhite, 0, 'base64');
+ assert.equal(quote.length, bytesWritten);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder on the constructor works
+ // even in the presence of whitespace.
+ b = new Buffer(expectedWhite, 'base64');
+ assert.equal(quote.length, b.length);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+
+ // check that the base64 decoder ignores illegal chars
+ var expectedIllegal = expected.slice(0, 60) + ' \x80' +
+ expected.slice(60, 120) + ' \xff' +
+ expected.slice(120, 180) + ' \x00' +
+ expected.slice(180, 240) + ' \x98' +
+ expected.slice(240, 300) + '\x03' +
+ expected.slice(300, 360);
+ b = new Buffer(expectedIllegal, 'base64');
+ assert.equal(quote.length, b.length);
+ assert.equal(quote, b.toString('ascii', 0, quote.length));
+}
+
+assert.equal(new Buffer('', 'base64').toString(), '');
+assert.equal(new Buffer('K', 'base64').toString(), '');
+
+// multiple-of-4 with padding
+assert.equal(new Buffer('Kg==', 'base64').toString(), '*');
+assert.equal(new Buffer('Kio=', 'base64').toString(), '**');
+assert.equal(new Buffer('Kioq', 'base64').toString(), '***');
+assert.equal(new Buffer('KioqKg==', 'base64').toString(), '****');
+assert.equal(new Buffer('KioqKio=', 'base64').toString(), '*****');
+assert.equal(new Buffer('KioqKioq', 'base64').toString(), '******');
+assert.equal(new Buffer('KioqKioqKg==', 'base64').toString(), '*******');
+assert.equal(new Buffer('KioqKioqKio=', 'base64').toString(), '********');
+assert.equal(new Buffer('KioqKioqKioq', 'base64').toString(), '*********');
+assert.equal(new Buffer('KioqKioqKioqKg==', 'base64').toString(),
+ '**********');
+assert.equal(new Buffer('KioqKioqKioqKio=', 'base64').toString(),
+ '***********');
+assert.equal(new Buffer('KioqKioqKioqKioq', 'base64').toString(),
+ '************');
+assert.equal(new Buffer('KioqKioqKioqKioqKg==', 'base64').toString(),
+ '*************');
+assert.equal(new Buffer('KioqKioqKioqKioqKio=', 'base64').toString(),
+ '**************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioq', 'base64').toString(),
+ '***************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKg==', 'base64').toString(),
+ '****************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKio=', 'base64').toString(),
+ '*****************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKioq', 'base64').toString(),
+ '******************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg==', 'base64').toString(),
+ '*******************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio=', 'base64').toString(),
+ '********************');
+
+// no padding, not a multiple of 4
+assert.equal(new Buffer('Kg', 'base64').toString(), '*');
+assert.equal(new Buffer('Kio', 'base64').toString(), '**');
+assert.equal(new Buffer('KioqKg', 'base64').toString(), '****');
+assert.equal(new Buffer('KioqKio', 'base64').toString(), '*****');
+assert.equal(new Buffer('KioqKioqKg', 'base64').toString(), '*******');
+assert.equal(new Buffer('KioqKioqKio', 'base64').toString(), '********');
+assert.equal(new Buffer('KioqKioqKioqKg', 'base64').toString(), '**********');
+assert.equal(new Buffer('KioqKioqKioqKio', 'base64').toString(), '***********');
+assert.equal(new Buffer('KioqKioqKioqKioqKg', 'base64').toString(),
+ '*************');
+assert.equal(new Buffer('KioqKioqKioqKioqKio', 'base64').toString(),
+ '**************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKg', 'base64').toString(),
+ '****************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKio', 'base64').toString(),
+ '*****************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKg', 'base64').toString(),
+ '*******************');
+assert.equal(new Buffer('KioqKioqKioqKioqKioqKioqKio', 'base64').toString(),
+ '********************');
+
+// handle padding graciously, multiple-of-4 or not
+assert.equal(
+ new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw==', 'base64').length,
+ 32
+);
+assert.equal(
+ new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw=', 'base64').length,
+ 32
+);
+assert.equal(
+ new Buffer('72INjkR5fchcxk9+VgdGPFJDxUBFR5/rMFsghgxADiw', 'base64').length,
+ 32
+);
+assert.equal(
+ new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg==', 'base64').length,
+ 31
+);
+assert.equal(
+ new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg=', 'base64').length,
+ 31
+);
+assert.equal(
+ new Buffer('w69jACy6BgZmaFvv96HG6MYksWytuZu3T1FvGnulPg', 'base64').length,
+ 31
+);
+
+// This string encodes single '.' character in UTF-16
+var dot = new Buffer('//4uAA==', 'base64');
+assert.equal(dot[0], 0xff);
+assert.equal(dot[1], 0xfe);
+assert.equal(dot[2], 0x2e);
+assert.equal(dot[3], 0x00);
+assert.equal(dot.toString('base64'), '//4uAA==');
+
+{
+ // Writing base64 at a position > 0 should not mangle the result.
+ //
+ // https://github.com/joyent/node/issues/402
+ var segments = ['TWFkbmVzcz8h', 'IFRoaXM=', 'IGlz', 'IG5vZGUuanMh'];
+ var b = new Buffer(64);
+ var pos = 0;
+
+ for (var i = 0; i < segments.length; ++i) {
+ pos += b.write(segments[i], pos, 'base64');
+ }
+ assert.equal(b.toString('latin1', 0, pos), 'Madness?! This is node.js!');
+ assert.equal(b.toString('binary', 0, pos), 'Madness?! This is node.js!');
+}
+
+// Regression test for https://github.com/nodejs/node/issues/3496.
+// assert.equal(Buffer('=bad'.repeat(1e4), 'base64').length, 0);
+
+{
+ // Creating buffers larger than pool size.
+ var l = Buffer.poolSize + 5;
+ var s = 'h'.repeat(l);
+
+ var b = new Buffer(s);
+
+ for (var i = 0; i < l; i++) {
+ assert.equal('h'.charCodeAt(0), b[i]);
+ }
+
+ var sb = b.toString();
+ assert.equal(sb.length, s.length);
+ assert.equal(sb, s);
+}
+
+{
+ // Single argument slice
+ var b = new Buffer('abcde');
+ assert.equal('bcde', b.slice(1).toString());
+}
+
+// slice(0,0).length === 0
+assert.equal(0, Buffer('hello').slice(0, 0).length);
+
+// test hex toString
+// console.log('Create hex string from buffer');
+var hexb = new Buffer(256);
+for (var i = 0; i < 256; i++) {
+ hexb[i] = i;
+}
+var hexStr = hexb.toString('hex');
+assert.equal(hexStr,
+ '000102030405060708090a0b0c0d0e0f' +
+ '101112131415161718191a1b1c1d1e1f' +
+ '202122232425262728292a2b2c2d2e2f' +
+ '303132333435363738393a3b3c3d3e3f' +
+ '404142434445464748494a4b4c4d4e4f' +
+ '505152535455565758595a5b5c5d5e5f' +
+ '606162636465666768696a6b6c6d6e6f' +
+ '707172737475767778797a7b7c7d7e7f' +
+ '808182838485868788898a8b8c8d8e8f' +
+ '909192939495969798999a9b9c9d9e9f' +
+ 'a0a1a2a3a4a5a6a7a8a9aaabacadaeaf' +
+ 'b0b1b2b3b4b5b6b7b8b9babbbcbdbebf' +
+ 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf' +
+ 'd0d1d2d3d4d5d6d7d8d9dadbdcdddedf' +
+ 'e0e1e2e3e4e5e6e7e8e9eaebecedeeef' +
+ 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff');
+
+// console.log('Create buffer from hex string');
+var hexb2 = new Buffer(hexStr, 'hex');
+for (var i = 0; i < 256; i++) {
+ assert.equal(hexb2[i], hexb[i]);
+}
+
+// Test single hex character throws TypeError
+// - https://github.com/nodejs/node/issues/6770
+assert.throws(function() {
+ Buffer.from('A', 'hex');
+}, TypeError);
+
+// Test single base64 char encodes as 0
+// assert.strictEqual(Buffer.from('A', 'base64').length, 0);
+
+{
+ // test an invalid slice end.
+// console.log('Try to slice off the end of the buffer');
+ var b = new Buffer([1, 2, 3, 4, 5]);
+ var b2 = b.toString('hex', 1, 10000);
+ var b3 = b.toString('hex', 1, 5);
+ var b4 = b.toString('hex', 1);
+ assert.equal(b2, b3);
+ assert.equal(b2, b4);
+}
+
+function buildBuffer(data) {
+ if (Array.isArray(data)) {
+ var buffer = Buffer(data.length);
+ data.forEach(function(v, k) {
+ buffer[k] = v;
+ });
+ return buffer;
+ }
+ return null;
+}
+
+var x = buildBuffer([0x81, 0xa3, 0x66, 0x6f, 0x6f, 0xa3, 0x62, 0x61, 0x72]);
+
+// console.log(x.inspect());
+assert.equal('', x.inspect());
+
+{
+ var z = x.slice(4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(5, z.length);
+ assert.equal(0x6f, z[0]);
+ assert.equal(0xa3, z[1]);
+ assert.equal(0x62, z[2]);
+ assert.equal(0x61, z[3]);
+ assert.equal(0x72, z[4]);
+}
+
+{
+ var z = x.slice(0);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(z.length, x.length);
+}
+
+{
+ var z = x.slice(0, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(4, z.length);
+ assert.equal(0x81, z[0]);
+ assert.equal(0xa3, z[1]);
+}
+
+{
+ var z = x.slice(0, 9);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(9, z.length);
+}
+
+{
+ var z = x.slice(1, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(3, z.length);
+ assert.equal(0xa3, z[0]);
+}
+
+{
+ var z = x.slice(2, 4);
+// console.log(z.inspect());
+// console.log(z.length);
+ assert.equal(2, z.length);
+ assert.equal(0x66, z[0]);
+ assert.equal(0x6f, z[1]);
+}
+
+assert.equal(0, Buffer('hello').slice(0, 0).length);
+
+['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ var b = new Buffer(10);
+ b.write('あいうえお', encoding);
+ assert.equal(b.toString(encoding), 'あいうえお');
+});
+
+{
+ // latin1 encoding should write only one byte per character.
+ var b = Buffer([0xde, 0xad, 0xbe, 0xef]);
+ var s = String.fromCharCode(0xffff);
+ b.write(s, 0, 'latin1');
+ assert.equal(0xff, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+ s = String.fromCharCode(0xaaee);
+ b.write(s, 0, 'latin1');
+ assert.equal(0xee, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+}
+
+{
+ // Binary encoding should write only one byte per character.
+ var b = Buffer([0xde, 0xad, 0xbe, 0xef]);
+ var s = String.fromCharCode(0xffff);
+ b.write(s, 0, 'binary');
+ assert.equal(0xff, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+ s = String.fromCharCode(0xaaee);
+ b.write(s, 0, 'binary');
+ assert.equal(0xee, b[0]);
+ assert.equal(0xad, b[1]);
+ assert.equal(0xbe, b[2]);
+ assert.equal(0xef, b[3]);
+}
+
+{
+ // #1210 Test UTF-8 string includes null character
+ var buf = new Buffer('\0');
+ assert.equal(buf.length, 1);
+ buf = new Buffer('\0\0');
+ assert.equal(buf.length, 2);
+}
+
+{
+ var buf = new Buffer(2);
+ var written = buf.write(''); // 0byte
+ assert.equal(written, 0);
+ written = buf.write('\0'); // 1byte (v8 adds null terminator)
+ assert.equal(written, 1);
+ written = buf.write('a\0'); // 1byte * 2
+ assert.equal(written, 2);
+ written = buf.write('あ'); // 3bytes
+ assert.equal(written, 0);
+ written = buf.write('\0あ'); // 1byte + 3bytes
+ assert.equal(written, 1);
+ written = buf.write('\0\0あ'); // 1byte * 2 + 3bytes
+ assert.equal(written, 2);
+}
+
+{
+ var buf = new Buffer(10);
+ written = buf.write('あいう'); // 3bytes * 3 (v8 adds null terminator)
+ assert.equal(written, 9);
+ written = buf.write('あいう\0'); // 3bytes * 3 + 1byte
+ assert.equal(written, 10);
+}
+
+{
+ // #243 Test write() with maxLength
+ var buf = new Buffer(4);
+ buf.fill(0xFF);
+ var written = buf.write('abcd', 1, 2, 'utf8');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0xFF);
+
+ buf.fill(0xFF);
+ written = buf.write('abcd', 1, 4);
+// console.log(buf);
+ assert.equal(written, 3);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0x63);
+
+ buf.fill(0xFF);
+ written = buf.write('abcd', 1, 2, 'utf8');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0x61);
+ assert.equal(buf[2], 0x62);
+ assert.equal(buf[3], 0xFF);
+
+ buf.fill(0xFF);
+ written = buf.write('abcdef', 1, 2, 'hex');
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0xFF);
+ assert.equal(buf[1], 0xAB);
+ assert.equal(buf[2], 0xCD);
+ assert.equal(buf[3], 0xFF);
+
+ ['ucs2', 'ucs-2', 'utf16le', 'utf-16le'].forEach(function(encoding) {
+ buf.fill(0xFF);
+ written = buf.write('abcd', 0, 2, encoding);
+// console.log(buf);
+ assert.equal(written, 2);
+ assert.equal(buf[0], 0x61);
+ assert.equal(buf[1], 0x00);
+ assert.equal(buf[2], 0xFF);
+ assert.equal(buf[3], 0xFF);
+ });
+}
+
+{
+ // test offset returns are correct
+ var b = new Buffer(16);
+ assert.equal(4, b.writeUInt32LE(0, 0));
+ assert.equal(6, b.writeUInt16LE(0, 4));
+ assert.equal(7, b.writeUInt8(0, 6));
+ assert.equal(8, b.writeInt8(0, 7));
+ assert.equal(16, b.writeDoubleLE(0, 8));
+}
+
+{
+ // test unmatched surrogates not producing invalid utf8 output
+ // ef bf bd = utf-8 representation of unicode replacement character
+ // see https://codereview.chromium.org/121173009/
+ var buf = new Buffer('ab\ud800cd', 'utf8');
+ assert.equal(buf[0], 0x61);
+ assert.equal(buf[1], 0x62);
+ assert.equal(buf[2], 0xef);
+ assert.equal(buf[3], 0xbf);
+ assert.equal(buf[4], 0xbd);
+ assert.equal(buf[5], 0x63);
+ assert.equal(buf[6], 0x64);
+}
+
+{
+ // test for buffer overrun
+ var buf = new Buffer([0, 0, 0, 0, 0]); // length: 5
+ var sub = buf.slice(0, 4); // length: 4
+ written = sub.write('12345', 'latin1');
+ assert.equal(written, 4);
+ assert.equal(buf[4], 0);
+ written = sub.write('12345', 'binary');
+ assert.equal(written, 4);
+ assert.equal(buf[4], 0);
+}
+
+// Check for fractional length args, junk length args, etc.
+// https://github.com/joyent/node/issues/1758
+
+// Call .fill() first, stops valgrind warning about uninitialized memory reads.
+Buffer(3.3).fill().toString(); // throws bad argument error in commit 43cb4ec
+assert.equal(Buffer(NaN).length, 0);
+assert.equal(Buffer(3.3).length, 3);
+assert.equal(Buffer({length: 3.3}).length, 3);
+assert.equal(Buffer({length: 'BAM'}).length, 0);
+
+// Make sure that strings are not coerced to numbers.
+assert.equal(Buffer('99').length, 2);
+assert.equal(Buffer('13.37').length, 5);
+
+// Ensure that the length argument is respected.
+'ascii utf8 hex base64 latin1 binary'.split(' ').forEach(function(enc) {
+ assert.equal(Buffer(1).write('aaaaaa', 0, 1, enc), 1);
+});
+
+{
+ // Regression test, guard against buffer overrun in the base64 decoder.
+ var a = Buffer(3);
+ var b = Buffer('xxx');
+ a.write('aaaaaaaa', 'base64');
+ assert.equal(b.toString(), 'xxx');
+}
+
+// issue GH-3416
+Buffer(Buffer(0), 0, 0);
+
+[ 'hex',
+ 'utf8',
+ 'utf-8',
+ 'ascii',
+ 'latin1',
+ 'binary',
+ 'base64',
+ 'ucs2',
+ 'ucs-2',
+ 'utf16le',
+ 'utf-16le' ].forEach(function(enc) {
+ assert.equal(Buffer.isEncoding(enc), true);
+ });
+
+[ 'utf9',
+ 'utf-7',
+ 'Unicode-FTW',
+ 'new gnu gun' ].forEach(function(enc) {
+ assert.equal(Buffer.isEncoding(enc), false);
+ });
+
+
+// GH-5110
+{
+ var buffer = new Buffer('test');
+ var string = JSON.stringify(buffer);
+
+ assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}');
+
+ assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) {
+ return value && value.type === 'Buffer'
+ ? new Buffer(value.data)
+ : value;
+ }));
+}
+
+// issue GH-7849
+{
+ var buf = new Buffer('test');
+ var json = JSON.stringify(buf);
+ var obj = JSON.parse(json);
+ var copy = new Buffer(obj);
+
+ assert(buf.equals(copy));
+}
+
+// issue GH-4331
+assert.throws(function() {
+ Buffer(0xFFFFFFFF);
+}, RangeError);
+assert.throws(function() {
+ Buffer(0xFFFFFFFFF);
+}, RangeError);
+
+// issue GH-5587
+assert.throws(function() {
+ var buf = new Buffer(8);
+ buf.writeFloatLE(0, 5);
+}, RangeError);
+assert.throws(function() {
+ var buf = new Buffer(16);
+ buf.writeDoubleLE(0, 9);
+}, RangeError);
+
+
+// attempt to overflow buffers, similar to previous bug in array buffers
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.readFloatLE(0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.writeFloatLE(0.0, 0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.readFloatLE(0xffffffff);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.writeFloatLE(0.0, 0xffffffff);
+}, RangeError);
+
+
+// ensure negative values can't get past offset
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.readFloatLE(-1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.writeFloatLE(0.0, -1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.readFloatLE(-1);
+}, RangeError);
+
+assert.throws(function() {
+ var buf = Buffer(8);
+ buf.writeFloatLE(0.0, -1);
+}, RangeError);
+
+// offset checks
+{
+ var buf = new Buffer(0);
+
+ assert.throws(function() { buf.readUInt8(0); }, RangeError);
+ assert.throws(function() { buf.readInt8(0); }, RangeError);
+}
+
+{
+ var buf = new Buffer([0xFF]);
+
+ assert.equal(buf.readUInt8(0), 255);
+ assert.equal(buf.readInt8(0), -1);
+}
+
+[16, 32].forEach(function(bits) {
+ var buf = new Buffer(bits / 8 - 1);
+
+ assert.throws(function() { buf['readUInt' + bits + 'BE'](0); },
+ RangeError,
+ 'readUInt' + bits + 'BE');
+
+ assert.throws(function() { buf['readUInt' + bits + 'LE'](0); },
+ RangeError,
+ 'readUInt' + bits + 'LE');
+
+ assert.throws(function() { buf['readInt' + bits + 'BE'](0); },
+ RangeError,
+ 'readInt' + bits + 'BE()');
+
+ assert.throws(function() { buf['readInt' + bits + 'LE'](0); },
+ RangeError,
+ 'readInt' + bits + 'LE()');
+});
+
+[16, 32].forEach(function(bits) {
+ var buf = new Buffer([0xFF, 0xFF, 0xFF, 0xFF]);
+
+ assert.equal(buf['readUInt' + bits + 'BE'](0),
+ (0xFFFFFFFF >>> (32 - bits)));
+
+ assert.equal(buf['readUInt' + bits + 'LE'](0),
+ (0xFFFFFFFF >>> (32 - bits)));
+
+ assert.equal(buf['readInt' + bits + 'BE'](0),
+ (0xFFFFFFFF >> (32 - bits)));
+
+ assert.equal(buf['readInt' + bits + 'LE'](0),
+ (0xFFFFFFFF >> (32 - bits)));
+});
+
+// test for common read(U)IntLE/BE
+{
+ var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]);
+
+ assert.strictEqual(buf.readUIntLE(0, 1), 0x01);
+ assert.strictEqual(buf.readUIntBE(0, 1), 0x01);
+ assert.strictEqual(buf.readUIntLE(0, 3), 0x030201);
+ assert.strictEqual(buf.readUIntBE(0, 3), 0x010203);
+ assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201);
+ assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405);
+ assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201);
+ assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506);
+ assert.strictEqual(buf.readIntLE(0, 1), 0x01);
+ assert.strictEqual(buf.readIntBE(0, 1), 0x01);
+ assert.strictEqual(buf.readIntLE(0, 3), 0x030201);
+ assert.strictEqual(buf.readIntBE(0, 3), 0x010203);
+ assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201);
+ assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405);
+ assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201);
+ assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506);
+}
+
+// test for common write(U)IntLE/BE
+{
+ var buf = Buffer(3);
+ buf.writeUIntLE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
+ assert.equal(buf.readUIntLE(0, 3), 0x123456);
+
+ buf = Buffer(3);
+ buf.writeUIntBE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
+ assert.equal(buf.readUIntBE(0, 3), 0x123456);
+
+ buf = Buffer(3);
+ buf.writeIntLE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]);
+ assert.equal(buf.readIntLE(0, 3), 0x123456);
+
+ buf = Buffer(3);
+ buf.writeIntBE(0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56]);
+ assert.equal(buf.readIntBE(0, 3), 0x123456);
+
+ buf = Buffer(3);
+ buf.writeIntLE(-0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xaa, 0xcb, 0xed]);
+ assert.equal(buf.readIntLE(0, 3), -0x123456);
+
+ buf = Buffer(3);
+ buf.writeIntBE(-0x123456, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcb, 0xaa]);
+ assert.equal(buf.readIntBE(0, 3), -0x123456);
+
+ buf = Buffer(3);
+ buf.writeIntLE(-0x123400, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0xcc, 0xed]);
+ assert.equal(buf.readIntLE(0, 3), -0x123400);
+
+ buf = Buffer(3);
+ buf.writeIntBE(-0x123400, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcc, 0x00]);
+ assert.equal(buf.readIntBE(0, 3), -0x123400);
+
+ buf = Buffer(3);
+ buf.writeIntLE(-0x120000, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0x00, 0xee]);
+ assert.equal(buf.readIntLE(0, 3), -0x120000);
+
+ buf = Buffer(3);
+ buf.writeIntBE(-0x120000, 0, 3);
+ assert.deepStrictEqual(buf.toJSON().data, [0xee, 0x00, 0x00]);
+ assert.equal(buf.readIntBE(0, 3), -0x120000);
+
+ buf = Buffer(5);
+ buf.writeUIntLE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
+ assert.equal(buf.readUIntLE(0, 5), 0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeUIntBE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
+ assert.equal(buf.readUIntBE(0, 5), 0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeIntLE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x90, 0x78, 0x56, 0x34, 0x12]);
+ assert.equal(buf.readIntLE(0, 5), 0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeIntBE(0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x12, 0x34, 0x56, 0x78, 0x90]);
+ assert.equal(buf.readIntBE(0, 5), 0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeIntLE(-0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x70, 0x87, 0xa9, 0xcb, 0xed]);
+ assert.equal(buf.readIntLE(0, 5), -0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeIntBE(-0x1234567890, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0xed, 0xcb, 0xa9, 0x87, 0x70]);
+ assert.equal(buf.readIntBE(0, 5), -0x1234567890);
+
+ buf = Buffer(5);
+ buf.writeIntLE(-0x0012000000, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0x00, 0x00, 0x00, 0xee, 0xff]);
+ assert.equal(buf.readIntLE(0, 5), -0x0012000000);
+
+ buf = Buffer(5);
+ buf.writeIntBE(-0x0012000000, 0, 5);
+ assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]);
+ assert.equal(buf.readIntBE(0, 5), -0x0012000000);
+}
+
+// test Buffer slice
+{
+ var buf = new Buffer('0123456789');
+ assert.equal(buf.slice(-10, 10), '0123456789');
+ assert.equal(buf.slice(-20, 10), '0123456789');
+ assert.equal(buf.slice(-20, -10), '');
+ assert.equal(buf.slice(), '0123456789');
+ assert.equal(buf.slice(0), '0123456789');
+ assert.equal(buf.slice(0, 0), '');
+ assert.equal(buf.slice(undefined), '0123456789');
+ assert.equal(buf.slice('foobar'), '0123456789');
+ assert.equal(buf.slice(undefined, undefined), '0123456789');
+
+ assert.equal(buf.slice(2), '23456789');
+ assert.equal(buf.slice(5), '56789');
+ assert.equal(buf.slice(10), '');
+ assert.equal(buf.slice(5, 8), '567');
+ assert.equal(buf.slice(8, -1), '8');
+ assert.equal(buf.slice(-10), '0123456789');
+ assert.equal(buf.slice(0, -9), '0');
+ assert.equal(buf.slice(0, -10), '');
+ assert.equal(buf.slice(0, -1), '012345678');
+ assert.equal(buf.slice(2, -2), '234567');
+ assert.equal(buf.slice(0, 65536), '0123456789');
+ assert.equal(buf.slice(65536, 0), '');
+ assert.equal(buf.slice(-5, -8), '');
+ assert.equal(buf.slice(-5, -3), '56');
+ assert.equal(buf.slice(-10, 10), '0123456789');
+ for (var i = 0, s = buf.toString(); i < buf.length; ++i) {
+ assert.equal(buf.slice(i), s.slice(i));
+ assert.equal(buf.slice(0, i), s.slice(0, i));
+ assert.equal(buf.slice(-i), s.slice(-i));
+ assert.equal(buf.slice(0, -i), s.slice(0, -i));
+ }
+
+ var utf16Buf = new Buffer('0123456789', 'utf16le');
+ assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer('012', 'utf16le'));
+
+ assert.equal(buf.slice('0', '1'), '0');
+ assert.equal(buf.slice('-5', '10'), '56789');
+ assert.equal(buf.slice('-10', '10'), '0123456789');
+ assert.equal(buf.slice('-10', '-5'), '01234');
+ assert.equal(buf.slice('-10', '-0'), '');
+ assert.equal(buf.slice('111'), '');
+ assert.equal(buf.slice('0', '-111'), '');
+
+ // try to slice a zero length Buffer
+ // see https://github.com/joyent/node/issues/5881
+ SlowBuffer(0).slice(0, 1);
+}
+
+// Regression test for #5482: should throw but not assert in C++ land.
+assert.throws(function() {
+ Buffer('', 'buffer');
+}, TypeError);
+
+// Regression test for #6111. Constructing a buffer from another buffer
+// should a) work, and b) not corrupt the source buffer.
+{
+ var a = [0];
+ for (var i = 0; i < 7; ++i) a = a.concat(a);
+ a = a.map(function(_, i) { return i; });
+ var b = Buffer(a);
+ var c = Buffer(b);
+ assert.strictEqual(b.length, a.length);
+ assert.strictEqual(c.length, a.length);
+ for (var i = 0, k = a.length; i < k; ++i) {
+ assert.strictEqual(a[i], i);
+ assert.strictEqual(b[i], i);
+ assert.strictEqual(c[i], i);
+ }
+}
+
+
+assert.throws(function() {
+ new Buffer((-1 >>> 0) + 1);
+}, RangeError);
+
+assert.throws(function() {
+ SlowBuffer((-1 >>> 0) + 1);
+}, RangeError);
+
+if (common.hasCrypto) {
+ // Test truncation after decode
+ // var crypto = require('crypto');
+
+ var b1 = new Buffer('YW55=======', 'base64');
+ var b2 = new Buffer('YW55', 'base64');
+
+ assert.equal(
+ 1 /*crypto.createHash('sha1').update(b1).digest('hex')*/,
+ 1 /*crypto.createHash('sha1').update(b2).digest('hex')*/
+ );
+} else {
+ common.skip('missing crypto');
+}
+
+// Test Compare
+{
+ var b = new Buffer(1).fill('a');
+ var c = new Buffer(1).fill('c');
+ var d = new Buffer(2).fill('aa');
+
+ assert.equal(b.compare(c), -1);
+ assert.equal(c.compare(d), 1);
+ assert.equal(d.compare(b), 1);
+ assert.equal(b.compare(d), -1);
+ assert.equal(b.compare(b), 0);
+
+ assert.equal(Buffer.compare(b, c), -1);
+ assert.equal(Buffer.compare(c, d), 1);
+ assert.equal(Buffer.compare(d, b), 1);
+ assert.equal(Buffer.compare(b, d), -1);
+ assert.equal(Buffer.compare(c, c), 0);
+
+ assert.equal(Buffer.compare(Buffer(0), Buffer(0)), 0);
+ assert.equal(Buffer.compare(Buffer(0), Buffer(1)), -1);
+ assert.equal(Buffer.compare(Buffer(1), Buffer(0)), 1);
+}
+
+assert.throws(function() {
+ var b = Buffer(1);
+ Buffer.compare(b, 'abc');
+});
+
+assert.throws(function() {
+ var b = Buffer(1);
+ Buffer.compare('abc', b);
+});
+
+assert.throws(function() {
+ var b = Buffer(1);
+ b.compare('abc');
+});
+
+// Test Equals
+{
+ var b = new Buffer(5).fill('abcdf');
+ var c = new Buffer(5).fill('abcdf');
+ var d = new Buffer(5).fill('abcde');
+ var e = new Buffer(6).fill('abcdef');
+
+ assert.ok(b.equals(c));
+ assert.ok(!c.equals(d));
+ assert.ok(!d.equals(e));
+ assert.ok(d.equals(d));
+}
+
+assert.throws(function() {
+ var b = Buffer(1);
+ b.equals('abc');
+});
+
+// Regression test for https://github.com/nodejs/node/issues/649.
+assert.throws(function() { Buffer(1422561062959).toString('utf8'); });
+
+var ps = Buffer.poolSize;
+Buffer.poolSize = 0;
+assert.equal(Buffer(1).parent, undefined);
+Buffer.poolSize = ps;
+
+// Test Buffer.copy() segfault
+assert.throws(function() {
+ Buffer(10).copy();
+});
+
+var regErrorMsg = new RegExp('First argument must be a string, Buffer, ' +
+ 'ArrayBuffer, Array, or array-like object.');
+
+assert.throws(function() {
+ new Buffer();
+}, regErrorMsg);
+
+assert.throws(function() {
+ new Buffer(null);
+}, regErrorMsg);
+
+
+// Test prototype getters don't throw
+assert.equal(Buffer.prototype.parent, undefined);
+assert.equal(Buffer.prototype.offset, undefined);
+assert.equal(SlowBuffer.prototype.parent, undefined);
+assert.equal(SlowBuffer.prototype.offset, undefined);
+
+{
+ // Test that large negative Buffer length inputs don't affect the pool offset.
+ // Use the fromArrayLike() variant here because it's more lenient
+ // about its input and passes the length directly to allocate().
+ assert.deepStrictEqual(Buffer({ length: -Buffer.poolSize }), Buffer.from(''));
+ assert.deepStrictEqual(Buffer({ length: -100 }), Buffer.from(''));
+
+ // Check pool offset after that by trying to write string into the pool.
+ assert.doesNotThrow(() => Buffer.from('abc'));
+}
+
+
+// Test failed or zero-sized Buffer allocations not affecting typed arrays
+{
+ var zeroArray = new Uint32Array(10).fill(0);
+ var sizes = [1e10, 0, 0.1, -1, 'a', undefined, null, NaN];
+ var allocators = [
+ Buffer,
+ SlowBuffer,
+ Buffer.alloc,
+ Buffer.allocUnsafe,
+ Buffer.allocUnsafeSlow
+ ];
+ for (var allocator of allocators) {
+ for (var size of sizes) {
+ try {
+ allocator(size);
+ } catch (e) {
+ assert.deepStrictEqual(new Uint32Array(10), zeroArray);
+ }
+ }
+ }
+}
+
+// Test that large negative Buffer length inputs throw errors.
+assert.throws(() => Buffer(-Buffer.poolSize),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer(-100),
+ '"size" argument must not be negative');
+assert.throws(() => Buffer(-1),
+ '"size" argument must not be negative');
+
diff --git a/node_modules/buffer/test/slice.js b/node_modules/buffer/test/slice.js
new file mode 100644
index 0000000..25c111c
--- /dev/null
+++ b/node_modules/buffer/test/slice.js
@@ -0,0 +1,37 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('modifying buffer created by .slice() modifies original memory', function (t) {
+ if (!B.TYPED_ARRAY_SUPPORT) return t.end()
+
+ var buf1 = new B(26)
+ for (var i = 0; i < 26; i++) {
+ buf1[i] = i + 97 // 97 is ASCII a
+ }
+
+ var buf2 = buf1.slice(0, 3)
+ t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
+
+ buf2[0] = '!'.charCodeAt(0)
+ t.equal(buf1.toString('ascii', 0, buf2.length), '!bc')
+
+ t.end()
+})
+
+test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) {
+ if (!B.TYPED_ARRAY_SUPPORT) return t.end()
+
+ var buf1 = new B(26)
+ for (var i = 0; i < 26; i++) {
+ buf1[i] = i + 97 // 97 is ASCII a
+ }
+
+ var buf2 = buf1.slice(0, 3)
+ t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
+
+ buf1[0] = '!'.charCodeAt(0)
+ t.equal(buf2.toString('ascii', 0, buf2.length), '!bc')
+
+ t.end()
+})
diff --git a/node_modules/buffer/test/static.js b/node_modules/buffer/test/static.js
new file mode 100644
index 0000000..4de900b
--- /dev/null
+++ b/node_modules/buffer/test/static.js
@@ -0,0 +1,17 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('Buffer.isEncoding', function (t) {
+ t.equal(B.isEncoding('HEX'), true)
+ t.equal(B.isEncoding('hex'), true)
+ t.equal(B.isEncoding('bad'), false)
+ t.end()
+})
+
+test('Buffer.isBuffer', function (t) {
+ t.equal(B.isBuffer(new B('hey', 'utf8')), true)
+ t.equal(B.isBuffer(new B([1, 2, 3], 'utf8')), true)
+ t.equal(B.isBuffer('hey'), false)
+ t.end()
+})
diff --git a/node_modules/buffer/test/to-string.js b/node_modules/buffer/test/to-string.js
new file mode 100644
index 0000000..2950d4d
--- /dev/null
+++ b/node_modules/buffer/test/to-string.js
@@ -0,0 +1,233 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('utf8 buffer to base64', function (t) {
+ t.equal(
+ new B('Ձאab', 'utf8').toString('base64'),
+ '1YHXkGFi'
+ )
+ t.end()
+})
+
+test('utf8 buffer to hex', function (t) {
+ t.equal(
+ new B('Ձאab', 'utf8').toString('hex'),
+ 'd581d7906162'
+ )
+ t.end()
+})
+
+test('utf8 to utf8', function (t) {
+ t.equal(
+ new B('öäüõÖÄÜÕ', 'utf8').toString('utf8'),
+ 'öäüõÖÄÜÕ'
+ )
+ t.end()
+})
+
+test('utf16le to utf16', function (t) {
+ t.equal(
+ new B(new B('abcd', 'utf8').toString('utf16le'), 'utf16le').toString('utf8'),
+ 'abcd'
+ )
+ t.end()
+})
+
+test('utf16le to hex', function (t) {
+ t.equal(
+ new B('abcd', 'utf16le').toString('hex'),
+ '6100620063006400'
+ )
+ t.end()
+})
+
+test('ascii buffer to base64', function (t) {
+ t.equal(
+ new B('123456!@#$%^', 'ascii').toString('base64'),
+ 'MTIzNDU2IUAjJCVe'
+ )
+ t.end()
+})
+
+test('ascii buffer to hex', function (t) {
+ t.equal(
+ new B('123456!@#$%^', 'ascii').toString('hex'),
+ '31323334353621402324255e'
+ )
+ t.end()
+})
+
+test('base64 buffer to utf8', function (t) {
+ t.equal(
+ new B('1YHXkGFi', 'base64').toString('utf8'),
+ 'Ձאab'
+ )
+ t.end()
+})
+
+test('hex buffer to utf8', function (t) {
+ t.equal(
+ new B('d581d7906162', 'hex').toString('utf8'),
+ 'Ձאab'
+ )
+ t.end()
+})
+
+test('base64 buffer to ascii', function (t) {
+ t.equal(
+ new B('MTIzNDU2IUAjJCVe', 'base64').toString('ascii'),
+ '123456!@#$%^'
+ )
+ t.end()
+})
+
+test('hex buffer to ascii', function (t) {
+ t.equal(
+ new B('31323334353621402324255e', 'hex').toString('ascii'),
+ '123456!@#$%^'
+ )
+ t.end()
+})
+
+test('base64 buffer to binary', function (t) {
+ t.equal(
+ new B('MTIzNDU2IUAjJCVe', 'base64').toString('binary'),
+ '123456!@#$%^'
+ )
+ t.end()
+})
+
+test('hex buffer to binary', function (t) {
+ t.equal(
+ new B('31323334353621402324255e', 'hex').toString('binary'),
+ '123456!@#$%^'
+ )
+ t.end()
+})
+
+test('utf8 to binary', function (t) {
+ /* jshint -W100 */
+ t.equal(
+ new B('öäüõÖÄÜÕ', 'utf8').toString('binary'),
+ 'öäüõÃÃÃÃ'
+ )
+ /* jshint +W100 */
+ t.end()
+})
+
+test('utf8 replacement chars (1 byte sequence)', function (t) {
+ t.equal(
+ new B([ 0x80 ]).toString(),
+ '\uFFFD'
+ )
+ t.equal(
+ new B([ 0x7F ]).toString(),
+ '\u007F'
+ )
+ t.end()
+})
+
+test('utf8 replacement chars (2 byte sequences)', function (t) {
+ t.equal(
+ new B([ 0xC7 ]).toString(),
+ '\uFFFD'
+ )
+ t.equal(
+ new B([ 0xC7, 0xB1 ]).toString(),
+ '\u01F1'
+ )
+ t.equal(
+ new B([ 0xC0, 0xB1 ]).toString(),
+ '\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xC1, 0xB1 ]).toString(),
+ '\uFFFD\uFFFD'
+ )
+ t.end()
+})
+
+test('utf8 replacement chars (3 byte sequences)', function (t) {
+ t.equal(
+ new B([ 0xE0 ]).toString(),
+ '\uFFFD'
+ )
+ t.equal(
+ new B([ 0xE0, 0xAC ]).toString(),
+ '\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xE0, 0xAC, 0xB9 ]).toString(),
+ '\u0B39'
+ )
+ t.end()
+})
+
+test('utf8 replacement chars (4 byte sequences)', function (t) {
+ t.equal(
+ new B([ 0xF4 ]).toString(),
+ '\uFFFD'
+ )
+ t.equal(
+ new B([ 0xF4, 0x8F ]).toString(),
+ '\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xF4, 0x8F, 0x80 ]).toString(),
+ '\uFFFD\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xF4, 0x8F, 0x80, 0x84 ]).toString(),
+ '\uDBFC\uDC04'
+ )
+ t.equal(
+ new B([ 0xFF ]).toString(),
+ '\uFFFD'
+ )
+ t.equal(
+ new B([ 0xFF, 0x8F, 0x80, 0x84 ]).toString(),
+ '\uFFFD\uFFFD\uFFFD\uFFFD'
+ )
+ t.end()
+})
+
+test('utf8 replacement chars on 256 random bytes', function (t) {
+ t.equal(
+ new B([ 152, 130, 206, 23, 243, 238, 197, 44, 27, 86, 208, 36, 163, 184, 164, 21, 94, 242, 178, 46, 25, 26, 253, 178, 72, 147, 207, 112, 236, 68, 179, 190, 29, 83, 239, 147, 125, 55, 143, 19, 157, 68, 157, 58, 212, 224, 150, 39, 128, 24, 94, 225, 120, 121, 75, 192, 112, 19, 184, 142, 203, 36, 43, 85, 26, 147, 227, 139, 242, 186, 57, 78, 11, 102, 136, 117, 180, 210, 241, 92, 3, 215, 54, 167, 249, 1, 44, 225, 146, 86, 2, 42, 68, 21, 47, 238, 204, 153, 216, 252, 183, 66, 222, 255, 15, 202, 16, 51, 134, 1, 17, 19, 209, 76, 238, 38, 76, 19, 7, 103, 249, 5, 107, 137, 64, 62, 170, 57, 16, 85, 179, 193, 97, 86, 166, 196, 36, 148, 138, 193, 210, 69, 187, 38, 242, 97, 195, 219, 252, 244, 38, 1, 197, 18, 31, 246, 53, 47, 134, 52, 105, 72, 43, 239, 128, 203, 73, 93, 199, 75, 222, 220, 166, 34, 63, 236, 11, 212, 76, 243, 171, 110, 78, 39, 205, 204, 6, 177, 233, 212, 243, 0, 33, 41, 122, 118, 92, 252, 0, 157, 108, 120, 70, 137, 100, 223, 243, 171, 232, 66, 126, 111, 142, 33, 3, 39, 117, 27, 107, 54, 1, 217, 227, 132, 13, 166, 3, 73, 53, 127, 225, 236, 134, 219, 98, 214, 125, 148, 24, 64, 142, 111, 231, 194, 42, 150, 185, 10, 182, 163, 244, 19, 4, 59, 135, 16 ]).toString(),
+ '\uFFFD\uFFFD\uFFFD\u0017\uFFFD\uFFFD\uFFFD\u002C\u001B\u0056\uFFFD\u0024\uFFFD\uFFFD\uFFFD\u0015\u005E\uFFFD\uFFFD\u002E\u0019\u001A\uFFFD\uFFFD\u0048\uFFFD\uFFFD\u0070\uFFFD\u0044\uFFFD\uFFFD\u001D\u0053\uFFFD\uFFFD\u007D\u0037\uFFFD\u0013\uFFFD\u0044\uFFFD\u003A\uFFFD\uFFFD\uFFFD\u0027\uFFFD\u0018\u005E\uFFFD\u0078\u0079\u004B\uFFFD\u0070\u0013\uFFFD\uFFFD\uFFFD\u0024\u002B\u0055\u001A\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u0039\u004E\u000B\u0066\uFFFD\u0075\uFFFD\uFFFD\uFFFD\u005C\u0003\uFFFD\u0036\uFFFD\uFFFD\u0001\u002C\uFFFD\uFFFD\u0056\u0002\u002A\u0044\u0015\u002F\uFFFD\u0319\uFFFD\uFFFD\uFFFD\u0042\uFFFD\uFFFD\u000F\uFFFD\u0010\u0033\uFFFD\u0001\u0011\u0013\uFFFD\u004C\uFFFD\u0026\u004C\u0013\u0007\u0067\uFFFD\u0005\u006B\uFFFD\u0040\u003E\uFFFD\u0039\u0010\u0055\uFFFD\uFFFD\u0061\u0056\uFFFD\uFFFD\u0024\uFFFD\uFFFD\uFFFD\uFFFD\u0045\uFFFD\u0026\uFFFD\u0061\uFFFD\uFFFD\uFFFD\uFFFD\u0026\u0001\uFFFD\u0012\u001F\uFFFD\u0035\u002F\uFFFD\u0034\u0069\u0048\u002B\uFFFD\uFFFD\uFFFD\u0049\u005D\uFFFD\u004B\uFFFD\u0726\u0022\u003F\uFFFD\u000B\uFFFD\u004C\uFFFD\uFFFD\u006E\u004E\u0027\uFFFD\uFFFD\u0006\uFFFD\uFFFD\uFFFD\uFFFD\u0000\u0021\u0029\u007A\u0076\u005C\uFFFD\u0000\uFFFD\u006C\u0078\u0046\uFFFD\u0064\uFFFD\uFFFD\uFFFD\uFFFD\u0042\u007E\u006F\uFFFD\u0021\u0003\u0027\u0075\u001B\u006B\u0036\u0001\uFFFD\uFFFD\uFFFD\u000D\uFFFD\u0003\u0049\u0035\u007F\uFFFD\uFFFD\uFFFD\uFFFD\u0062\uFFFD\u007D\uFFFD\u0018\u0040\uFFFD\u006F\uFFFD\uFFFD\u002A\uFFFD\uFFFD\u000A\uFFFD\uFFFD\uFFFD\u0013\u0004\u003B\uFFFD\u0010'
+ )
+ t.end()
+})
+
+test('utf8 replacement chars for anything in the surrogate pair range', function (t) {
+ t.equal(
+ new B([ 0xED, 0x9F, 0xBF ]).toString(),
+ '\uD7FF'
+ )
+ t.equal(
+ new B([ 0xED, 0xA0, 0x80 ]).toString(),
+ '\uFFFD\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xED, 0xBE, 0x8B ]).toString(),
+ '\uFFFD\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xED, 0xBF, 0xBF ]).toString(),
+ '\uFFFD\uFFFD\uFFFD'
+ )
+ t.equal(
+ new B([ 0xEE, 0x80, 0x80 ]).toString(),
+ '\uE000'
+ )
+ t.end()
+})
+
+test('utf8 don\'t replace the replacement char', function (t) {
+ t.equal(
+ new B('\uFFFD').toString(),
+ '\uFFFD'
+ )
+ t.end()
+})
diff --git a/node_modules/buffer/test/write.js b/node_modules/buffer/test/write.js
new file mode 100644
index 0000000..5841806
--- /dev/null
+++ b/node_modules/buffer/test/write.js
@@ -0,0 +1,131 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+var isnan = require('is-nan')
+
+test('buffer.write string should get parsed as number', function (t) {
+ var b = new B(64)
+ b.writeUInt16LE('1003', 0)
+ t.equal(b.readUInt16LE(0), 1003)
+ t.end()
+})
+
+test('buffer.writeUInt8 a fractional number will get Math.floored', function (t) {
+ // Some extra work is necessary to make this test pass with the Object implementation
+
+ var b = new B(1)
+ b.writeInt8(5.5, 0)
+ t.equal(b[0], 5)
+ t.end()
+})
+
+test('writeUint8 with a negative number throws', function (t) {
+ var buf = new B(1)
+
+ t.throws(function () {
+ buf.writeUInt8(-3, 0)
+ })
+
+ t.end()
+})
+
+test('hex of write{Uint,Int}{8,16,32}{LE,BE}', function (t) {
+ t.plan(2 * (2 * 2 * 2 + 2))
+ var hex = [
+ '03', '0300', '0003', '03000000', '00000003',
+ 'fd', 'fdff', 'fffd', 'fdffffff', 'fffffffd'
+ ]
+ var reads = [ 3, 3, 3, 3, 3, -3, -3, -3, -3, -3 ]
+ var xs = ['UInt', 'Int']
+ var ys = [8, 16, 32]
+ for (var i = 0; i < xs.length; i++) {
+ var x = xs[i]
+ for (var j = 0; j < ys.length; j++) {
+ var y = ys[j]
+ var endianesses = (y === 8) ? [''] : ['LE', 'BE']
+ for (var k = 0; k < endianesses.length; k++) {
+ var z = endianesses[k]
+
+ var v1 = new B(y / 8)
+ var writefn = 'write' + x + y + z
+ var val = (x === 'Int') ? -3 : 3
+ v1[writefn](val, 0)
+ t.equal(
+ v1.toString('hex'),
+ hex.shift()
+ )
+ var readfn = 'read' + x + y + z
+ t.equal(
+ v1[readfn](0),
+ reads.shift()
+ )
+ }
+ }
+ }
+ t.end()
+})
+
+test('hex of write{Uint,Int}{8,16,32}{LE,BE} with overflow', function (t) {
+ if (!B.TYPED_ARRAY_SUPPORT) {
+ t.pass('object impl: skipping overflow test')
+ t.end()
+ return
+ }
+
+ t.plan(3 * (2 * 2 * 2 + 2))
+ var hex = [
+ '', '03', '00', '030000', '000000',
+ '', 'fd', 'ff', 'fdffff', 'ffffff'
+ ]
+ var reads = [
+ undefined, 3, 0, NaN, 0,
+ undefined, 253, -256, 16777213, -256
+ ]
+ var xs = ['UInt', 'Int']
+ var ys = [8, 16, 32]
+ for (var i = 0; i < xs.length; i++) {
+ var x = xs[i]
+ for (var j = 0; j < ys.length; j++) {
+ var y = ys[j]
+ var endianesses = (y === 8) ? [''] : ['LE', 'BE']
+ for (var k = 0; k < endianesses.length; k++) {
+ var z = endianesses[k]
+
+ var v1 = new B(y / 8 - 1)
+ var next = new B(4)
+ next.writeUInt32BE(0, 0)
+ var writefn = 'write' + x + y + z
+ var val = (x === 'Int') ? -3 : 3
+ v1[writefn](val, 0, true)
+ t.equal(
+ v1.toString('hex'),
+ hex.shift()
+ )
+ // check that nothing leaked to next buffer.
+ t.equal(next.readUInt32BE(0), 0)
+ // check that no bytes are read from next buffer.
+ next.writeInt32BE(~0, 0)
+ var readfn = 'read' + x + y + z
+ var r = reads.shift()
+ if (isnan(r)) t.pass('equal')
+ else t.equal(v1[readfn](0, true), r)
+ }
+ }
+ }
+ t.end()
+})
+test('large values do not improperly roll over (ref #80)', function (t) {
+ var nums = [-25589992, -633756690, -898146932]
+ var out = new B(12)
+ out.fill(0)
+ out.writeInt32BE(nums[0], 0)
+ var newNum = out.readInt32BE(0)
+ t.equal(nums[0], newNum)
+ out.writeInt32BE(nums[1], 4)
+ newNum = out.readInt32BE(4)
+ t.equal(nums[1], newNum)
+ out.writeInt32BE(nums[2], 8)
+ newNum = out.readInt32BE(8)
+ t.equal(nums[2], newNum)
+ t.end()
+})
diff --git a/node_modules/buffer/test/write_infinity.js b/node_modules/buffer/test/write_infinity.js
new file mode 100644
index 0000000..17d606a
--- /dev/null
+++ b/node_modules/buffer/test/write_infinity.js
@@ -0,0 +1,45 @@
+if (process.env.OBJECT_IMPL) global.TYPED_ARRAY_SUPPORT = false
+var B = require('../').Buffer
+var test = require('tape')
+
+test('write/read Infinity as a float', function (t) {
+ var buf = new B(4)
+ t.equal(buf.writeFloatBE(Infinity, 0), 4)
+ t.equal(buf.readFloatBE(0), Infinity)
+ t.end()
+})
+
+test('write/read -Infinity as a float', function (t) {
+ var buf = new B(4)
+ t.equal(buf.writeFloatBE(-Infinity, 0), 4)
+ t.equal(buf.readFloatBE(0), -Infinity)
+ t.end()
+})
+
+test('write/read Infinity as a double', function (t) {
+ var buf = new B(8)
+ t.equal(buf.writeDoubleBE(Infinity, 0), 8)
+ t.equal(buf.readDoubleBE(0), Infinity)
+ t.end()
+})
+
+test('write/read -Infinity as a double', function (t) {
+ var buf = new B(8)
+ t.equal(buf.writeDoubleBE(-Infinity, 0), 8)
+ t.equal(buf.readDoubleBE(0), -Infinity)
+ t.end()
+})
+
+test('write/read float greater than max', function (t) {
+ var buf = new B(4)
+ t.equal(buf.writeFloatBE(4e38, 0), 4)
+ t.equal(buf.readFloatBE(0), Infinity)
+ t.end()
+})
+
+test('write/read float less than min', function (t) {
+ var buf = new B(4)
+ t.equal(buf.writeFloatBE(-4e40, 0), 4)
+ t.equal(buf.readFloatBE(0), -Infinity)
+ t.end()
+})
diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md
new file mode 100644
index 0000000..56932a4
--- /dev/null
+++ b/node_modules/bytes/History.md
@@ -0,0 +1,70 @@
+2.4.0 / 2016-06-01
+==================
+
+ * Add option "unitSeparator"
+
+2.3.0 / 2016-02-15
+==================
+
+ * Drop partial bytes on all parsed units
+ * Fix non-finite numbers to `.format` to return `null`
+ * Fix parsing byte string that looks like hex
+ * perf: hoist regular expressions
+
+2.2.0 / 2015-11-13
+==================
+
+ * add option "decimalPlaces"
+ * add option "fixedDecimals"
+
+2.1.0 / 2015-05-21
+==================
+
+ * add `.format` export
+ * add `.parse` export
+
+2.0.2 / 2015-05-20
+==================
+
+ * remove map recreation
+ * remove unnecessary object construction
+
+2.0.1 / 2015-05-07
+==================
+
+ * fix browserify require
+ * remove node.extend dependency
+
+2.0.0 / 2015-04-12
+==================
+
+ * add option "case"
+ * add option "thousandsSeparator"
+ * return "null" on invalid parse input
+ * support proper round-trip: bytes(bytes(num)) === num
+ * units no longer case sensitive when parsing
+
+1.0.0 / 2014-05-05
+==================
+
+ * add negative support. fixes #6
+
+0.3.0 / 2014-03-19
+==================
+
+ * added terabyte support
+
+0.2.1 / 2013-04-01
+==================
+
+ * add .component
+
+0.2.0 / 2012-10-28
+==================
+
+ * bytes(200).should.eql('200b')
+
+0.1.0 / 2012-07-04
+==================
+
+ * add bytes to string conversion [yields]
diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE
new file mode 100644
index 0000000..63e95a9
--- /dev/null
+++ b/node_modules/bytes/LICENSE
@@ -0,0 +1,23 @@
+(The MIT License)
+
+Copyright (c) 2012-2014 TJ Holowaychuk
+Copyright (c) 2015 Jed Watson
+
+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/bytes/Readme.md b/node_modules/bytes/Readme.md
new file mode 100644
index 0000000..7465fde
--- /dev/null
+++ b/node_modules/bytes/Readme.md
@@ -0,0 +1,114 @@
+# Bytes utility
+
+[![NPM Version][npm-image]][npm-url]
+[![NPM Downloads][downloads-image]][downloads-url]
+[![Build Status][travis-image]][travis-url]
+
+Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa.
+
+## Usage
+
+```js
+var bytes = require('bytes');
+```
+
+#### bytes.format(number value, [options]): string|null
+
+Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is
+ rounded.
+
+**Arguments**
+
+| Name | Type | Description |
+|---------|--------|--------------------|
+| value | `number` | Value in bytes |
+| options | `Object` | Conversion options |
+
+**Options**
+
+| Property | Type | Description |
+|-------------------|--------|-----------------------------------------------------------------------------------------|
+| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. |
+| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` |
+| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `' '`. |
+| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. |
+
+**Returns**
+
+| Name | Type | Description |
+|---------|-------------|-------------------------|
+| results | `string`|`null` | Return null upon error. String value otherwise. |
+
+**Example**
+
+```js
+bytes(1024);
+// output: '1kB'
+
+bytes(1000);
+// output: '1000B'
+
+bytes(1000, {thousandsSeparator: ' '});
+// output: '1 000B'
+
+bytes(1024 * 1.7, {decimalPlaces: 0});
+// output: '2kB'
+
+bytes(1024, {unitSeparator: ' '});
+// output: '1 kB'
+
+```
+
+#### bytes.parse(string value): number|null
+
+Parse the string value into an integer in bytes. If no unit is given, it is assumed the value is in bytes.
+
+Supported units and abbreviations are as follows and are case-insensitive:
+
+ * "b" for bytes
+ * "kb" for kilobytes
+ * "mb" for megabytes
+ * "gb" for gigabytes
+ * "tb" for terabytes
+
+The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.
+
+**Arguments**
+
+| Name | Type | Description |
+|---------------|--------|--------------------|
+| value | `string` | String to parse. |
+
+**Returns**
+
+| Name | Type | Description |
+|---------|-------------|-------------------------|
+| results | `number`|`null` | Return null upon error. Value in bytes otherwise. |
+
+**Example**
+
+```js
+bytes('1kB');
+// output: 1024
+
+bytes('1024');
+// output: 1024
+```
+
+## Installation
+
+```bash
+npm install bytes --save
+component install visionmedia/bytes.js
+```
+
+## License
+
+[![npm](https://img.shields.io/npm/l/express.svg)](https://github.com/visionmedia/bytes.js/blob/master/LICENSE)
+
+[downloads-image]: https://img.shields.io/npm/dm/bytes.svg
+[downloads-url]: https://npmjs.org/package/bytes
+[npm-image]: https://img.shields.io/npm/v/bytes.svg
+[npm-url]: https://npmjs.org/package/bytes
+[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg
+[travis-url]: https://travis-ci.org/visionmedia/bytes.js
diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js
new file mode 100644
index 0000000..aa24231
--- /dev/null
+++ b/node_modules/bytes/index.js
@@ -0,0 +1,157 @@
+/*!
+ * bytes
+ * Copyright(c) 2012-2014 TJ Holowaychuk
+ * Copyright(c) 2015 Jed Watson
+ * MIT Licensed
+ */
+
+'use strict';
+
+/**
+ * Module exports.
+ * @public
+ */
+
+module.exports = bytes;
+module.exports.format = format;
+module.exports.parse = parse;
+
+/**
+ * Module variables.
+ * @private
+ */
+
+var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
+
+var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
+
+var map = {
+ b: 1,
+ kb: 1 << 10,
+ mb: 1 << 20,
+ gb: 1 << 30,
+ tb: ((1 << 30) * 1024)
+};
+
+// TODO: use is-finite module?
+var numberIsFinite = Number.isFinite || function (v) { return typeof v === 'number' && isFinite(v); };
+
+var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i;
+
+/**
+ * Convert the given value in bytes into a string or parse to string to an integer in bytes.
+ *
+ * @param {string|number} value
+ * @param {{
+ * case: [string],
+ * decimalPlaces: [number]
+ * fixedDecimals: [boolean]
+ * thousandsSeparator: [string]
+ * unitSeparator: [string]
+ * }} [options] bytes options.
+ *
+ * @returns {string|number|null}
+ */
+
+function bytes(value, options) {
+ if (typeof value === 'string') {
+ return parse(value);
+ }
+
+ if (typeof value === 'number') {
+ return format(value, options);
+ }
+
+ return null;
+}
+
+/**
+ * Format the given value in bytes into a string.
+ *
+ * If the value is negative, it is kept as such. If it is a float,
+ * it is rounded.
+ *
+ * @param {number} value
+ * @param {object} [options]
+ * @param {number} [options.decimalPlaces=2]
+ * @param {number} [options.fixedDecimals=false]
+ * @param {string} [options.thousandsSeparator=]
+ * @param {string} [options.unitSeparator=]
+ *
+ * @returns {string|null}
+ * @public
+ */
+
+function format(value, options) {
+ if (!numberIsFinite(value)) {
+ return null;
+ }
+
+ var mag = Math.abs(value);
+ var thousandsSeparator = (options && options.thousandsSeparator) || '';
+ var unitSeparator = (options && options.unitSeparator) || '';
+ var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
+ var fixedDecimals = Boolean(options && options.fixedDecimals);
+ var unit = 'B';
+
+ if (mag >= map.tb) {
+ unit = 'TB';
+ } else if (mag >= map.gb) {
+ unit = 'GB';
+ } else if (mag >= map.mb) {
+ unit = 'MB';
+ } else if (mag >= map.kb) {
+ unit = 'kB';
+ }
+
+ var val = value / map[unit.toLowerCase()];
+ var str = val.toFixed(decimalPlaces);
+
+ if (!fixedDecimals) {
+ str = str.replace(formatDecimalsRegExp, '$1');
+ }
+
+ if (thousandsSeparator) {
+ str = str.replace(formatThousandsRegExp, thousandsSeparator);
+ }
+
+ return str + unitSeparator + unit;
+}
+
+/**
+ * Parse the string value into an integer in bytes.
+ *
+ * If no unit is given, it is assumed the value is in bytes.
+ *
+ * @param {number|string} val
+ *
+ * @returns {number|null}
+ * @public
+ */
+
+function parse(val) {
+ if (typeof val === 'number' && !isNaN(val)) {
+ return val;
+ }
+
+ if (typeof val !== 'string') {
+ return null;
+ }
+
+ // Test if the string passed is valid
+ var results = parseRegExp.exec(val);
+ var floatValue;
+ var unit = 'b';
+
+ if (!results) {
+ // Nothing could be extracted from the given string
+ floatValue = parseInt(val, 10);
+ unit = 'b'
+ } else {
+ // Retrieve the value and the unit
+ floatValue = parseFloat(results[1]);
+ unit = results[4].toLowerCase();
+ }
+
+ return Math.floor(map[unit] * floatValue);
+}
diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json
new file mode 100644
index 0000000..fc289ba
--- /dev/null
+++ b/node_modules/bytes/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "bytes",
+ "description": "Utility to parse a string bytes to bytes and vice-versa",
+ "version": "2.4.0",
+ "author": "TJ Holowaychuk (http://tjholowaychuk.com)",
+ "contributors": [
+ "Jed Watson ",
+ "Théo FIDRY "
+ ],
+ "license": "MIT",
+ "keywords": [
+ "byte",
+ "bytes",
+ "utility",
+ "parse",
+ "parser",
+ "convert",
+ "converter"
+ ],
+ "repository": "visionmedia/bytes.js",
+ "component": {
+ "scripts": {
+ "bytes/index.js": "index.js"
+ }
+ },
+ "devDependencies": {
+ "mocha": "1.21.5"
+ },
+ "files": [
+ "History.md",
+ "LICENSE",
+ "Readme.md",
+ "index.js"
+ ],
+ "scripts": {
+ "test": "mocha --check-leaks --reporter spec"
+ }
+}
diff --git a/node_modules/camelcase/index.js b/node_modules/camelcase/index.js
new file mode 100644
index 0000000..b46e100
--- /dev/null
+++ b/node_modules/camelcase/index.js
@@ -0,0 +1,27 @@
+'use strict';
+module.exports = function () {
+ var str = [].map.call(arguments, function (str) {
+ return str.trim();
+ }).filter(function (str) {
+ return str.length;
+ }).join('-');
+
+ if (!str.length) {
+ return '';
+ }
+
+ if (str.length === 1 || !(/[_.\- ]+/).test(str) ) {
+ if (str[0] === str[0].toLowerCase() && str.slice(1) !== str.slice(1).toLowerCase()) {
+ return str;
+ }
+
+ return str.toLowerCase();
+ }
+
+ return str
+ .replace(/^[_.\- ]+/, '')
+ .toLowerCase()
+ .replace(/[_.\- ]+(\w|$)/g, function (m, p1) {
+ return p1.toUpperCase();
+ });
+};
diff --git a/node_modules/camelcase/license b/node_modules/camelcase/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/camelcase/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus (sindresorhus.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/camelcase/package.json b/node_modules/camelcase/package.json
new file mode 100644
index 0000000..34f75e7
--- /dev/null
+++ b/node_modules/camelcase/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "camelcase",
+ "version": "1.2.1",
+ "description": "Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar",
+ "license": "MIT",
+ "repository": "sindresorhus/camelcase",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "http://sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "node test.js"
+ },
+ "files": [
+ "index.js"
+ ],
+ "keywords": [
+ "camelcase",
+ "camel-case",
+ "camel",
+ "case",
+ "dash",
+ "hyphen",
+ "dot",
+ "underscore",
+ "separator",
+ "string",
+ "text",
+ "convert"
+ ],
+ "devDependencies": {
+ "ava": "0.0.4"
+ }
+}
diff --git a/node_modules/camelcase/readme.md b/node_modules/camelcase/readme.md
new file mode 100644
index 0000000..516dc39
--- /dev/null
+++ b/node_modules/camelcase/readme.md
@@ -0,0 +1,56 @@
+# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase)
+
+> Convert a dash/dot/underscore/space separated string to camelCase: `foo-bar` → `fooBar`
+
+
+## Install
+
+```sh
+$ npm install --save camelcase
+```
+
+
+## Usage
+
+```js
+var camelCase = require('camelcase');
+
+camelCase('foo-bar');
+//=> fooBar
+
+camelCase('foo_bar');
+//=> fooBar
+
+camelCase('Foo-Bar');
+//=> fooBar
+
+camelCase('--foo.bar');
+//=> fooBar
+
+camelCase('__foo__bar__');
+//=> fooBar
+
+camelCase('foo bar');
+//=> fooBar
+
+console.log(process.argv[3]);
+//=> --foo-bar
+camelCase(process.argv[3]);
+//=> fooBar
+
+camelCase('foo', 'bar');
+//=> fooBar
+
+camelCase('__foo__', '--bar');
+//=> fooBar
+```
+
+
+## Related
+
+See [`decamelize`](https://github.com/sindresorhus/decamelize) for the inverse.
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/node_modules/caseless/LICENSE b/node_modules/caseless/LICENSE
new file mode 100644
index 0000000..61789f4
--- /dev/null
+++ b/node_modules/caseless/LICENSE
@@ -0,0 +1,28 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+1. Definitions.
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+You must give any other recipients of the Work or Derivative Works a copy of this License; and
+You must cause any modified files to carry prominent notices stating that You changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/node_modules/caseless/README.md b/node_modules/caseless/README.md
new file mode 100644
index 0000000..e5077a2
--- /dev/null
+++ b/node_modules/caseless/README.md
@@ -0,0 +1,45 @@
+## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing.
+
+This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set.
+
+## Usage
+
+```javascript
+var headers = {}
+ , c = caseless(headers)
+ ;
+c.set('a-Header', 'asdf')
+c.get('a-header') === 'asdf'
+```
+
+## has(key)
+
+Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with.
+
+```javascript
+c.has('a-header') === 'a-Header'
+```
+
+## set(key, value[, clobber=true])
+
+Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header.
+
+```javascript
+c.set('a-Header', 'fdas')
+c.set('a-HEADER', 'more', false)
+c.get('a-header') === 'fdsa,more'
+```
+
+## swap(key)
+
+Swaps the casing of a header with the new one that is passed in.
+
+```javascript
+var headers = {}
+ , c = caseless(headers)
+ ;
+c.set('a-Header', 'fdas')
+c.swap('a-HEADER')
+c.has('a-header') === 'a-HEADER'
+headers === {'a-HEADER': 'fdas'}
+```
diff --git a/node_modules/caseless/index.js b/node_modules/caseless/index.js
new file mode 100644
index 0000000..d86a70e
--- /dev/null
+++ b/node_modules/caseless/index.js
@@ -0,0 +1,66 @@
+function Caseless (dict) {
+ this.dict = dict || {}
+}
+Caseless.prototype.set = function (name, value, clobber) {
+ if (typeof name === 'object') {
+ for (var i in name) {
+ this.set(i, name[i], value)
+ }
+ } else {
+ if (typeof clobber === 'undefined') clobber = true
+ var has = this.has(name)
+
+ if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
+ else this.dict[has || name] = value
+ return has
+ }
+}
+Caseless.prototype.has = function (name) {
+ var keys = Object.keys(this.dict)
+ , name = name.toLowerCase()
+ ;
+ for (var i=0;i",
+ "license": "Apache-2.0",
+ "bugs": {
+ "url": "https://github.com/mikeal/caseless/issues"
+ },
+ "devDependencies": {
+ "tape": "^2.10.2"
+ }
+}
diff --git a/node_modules/caseless/test.js b/node_modules/caseless/test.js
new file mode 100644
index 0000000..084bbaf
--- /dev/null
+++ b/node_modules/caseless/test.js
@@ -0,0 +1,40 @@
+var tape = require('tape')
+ , caseless = require('./')
+ ;
+
+tape('set get has', function (t) {
+ var headers = {}
+ , c = caseless(headers)
+ ;
+ t.plan(17)
+ c.set('a-Header', 'asdf')
+ t.equal(c.get('a-header'), 'asdf')
+ t.equal(c.has('a-header'), 'a-Header')
+ t.ok(!c.has('nothing'))
+ // old bug where we used the wrong regex
+ t.ok(!c.has('a-hea'))
+ c.set('a-header', 'fdsa')
+ t.equal(c.get('a-header'), 'fdsa')
+ t.equal(c.get('a-Header'), 'fdsa')
+ c.set('a-HEADER', 'more', false)
+ t.equal(c.get('a-header'), 'fdsa,more')
+
+ t.deepEqual(headers, {'a-Header': 'fdsa,more'})
+ c.swap('a-HEADER')
+ t.deepEqual(headers, {'a-HEADER': 'fdsa,more'})
+
+ c.set('deleteme', 'foobar')
+ t.ok(c.has('deleteme'))
+ t.ok(c.del('deleteme'))
+ t.notOk(c.has('deleteme'))
+ t.notOk(c.has('idonotexist'))
+ t.ok(c.del('idonotexist'))
+
+ c.set('tva', 'test1')
+ c.set('tva-header', 'test2')
+ t.equal(c.has('tva'), 'tva')
+ t.notOk(c.has('header'))
+
+ t.equal(c.get('tva'), 'test1')
+
+})
diff --git a/node_modules/center-align/LICENSE b/node_modules/center-align/LICENSE
new file mode 100644
index 0000000..65f90ac
--- /dev/null
+++ b/node_modules/center-align/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015, Jon Schlinkert.
+
+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/center-align/README.md b/node_modules/center-align/README.md
new file mode 100644
index 0000000..cbcf3be
--- /dev/null
+++ b/node_modules/center-align/README.md
@@ -0,0 +1,74 @@
+# center-align [![NPM version](https://badge.fury.io/js/center-align.svg)](http://badge.fury.io/js/center-align)
+
+> Center-align the text in a string.
+
+Install with [npm](https://www.npmjs.com/)
+
+```sh
+$ npm i center-align --save
+```
+
+## Usage
+
+```js
+var centerAlign = require('center-align');
+```
+
+**Example**
+
+If used on the following:
+
+```
+Lorem ipsum dolor sit amet,
+consectetur adipiscing
+elit, sed do eiusmod tempor incididunt
+ut labore et dolore
+magna aliqua. Ut enim ad minim
+veniam, quis
+```
+
+The result would be:
+
+```
+ Lorem ipsum dolor sit amet,
+ consectetur adipiscing
+elit, sed do eiusmod tempor incididunt
+ ut labore et dolore
+ magna aliqua. Ut enim ad minim
+ veniam, quis
+```
+
+## Related projects
+
+* [align-text](https://www.npmjs.com/package/align-text): Align the text in a string. | [homepage](https://github.com/jonschlinkert/align-text)
+* [justified](https://www.npmjs.com/package/justified): Wrap words to a specified length and justified the text. | [homepage](https://github.com/jonschlinkert/justified)
+* [right-align](https://www.npmjs.com/package/right-align): Right-align the text in a string. | [homepage](https://github.com/jonschlinkert/right-align)
+* [word-wrap](https://www.npmjs.com/package/word-wrap): Wrap words to a specified length. | [homepage](https://github.com/jonschlinkert/word-wrap)
+
+## Running tests
+
+Install dev dependencies:
+
+```sh
+$ npm i -d && npm test
+```
+
+## Contributing
+
+Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/center-align/issues/new).
+
+## Author
+
+**Jon Schlinkert**
+
++ [github/jonschlinkert](https://github.com/jonschlinkert)
++ [twitter/jonschlinkert](http://twitter.com/jonschlinkert)
+
+## License
+
+Copyright © 2015 Jon Schlinkert
+Released under the MIT license.
+
+***
+
+_This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on October 27, 2015._
\ No newline at end of file
diff --git a/node_modules/center-align/index.js b/node_modules/center-align/index.js
new file mode 100644
index 0000000..c6ed54a
--- /dev/null
+++ b/node_modules/center-align/index.js
@@ -0,0 +1,16 @@
+/*!
+ * center-align
+ *
+ * Copycenter (c) 2015, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+
+'use strict';
+
+var utils = require('./utils');
+
+module.exports = function centerAlign(val) {
+ return utils.align(val, function (len, longest) {
+ return Math.floor((longest - len) / 2);
+ });
+};
diff --git a/node_modules/center-align/package.json b/node_modules/center-align/package.json
new file mode 100644
index 0000000..eee07ee
--- /dev/null
+++ b/node_modules/center-align/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "center-align",
+ "description": "Center-align the text in a string.",
+ "version": "0.1.3",
+ "homepage": "https://github.com/jonschlinkert/center-align",
+ "author": "Jon Schlinkert (https://github.com/jonschlinkert)",
+ "repository": "jonschlinkert/center-align",
+ "bugs": {
+ "url": "https://github.com/jonschlinkert/center-align/issues"
+ },
+ "license": "MIT",
+ "files": [
+ "index.js",
+ "utils.js"
+ ],
+ "main": "index.js",
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "mocha"
+ },
+ "dependencies": {
+ "align-text": "^0.1.3",
+ "lazy-cache": "^1.0.3"
+ },
+ "devDependencies": {
+ "mocha": "^2.2.0"
+ },
+ "keywords": [
+ "align",
+ "align-center",
+ "center",
+ "center-align",
+ "right",
+ "right-align",
+ "text",
+ "typography"
+ ],
+ "verb": {
+ "related": {
+ "description": "",
+ "list": [
+ "align-text",
+ "right-align",
+ "justified",
+ "word-wrap"
+ ]
+ }
+ }
+}
diff --git a/node_modules/center-align/utils.js b/node_modules/center-align/utils.js
new file mode 100644
index 0000000..aead6d2
--- /dev/null
+++ b/node_modules/center-align/utils.js
@@ -0,0 +1,40 @@
+'use strict';
+
+/**
+ * Lazily-required module dependencies (makes the application
+ * faster)
+ */
+
+var utils = require('lazy-cache')(require);
+
+/**
+ * Temporarily re-assign `require` to trick browserify and
+ * webpack into reconizing lazy dependencies.
+ *
+ * This tiny bit of ugliness has the huge dual advantage of
+ * only loading modules that are actually called at some
+ * point in the lifecycle of the application, whilst also
+ * allowing browserify and webpack to find modules that
+ * are depended on but never actually called.
+ */
+
+var fn = require;
+require = utils;
+
+/**
+ * Lazily required module dependencies
+ */
+
+require('align-text', 'align');
+
+/**
+ * Restore `require`
+ */
+
+require = fn;
+
+/**
+ * Expose `utils` modules
+ */
+
+module.exports = utils;
diff --git a/node_modules/chalk/index.js b/node_modules/chalk/index.js
new file mode 100644
index 0000000..2d85a91
--- /dev/null
+++ b/node_modules/chalk/index.js
@@ -0,0 +1,116 @@
+'use strict';
+var escapeStringRegexp = require('escape-string-regexp');
+var ansiStyles = require('ansi-styles');
+var stripAnsi = require('strip-ansi');
+var hasAnsi = require('has-ansi');
+var supportsColor = require('supports-color');
+var defineProps = Object.defineProperties;
+var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
+
+function Chalk(options) {
+ // detect mode if not set manually
+ this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
+}
+
+// use bright blue on Windows as the normal blue color is illegible
+if (isSimpleWindowsTerm) {
+ ansiStyles.blue.open = '\u001b[94m';
+}
+
+var styles = (function () {
+ var ret = {};
+
+ Object.keys(ansiStyles).forEach(function (key) {
+ ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
+
+ ret[key] = {
+ get: function () {
+ return build.call(this, this._styles.concat(key));
+ }
+ };
+ });
+
+ return ret;
+})();
+
+var proto = defineProps(function chalk() {}, styles);
+
+function build(_styles) {
+ var builder = function () {
+ return applyStyle.apply(builder, arguments);
+ };
+
+ builder._styles = _styles;
+ builder.enabled = this.enabled;
+ // __proto__ is used because we must return a function, but there is
+ // no way to create a function with a different prototype.
+ /* eslint-disable no-proto */
+ builder.__proto__ = proto;
+
+ return builder;
+}
+
+function applyStyle() {
+ // support varags, but simply cast to string in case there's only one arg
+ var args = arguments;
+ var argsLen = args.length;
+ var str = argsLen !== 0 && String(arguments[0]);
+
+ if (argsLen > 1) {
+ // don't slice `arguments`, it prevents v8 optimizations
+ for (var a = 1; a < argsLen; a++) {
+ str += ' ' + args[a];
+ }
+ }
+
+ if (!this.enabled || !str) {
+ return str;
+ }
+
+ var nestedStyles = this._styles;
+ var i = nestedStyles.length;
+
+ // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
+ // see https://github.com/chalk/chalk/issues/58
+ // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
+ var originalDim = ansiStyles.dim.open;
+ if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
+ ansiStyles.dim.open = '';
+ }
+
+ while (i--) {
+ var code = ansiStyles[nestedStyles[i]];
+
+ // Replace any instances already present with a re-opening code
+ // otherwise only the part of the string until said closing code
+ // will be colored, and the rest will simply be 'plain'.
+ str = code.open + str.replace(code.closeRe, code.open) + code.close;
+ }
+
+ // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
+ ansiStyles.dim.open = originalDim;
+
+ return str;
+}
+
+function init() {
+ var ret = {};
+
+ Object.keys(styles).forEach(function (name) {
+ ret[name] = {
+ get: function () {
+ return build.call(this, [name]);
+ }
+ };
+ });
+
+ return ret;
+}
+
+defineProps(Chalk.prototype, init());
+
+module.exports = new Chalk();
+module.exports.styles = ansiStyles;
+module.exports.hasColor = hasAnsi;
+module.exports.stripColor = stripAnsi;
+module.exports.supportsColor = supportsColor;
diff --git a/node_modules/chalk/license b/node_modules/chalk/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/chalk/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus (sindresorhus.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/chalk/node_modules/supports-color/index.js b/node_modules/chalk/node_modules/supports-color/index.js
new file mode 100644
index 0000000..4346e27
--- /dev/null
+++ b/node_modules/chalk/node_modules/supports-color/index.js
@@ -0,0 +1,50 @@
+'use strict';
+var argv = process.argv;
+
+var terminator = argv.indexOf('--');
+var hasFlag = function (flag) {
+ flag = '--' + flag;
+ var pos = argv.indexOf(flag);
+ return pos !== -1 && (terminator !== -1 ? pos < terminator : true);
+};
+
+module.exports = (function () {
+ if ('FORCE_COLOR' in process.env) {
+ return true;
+ }
+
+ if (hasFlag('no-color') ||
+ hasFlag('no-colors') ||
+ hasFlag('color=false')) {
+ return false;
+ }
+
+ if (hasFlag('color') ||
+ hasFlag('colors') ||
+ hasFlag('color=true') ||
+ hasFlag('color=always')) {
+ return true;
+ }
+
+ if (process.stdout && !process.stdout.isTTY) {
+ return false;
+ }
+
+ if (process.platform === 'win32') {
+ return true;
+ }
+
+ if ('COLORTERM' in process.env) {
+ return true;
+ }
+
+ if (process.env.TERM === 'dumb') {
+ return false;
+ }
+
+ if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
+ return true;
+ }
+
+ return false;
+})();
diff --git a/node_modules/chalk/node_modules/supports-color/license b/node_modules/chalk/node_modules/supports-color/license
new file mode 100644
index 0000000..654d0bf
--- /dev/null
+++ b/node_modules/chalk/node_modules/supports-color/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Sindre Sorhus (sindresorhus.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/chalk/node_modules/supports-color/package.json b/node_modules/chalk/node_modules/supports-color/package.json
new file mode 100644
index 0000000..3bb77ac
--- /dev/null
+++ b/node_modules/chalk/node_modules/supports-color/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "supports-color",
+ "version": "2.0.0",
+ "description": "Detect whether a terminal supports color",
+ "license": "MIT",
+ "repository": "chalk/supports-color",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "maintainers": [
+ "Sindre Sorhus (sindresorhus.com)",
+ "Joshua Appelman (jbnicolai.com)"
+ ],
+ "engines": {
+ "node": ">=0.8.0"
+ },
+ "scripts": {
+ "test": "mocha"
+ },
+ "files": [
+ "index.js"
+ ],
+ "keywords": [
+ "color",
+ "colour",
+ "colors",
+ "terminal",
+ "console",
+ "cli",
+ "ansi",
+ "styles",
+ "tty",
+ "rgb",
+ "256",
+ "shell",
+ "xterm",
+ "command-line",
+ "support",
+ "supports",
+ "capability",
+ "detect"
+ ],
+ "devDependencies": {
+ "mocha": "*",
+ "require-uncached": "^1.0.2"
+ }
+}
diff --git a/node_modules/chalk/node_modules/supports-color/readme.md b/node_modules/chalk/node_modules/supports-color/readme.md
new file mode 100644
index 0000000..b4761f1
--- /dev/null
+++ b/node_modules/chalk/node_modules/supports-color/readme.md
@@ -0,0 +1,36 @@
+# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
+
+> Detect whether a terminal supports color
+
+
+## Install
+
+```
+$ npm install --save supports-color
+```
+
+
+## Usage
+
+```js
+var supportsColor = require('supports-color');
+
+if (supportsColor) {
+ console.log('Terminal supports color');
+}
+```
+
+It obeys the `--color` and `--no-color` CLI flags.
+
+For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
+
+
+## Related
+
+- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
+- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
+
+
+## License
+
+MIT © [Sindre Sorhus](http://sindresorhus.com)
diff --git a/node_modules/chalk/package.json b/node_modules/chalk/package.json
new file mode 100644
index 0000000..2b5881e
--- /dev/null
+++ b/node_modules/chalk/package.json
@@ -0,0 +1,70 @@
+{
+ "name": "chalk",
+ "version": "1.1.3",
+ "description": "Terminal string styling done right. Much color.",
+ "license": "MIT",
+ "repository": "chalk/chalk",
+ "maintainers": [
+ "Sindre Sorhus (sindresorhus.com)",
+ "Joshua Appelman (jbnicolai.com)",
+ "JD Ballard (github.com/qix-)"
+ ],
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "scripts": {
+ "test": "xo && mocha",
+ "bench": "matcha benchmark.js",
+ "coverage": "nyc npm test && nyc report",
+ "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
+ },
+ "files": [
+ "index.js"
+ ],
+ "keywords": [
+ "color",
+ "colour",
+ "colors",
+ "terminal",
+ "console",
+ "cli",
+ "string",
+ "str",
+ "ansi",
+ "style",
+ "styles",
+ "tty",
+ "formatting",
+ "rgb",
+ "256",
+ "shell",
+ "xterm",
+ "log",
+ "logging",
+ "command-line",
+ "text"
+ ],
+ "dependencies": {
+ "ansi-styles": "^2.2.1",
+ "escape-string-regexp": "^1.0.2",
+ "has-ansi": "^2.0.0",
+ "strip-ansi": "^3.0.0",
+ "supports-color": "^2.0.0"
+ },
+ "devDependencies": {
+ "coveralls": "^2.11.2",
+ "matcha": "^0.6.0",
+ "mocha": "*",
+ "nyc": "^3.0.0",
+ "require-uncached": "^1.0.2",
+ "resolve-from": "^1.0.0",
+ "semver": "^4.3.3",
+ "xo": "*"
+ },
+ "xo": {
+ "envs": [
+ "node",
+ "mocha"
+ ]
+ }
+}
diff --git a/node_modules/chalk/readme.md b/node_modules/chalk/readme.md
new file mode 100644
index 0000000..5cf111e
--- /dev/null
+++ b/node_modules/chalk/readme.md
@@ -0,0 +1,213 @@
+
+
+
+
+
+
+
+
+
+> Terminal string styling done right
+
+[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
+[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
+[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
+
+
+[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
+
+**Chalk is a clean and focused alternative.**
+
+![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
+
+
+## Why
+
+- Highly performant
+- Doesn't extend `String.prototype`
+- Expressive API
+- Ability to nest styles
+- Clean and focused
+- Auto-detects color support
+- Actively maintained
+- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
+
+
+## Install
+
+```
+$ npm install --save chalk
+```
+
+
+## Usage
+
+Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
+
+```js
+var chalk = require('chalk');
+
+// style a string
+chalk.blue('Hello world!');
+
+// combine styled and normal strings
+chalk.blue('Hello') + 'World' + chalk.red('!');
+
+// compose multiple styles using the chainable API
+chalk.blue.bgRed.bold('Hello world!');
+
+// pass in multiple arguments
+chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
+
+// nest styles
+chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
+
+// nest styles of the same type even (color, underline, background)
+chalk.green(
+ 'I am a green line ' +
+ chalk.blue.underline.bold('with a blue substring') +
+ ' that becomes green again!'
+);
+```
+
+Easily define your own themes.
+
+```js
+var chalk = require('chalk');
+var error = chalk.bold.red;
+console.log(error('Error!'));
+```
+
+Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
+
+```js
+var name = 'Sindre';
+console.log(chalk.green('Hello %s'), name);
+//=> Hello Sindre
+```
+
+
+## API
+
+### chalk.`
+
+
+
+
+
+